@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,77 +1,77 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var sy=Object.create;var
|
|
5
|
-
`)}}
|
|
6
|
-
`)
|
|
4
|
+
var sy=Object.create;var Cd=Object.defineProperty;var cy=Object.getOwnPropertyDescriptor;var ly=Object.getOwnPropertyNames;var uy=Object.getPrototypeOf,dy=Object.prototype.hasOwnProperty;var ra=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var P=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var fy=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ly(t))!dy.call(e,n)&&n!==i&&Cd(e,n,{get:()=>t[n],enumerable:!(r=cy(t,n))||r.enumerable});return e};var _r=(e,t,i)=>(i=e!=null?sy(uy(e)):{},fy(t||!e||!e.__esModule?Cd(i,"default",{value:e,enumerable:!0}):i,e));var F=P(fe=>{"use strict";var Es=Symbol.for("yaml.alias"),Pd=Symbol.for("yaml.document"),na=Symbol.for("yaml.map"),Rd=Symbol.for("yaml.pair"),Cs=Symbol.for("yaml.scalar"),aa=Symbol.for("yaml.seq"),wt=Symbol.for("yaml.node.type"),wy=e=>!!e&&typeof e=="object"&&e[wt]===Es,yy=e=>!!e&&typeof e=="object"&&e[wt]===Pd,Ny=e=>!!e&&typeof e=="object"&&e[wt]===na,by=e=>!!e&&typeof e=="object"&&e[wt]===Rd,Ad=e=>!!e&&typeof e=="object"&&e[wt]===Cs,ky=e=>!!e&&typeof e=="object"&&e[wt]===aa;function _d(e){if(e&&typeof e=="object")switch(e[wt]){case na:case aa:return!0}return!1}function Sy(e){if(e&&typeof e=="object")switch(e[wt]){case Es:case na:case Cs:case aa:return!0}return!1}var Ey=e=>(Ad(e)||_d(e))&&!!e.anchor;fe.ALIAS=Es;fe.DOC=Pd;fe.MAP=na;fe.NODE_TYPE=wt;fe.PAIR=Rd;fe.SCALAR=Cs;fe.SEQ=aa;fe.hasAnchor=Ey;fe.isAlias=wy;fe.isCollection=_d;fe.isDocument=yy;fe.isMap=Ny;fe.isNode=Sy;fe.isPair=by;fe.isScalar=Ad;fe.isSeq=ky});var jr=P(xs=>{"use strict";var ce=F(),ke=Symbol("break visit"),Id=Symbol("skip children"),ot=Symbol("remove node");function oa(e,t){let i=Td(t);ce.isDocument(e)?Hi(null,e.contents,i,Object.freeze([e]))===ot&&(e.contents=null):Hi(null,e,i,Object.freeze([]))}oa.BREAK=ke;oa.SKIP=Id;oa.REMOVE=ot;function Hi(e,t,i,r){let n=jd(e,t,i,r);if(ce.isNode(n)||ce.isPair(n))return $d(e,r,n),Hi(e,n,i,r);if(typeof n!="symbol"){if(ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=Hi(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ke)return ke;o===ot&&(t.items.splice(a,1),a-=1)}}}else if(ce.isPair(t)){r=Object.freeze(r.concat(t));let a=Hi("key",t.key,i,r);if(a===ke)return ke;a===ot&&(t.key=null);let o=Hi("value",t.value,i,r);if(o===ke)return ke;o===ot&&(t.value=null)}}return n}async function sa(e,t){let i=Td(t);ce.isDocument(e)?await Di(null,e.contents,i,Object.freeze([e]))===ot&&(e.contents=null):await Di(null,e,i,Object.freeze([]))}sa.BREAK=ke;sa.SKIP=Id;sa.REMOVE=ot;async function Di(e,t,i,r){let n=await jd(e,t,i,r);if(ce.isNode(n)||ce.isPair(n))return $d(e,r,n),Di(e,n,i,r);if(typeof n!="symbol"){if(ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await Di(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ke)return ke;o===ot&&(t.items.splice(a,1),a-=1)}}}else if(ce.isPair(t)){r=Object.freeze(r.concat(t));let a=await Di("key",t.key,i,r);if(a===ke)return ke;a===ot&&(t.key=null);let o=await Di("value",t.value,i,r);if(o===ke)return ke;o===ot&&(t.value=null)}}return n}function Td(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 jd(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(ce.isMap(t))return i.Map?.(e,t,r);if(ce.isSeq(t))return i.Seq?.(e,t,r);if(ce.isPair(t))return i.Pair?.(e,t,r);if(ce.isScalar(t))return i.Scalar?.(e,t,r);if(ce.isAlias(t))return i.Alias?.(e,t,r)}function $d(e,t,i){let r=t[t.length-1];if(ce.isCollection(r))r.items[e]=i;else if(ce.isPair(r))e==="key"?r.key=i:r.value=i;else if(ce.isDocument(r))r.contents=i;else{let n=ce.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}xs.visit=oa;xs.visitAsync=sa});var Ps=P(Hd=>{"use strict";var Od=F(),Cy=jr(),xy={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Py=e=>e.replace(/[!,[\]{}]/g,t=>xy[t]),$r=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+Py(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&Od.isNode(t.contents)){let a={};Cy.visit(t.contents,(o,s)=>{Od.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
|
|
5
|
+
`)}};$r.defaultYaml={explicit:!1,version:"1.2"};$r.defaultTags={"!!":"tag:yaml.org,2002:"};Hd.Directives=$r});var ca=P(Or=>{"use strict";var Dd=F(),Ry=jr();function Ay(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function Ld(e){let t=new Set;return Ry.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Bd(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function _y(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Ld(e));let o=Bd(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Dd.isScalar(o.node)||Dd.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:r}}Or.anchorIsValid=Ay;Or.anchorNames=Ld;Or.createNodeAnchors=_y;Or.findNewAnchor=Bd});var Rs=P(Vd=>{"use strict";function Hr(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=Hr(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=Hr(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=Hr(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=Hr(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}Vd.applyReviver=Hr});var Lt=P(qd=>{"use strict";var Iy=F();function Fd(e,t,i){if(Array.isArray(e))return e.map((r,n)=>Fd(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!Iy.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}qd.toJS=Fd});var la=P(Wd=>{"use strict";var Ty=Rs(),Md=F(),jy=Lt(),As=class{constructor(t){Object.defineProperty(this,Md.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!Md.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=jy.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Ty.applyReviver(a,{"":s},"",s):s}};Wd.NodeBase=As});var Dr=P(zd=>{"use strict";var $y=ca(),Oy=jr(),Li=F(),Hy=la(),Dy=Lt(),_s=class extends Hy.NodeBase{constructor(t){super(Li.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],Oy.visit(t,{Node:(a,o)=>{(Li.isAlias(o)||Li.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(Dy.toJS(o,null,i),s=r.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=ua(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if($y.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 ua(e,t,i){if(Li.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Li.isCollection(t)){let r=0;for(let n of t.items){let a=ua(e,n,i);a>r&&(r=a)}return r}else if(Li.isPair(t)){let r=ua(e,t.key,i),n=ua(e,t.value,i);return Math.max(r,n)}return 1}zd.Alias=_s});var re=P(Is=>{"use strict";var Ly=F(),By=la(),Vy=Lt(),Fy=e=>!e||typeof e!="function"&&typeof e!="object",Bt=class extends By.NodeBase{constructor(t){super(Ly.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:Vy.toJS(this.value,t,i)}toString(){return String(this.value)}};Bt.BLOCK_FOLDED="BLOCK_FOLDED";Bt.BLOCK_LITERAL="BLOCK_LITERAL";Bt.PLAIN="PLAIN";Bt.QUOTE_DOUBLE="QUOTE_DOUBLE";Bt.QUOTE_SINGLE="QUOTE_SINGLE";Is.Scalar=Bt;Is.isScalarValue=Fy});var Lr=P(Gd=>{"use strict";var qy=Dr(),wi=F(),Jd=re(),My="tag:yaml.org,2002:";function Wy(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function zy(e,t,i){if(wi.isDocument(e)&&(e=e.contents),wi.isNode(e))return e;if(wi.isPair(e)){let d=i.schema[wi.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new qy.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=My+t.slice(2));let l=Wy(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Jd.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[wi.MAP]:Symbol.iterator in Object(e)?o[wi.SEQ]:o[wi.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new Jd.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Gd.createNode=zy});var fa=P(da=>{"use strict";var Jy=Lr(),st=F(),Gy=la();function Ts(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return Jy.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Ud=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,js=class extends Gy.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>st.isNode(r)||st.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Ud(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(st.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Ts(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(st.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&st.isScalar(a)?a.value:a:st.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!st.isPair(i))return!1;let r=i.value;return r==null||t&&st.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return st.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(st.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Ts(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};da.Collection=js;da.collectionFromPath=Ts;da.isEmptyPath=Ud});var Br=P(pa=>{"use strict";var Uy=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function $s(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ky=(e,t,i)=>e.endsWith(`
|
|
6
|
+
`)?$s(i,t):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
|
|
9
|
-
`)i===
|
|
8
|
+
`+$s(i,t):(e.endsWith(" ")?"":" ")+i;pa.indentComment=$s;pa.lineComment=Ky;pa.stringifyComment=Uy});var Yd=P(Vr=>{"use strict";var Yy="flow",Os="block",ha="quoted";function Xy(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,p,v=!1,h=-1,m=-1,S=-1;i===Os&&(h=Kd(e,h,t.length),h!==-1&&(d=h+c));for(let N;N=e[h+=1];){if(i===ha&&N==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}S=h}if(N===`
|
|
9
|
+
`)i===Os&&(h=Kd(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(N===" "&&p&&p!==" "&&p!==`
|
|
10
10
|
`&&p!==" "){let k=e[h+1];k&&k!==" "&&k!==`
|
|
11
|
-
`&&k!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===
|
|
12
|
-
${t}${e.slice(0,E)}`:(i===
|
|
13
|
-
${t}${e.slice(k+1,E)}`)}return y}function
|
|
14
|
-
`);r=t,n=t+1,a=e[n]}return r}
|
|
15
|
-
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function
|
|
11
|
+
`&&k!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===ha){for(;p===" "||p===" ";)p=N,N=e[h+=1],v=!0;let k=h>S+1?h-2:m-1;if(u[k])return e;l.push(k),u[k]=!0,d=k+c,f=void 0}else v=!0}p=N}if(v&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let N=0;N<l.length;++N){let k=l[N],E=l[N+1]||e.length;k===0?y=`
|
|
12
|
+
${t}${e.slice(0,E)}`:(i===ha&&u[k]&&(y+=`${e[k]}\\`),y+=`
|
|
13
|
+
${t}${e.slice(k+1,E)}`)}return y}function Kd(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
+
`);r=t,n=t+1,a=e[n]}return r}Vr.FOLD_BLOCK=Os;Vr.FOLD_FLOW=Yy;Vr.FOLD_QUOTED=ha;Vr.foldFlowLines=Xy});var qr=P(Xd=>{"use strict";var Je=re(),Vt=Yd(),va=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ga=e=>/^(%|---|\.\.\.)/m.test(e);function Qy(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Fr(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(ga(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:Vt.foldFlowLines(o,a,Vt.FOLD_QUOTED,
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
20
|
-
${i}`)+"'";return t.implicitKey?r:Vt.foldFlowLines(r,i,Vt.FOLD_FLOW,
|
|
18
|
+
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:Vt.foldFlowLines(o,a,Vt.FOLD_QUOTED,va(t,!1))}function Hs(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Fr(e,t);let i=t.indent||(ga(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return t.implicitKey?r:Vt.foldFlowLines(r,i,Vt.FOLD_FLOW,va(t,!1))}function Bi(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=Fr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=Hs:a&&!n?r=Fr:r=i?Hs:Fr}return r(e,t)}var Ds;try{Ds=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{Ds=/\n+(?!\n|$)/g}function ma({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return Bi(i,r);let l=r.indent||(r.forceBlockIndent||ga(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Je.Scalar.BLOCK_FOLDED?!1:t===Je.Scalar.BLOCK_LITERAL?!0:!Qy(i,c,l.length);if(!i)return u?`|
|
|
24
24
|
`:`>
|
|
25
25
|
`;let d,f;for(f=i.length;f>0;--f){let E=i[f-1];if(E!==`
|
|
26
26
|
`&&E!==" "&&E!==" ")break}let p=i.substring(f),v=p.indexOf(`
|
|
27
27
|
`);v===-1?d="-":i===p||v!==p.length-1?(d="+",a&&a()):d="",p&&(i=i.slice(0,-p.length),p[p.length-1]===`
|
|
28
|
-
`&&(p=p.slice(0,-1)),p=p.replace(
|
|
28
|
+
`&&(p=p.slice(0,-1)),p=p.replace(Ds,`$&${l}`));let h=!1,m,S=-1;for(m=0;m<i.length;++m){let E=i[m];if(E===" ")h=!0;else if(E===`
|
|
29
29
|
`)S=m;else break}let y=i.substring(0,S<m?S+1:m);y&&(i=i.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let k=(h?l?"2":"1":"")+d;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let E=i.replace(/\n+/g,`
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,x=
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,x=va(r,!0);o!=="folded"&&t!==Je.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{b=!0});let g=Vt.foldFlowLines(`${y}${E}${p}`,l,Vt.FOLD_BLOCK,x);if(!b)return`>${k}
|
|
31
31
|
${l}${g}`}return i=i.replace(/\n+/g,`$&${l}`),`|${k}
|
|
32
32
|
${l}${y}${i}${p}`}function Zy(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
33
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return
|
|
37
|
-
${t.indent}${s}`:s}
|
|
38
|
-
${s}:`):(m=`${m}:`,f&&(m+=
|
|
33
|
+
`)||u&&/[[\]{},]/.test(a))return Bi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
+
`)?Bi(a,t):ma(e,t,i,r);if(!s&&!u&&n!==Je.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return ma(e,t,i,r);if(ga(a)){if(c==="")return t.forceBlockIndent=!0,ma(e,t,i,r);if(s&&c===l)return Bi(a,t)}let d=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return Bi(a,t)}return s?d:Vt.foldFlowLines(d,c,Vt.FOLD_FLOW,va(t,!1))}function eN(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Je.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Je.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Je.Scalar.BLOCK_FOLDED:case Je.Scalar.BLOCK_LITERAL:return n||a?Bi(o.value,t):ma(o,t,i,r);case Je.Scalar.QUOTE_DOUBLE:return Fr(o.value,t);case Je.Scalar.QUOTE_SINGLE:return Hs(o.value,t);case Je.Scalar.PLAIN:return Zy(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Xd.stringifyString=eN});var Mr=P(Ls=>{"use strict";var tN=ca(),Ft=F(),iN=Br(),rN=qr();function nN(e,t){let i=Object.assign({blockQuote:!0,commentString:iN.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function aN(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(Ft.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function oN(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Ft.isScalar(e)||Ft.isCollection(e))&&e.anchor;a&&tN.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function sN(e,t,i,r){if(Ft.isPair(e))return e.toString(t,i,r);if(Ft.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=Ft.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=aN(t.doc.schema.tags,a));let o=oN(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):Ft.isScalar(a)?rN.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Ft.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}Ls.createStringifyContext=nN;Ls.stringify=sN});var tf=P(ef=>{"use strict";var yt=F(),Qd=re(),Zd=Mr(),Wr=Br();function cN({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=yt.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(yt.isCollection(e)||!yt.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!d&&(!e||f&&t==null&&!i.inFlow||yt.isCollection(e)||(yt.isScalar(e)?e.type===Qd.Scalar.BLOCK_FOLDED||e.type===Qd.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=Zd.stringify(e,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=Wr.lineComment(m,i.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=Wr.lineComment(m,i.indent,l(f))),m=`? ${m}
|
|
38
|
+
${s}:`):(m=`${m}:`,f&&(m+=Wr.lineComment(m,i.indent,l(f))));let S,y,N;yt.isNode(t)?(S=!!t.spaceBefore,y=t.commentBefore,N=t.comment):(S=!1,y=null,N=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!f&&yt.isScalar(t)&&(i.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&yt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let k=!1,E=Zd.stringify(t,i,()=>k=!0,()=>h=!0),b=" ";if(f||S||y){if(b=S?`
|
|
39
39
|
`:"",y){let x=l(y);b+=`
|
|
40
|
-
${
|
|
40
|
+
${Wr.indentComment(x,i.indent)}`}E===""&&!i.inFlow?b===`
|
|
41
41
|
`&&N&&(b=`
|
|
42
42
|
|
|
43
43
|
`):b+=`
|
|
44
44
|
${i.indent}`}else if(!p&&yt.isCollection(t)){let x=E[0],g=E.indexOf(`
|
|
45
45
|
`),w=g!==-1,C=i.inFlow??t.flow??t.items.length===0;if(w||!C){let O=!1;if(w&&(x==="&"||x==="!")){let T=E.indexOf(" ");x==="&"&&T!==-1&&T<g&&E[T+1]==="!"&&(T=E.indexOf(" ",T+1)),(T===-1||g<T)&&(O=!0)}O||(b=`
|
|
46
46
|
${i.indent}`)}}else(E===""||E[0]===`
|
|
47
|
-
`)&&(b="");return m+=b+E,i.inFlow?k&&r&&r():N&&!k?m+=
|
|
47
|
+
`)&&(b="");return m+=b+E,i.inFlow?k&&r&&r():N&&!k?m+=Wr.lineComment(m,i.indent,l(N)):h&&n&&n(),m}ef.stringifyPair=cN});var Vs=P(Bs=>{"use strict";var rf=ra("process");function lN(e,...t){e==="debug"&&console.log(...t)}function uN(e,t){(e==="debug"||e==="warn")&&(typeof rf.emitWarning=="function"?rf.emitWarning(t):console.warn(t))}Bs.debug=lN;Bs.warn=uN});var ka=P(ba=>{"use strict";var Na=F(),nf=re(),wa="<<",ya={identify:e=>e===wa||typeof e=="symbol"&&e.description===wa,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new nf.Scalar(Symbol(wa)),{addToJSMap:af}),stringify:()=>wa},dN=(e,t)=>(ya.identify(t)||Na.isScalar(t)&&(!t.type||t.type===nf.Scalar.PLAIN)&&ya.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===ya.tag&&i.default);function af(e,t,i){let r=of(e,i);if(Na.isSeq(r))for(let n of r.items)Fs(e,t,n);else if(Array.isArray(r))for(let n of r)Fs(e,t,n);else Fs(e,t,r)}function Fs(e,t,i){let r=of(e,i);if(!Na.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function of(e,t){return e&&Na.isAlias(t)?t.resolve(e.doc,e):t}ba.addMergeToJSMap=af;ba.isMergeKey=dN;ba.merge=ya});var Ms=P(lf=>{"use strict";var fN=Vs(),sf=ka(),pN=Mr(),cf=F(),qs=Lt();function hN(e,t,{key:i,value:r}){if(cf.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(sf.isMergeKey(e,i))sf.addMergeToJSMap(e,t,r);else{let n=qs.toJS(i,"",e);if(t instanceof Map)t.set(n,qs.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=mN(i,n,e),o=qs.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function mN(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(cf.isNode(e)&&i?.doc){let r=pN.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),fN.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}lf.addPairToJSMap=hN});var qt=P(Ws=>{"use strict";var uf=Lr(),vN=tf(),gN=Ms(),Sa=F();function wN(e,t,i){let r=uf.createNode(e,void 0,i),n=uf.createNode(t,void 0,i);return new Ea(r,n)}var Ea=class e{constructor(t,i=null){Object.defineProperty(this,Sa.NODE_TYPE,{value:Sa.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return Sa.isNode(i)&&(i=i.clone(t)),Sa.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return gN.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?vN.stringifyPair(this,t,i,r):JSON.stringify(this)}};Ws.Pair=Ea;Ws.createPair=wN});var zs=P(ff=>{"use strict";var yi=F(),df=Mr(),Ca=Br();function yN(e,t,i){return(t.inFlow??e.flow?bN:NN)(e,t,i)}function NN({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(yi.isNode(h))!d&&h.spaceBefore&&f.push(""),xa(i,f,h.commentBefore,d),h.comment&&(m=h.comment);else if(yi.isPair(h)){let y=yi.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&f.push(""),xa(i,f,y.commentBefore,d))}d=!1;let S=df.stringify(h,u,()=>m=null,()=>d=!0);m&&(S+=Ca.lineComment(S,a,l(m))),d&&m&&(d=!1),f.push(r+S)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let v=1;v<f.length;++v){let h=f[v];p+=h?`
|
|
48
48
|
${c}${h}`:`
|
|
49
49
|
`}}return e?(p+=`
|
|
50
|
-
`+
|
|
51
|
-
`)),v<e.length-1?S+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,N)=>y+N.length+2,2)+(S.length+2)>t.options.lineWidth)),l&&(S+=",")),m&&(S+=
|
|
50
|
+
`+Ca.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function bN({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(yi.isNode(h))h.spaceBefore&&d.push(""),xa(t,d,h.commentBefore,!1),h.comment&&(m=h.comment);else if(yi.isPair(h)){let y=yi.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),xa(t,d,y.commentBefore,!1),y.comment&&(l=!0));let N=yi.isNode(h.value)?h.value:null;N?(N.comment&&(m=N.comment),N.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(m=y.comment)}m&&(l=!0);let S=df.stringify(h,c,()=>m=null);l||(l=d.length>u||S.includes(`
|
|
51
|
+
`)),v<e.length-1?S+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,N)=>y+N.length+2,2)+(S.length+2)>t.options.lineWidth)),l&&(S+=",")),m&&(S+=Ca.lineComment(S,r,s(m))),d.push(S),u=d.length}let{start:f,end:p}=i;if(d.length===0)return f+p;if(!l){let v=d.reduce((h,m)=>h+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let h of d)v+=h?`
|
|
52
52
|
${a}${n}${h}`:`
|
|
53
53
|
`;return`${v}
|
|
54
|
-
${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function
|
|
55
|
-
`:" ")}return nb.stringifyString({comment:e,type:t,value:s},r,n,a)}};
|
|
54
|
+
${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function xa({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Ca.indentComment(t(r),e);i.push(a.trimStart())}}ff.stringifyCollection=yN});var Wt=P(Gs=>{"use strict";var kN=zs(),SN=Ms(),EN=fa(),Mt=F(),Pa=qt(),CN=re();function zr(e,t){let i=Mt.isScalar(t)?t.value:t;for(let r of e)if(Mt.isPair(r)&&(r.key===t||r.key===i||Mt.isScalar(r.key)&&r.key.value===i))return r}var Js=class extends EN.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Mt.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Pa.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;Mt.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Pa.Pair(t,t?.value):r=new Pa.Pair(t.key,t.value);let n=zr(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Mt.isScalar(n.value)&&CN.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=zr(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=zr(this.items,t)?.value;return(!i&&Mt.isScalar(n)?n.value:n)??void 0}has(t){return!!zr(this.items,t)}set(t,i){this.add(new Pa.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)SN.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Mt.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})),kN.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Gs.YAMLMap=Js;Gs.findPair=zr});var Vi=P(hf=>{"use strict";var xN=F(),pf=Wt(),PN={collection:"map",default:!0,nodeClass:pf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return xN.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>pf.YAMLMap.from(e,t,i)};hf.map=PN});var zt=P(mf=>{"use strict";var RN=Lr(),AN=zs(),_N=fa(),Aa=F(),IN=re(),TN=Lt(),Us=class extends _N.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Aa.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Ra(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Ra(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Aa.isScalar(n)?n.value:n}has(t){let i=Ra(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Ra(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Aa.isScalar(n)&&IN.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(TN.toJS(a,String(n++),i));return r}toString(t,i,r){return t?AN.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(RN.createNode(s,void 0,r))}}return a}};function Ra(e){let t=Aa.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}mf.YAMLSeq=Us});var Fi=P(gf=>{"use strict";var jN=F(),vf=zt(),$N={collection:"seq",default:!0,nodeClass:vf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return jN.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>vf.YAMLSeq.from(e,t,i)};gf.seq=$N});var Jr=P(wf=>{"use strict";var ON=qr(),HN={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),ON.stringifyString(e,t,i,r)}};wf.string=HN});var _a=P(bf=>{"use strict";var yf=re(),Nf={identify:e=>e==null,createNode:()=>new yf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new yf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Nf.test.test(e)?e:t.options.nullStr};bf.nullTag=Nf});var Ks=P(Sf=>{"use strict";var DN=re(),kf={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new DN.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&kf.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};Sf.boolTag=kf});var qi=P(Ef=>{"use strict";function LN({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Ef.stringifyNumber=LN});var Xs=P(Ia=>{"use strict";var BN=re(),Ys=qi(),VN={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:Ys.stringifyNumber},FN={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():Ys.stringifyNumber(e)}},qN={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 BN.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Ys.stringifyNumber};Ia.float=qN;Ia.floatExp=FN;Ia.floatNaN=VN});var Zs=P(ja=>{"use strict";var Cf=qi(),Ta=e=>typeof e=="bigint"||Number.isInteger(e),Qs=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function xf(e,t,i){let{value:r}=e;return Ta(r)&&r>=0?i+r.toString(t):Cf.stringifyNumber(e)}var MN={identify:e=>Ta(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Qs(e,2,8,i),stringify:e=>xf(e,8,"0o")},WN={identify:Ta,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Qs(e,0,10,i),stringify:Cf.stringifyNumber},zN={identify:e=>Ta(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Qs(e,2,16,i),stringify:e=>xf(e,16,"0x")};ja.int=WN;ja.intHex=zN;ja.intOct=MN});var Rf=P(Pf=>{"use strict";var JN=Vi(),GN=_a(),UN=Fi(),KN=Jr(),YN=Ks(),ec=Xs(),tc=Zs(),XN=[JN.map,UN.seq,KN.string,GN.nullTag,YN.boolTag,tc.intOct,tc.int,tc.intHex,ec.floatNaN,ec.floatExp,ec.float];Pf.schema=XN});var If=P(_f=>{"use strict";var QN=re(),ZN=Vi(),eb=Fi();function Af(e){return typeof e=="bigint"||Number.isInteger(e)}var $a=({value:e})=>JSON.stringify(e),tb=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:$a},{identify:e=>e==null,createNode:()=>new QN.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:$a},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:$a},{identify:Af,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>Af(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:$a}],ib={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},rb=[ZN.map,eb.seq].concat(tb,ib);_f.schema=rb});var rc=P(Tf=>{"use strict";var Gr=ra("buffer"),ic=re(),nb=qr(),ab={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Gr.Buffer=="function")return Gr.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof Gr.Buffer=="function")s=o instanceof Gr.Buffer?o.toString("base64"):Gr.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=ic.Scalar.BLOCK_LITERAL),t!==ic.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===ic.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return nb.stringifyString({comment:e,type:t,value:s},r,n,a)}};Tf.binary=ab});var Da=P(Ha=>{"use strict";var Oa=F(),nc=qt(),ob=re(),sb=zt();function jf(e,t){if(Oa.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!Oa.isPair(r)){if(Oa.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new nc.Pair(new ob.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
|
|
56
56
|
${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
|
|
57
|
-
${a.comment}`:r.comment}r=n}e.items[i]=$a.isPair(r)?r:new ic.Pair(r)}}else t("Expected a sequence for this tag");return e}function Of(e,t,i){let{replacer:r}=i,n=new sb.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(ic.createPair(s,c,i))}return n}var cb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:$f,createNode:Of};Oa.createPairs=Of;Oa.pairs=cb;Oa.resolvePairs=$f});var ac=P(nc=>{"use strict";var Hf=F(),rc=Lt(),Jr=Wt(),lb=zt(),Df=Ha(),Ni=class e extends lb.YAMLSeq{constructor(){super(),this.add=Jr.YAMLMap.prototype.add.bind(this),this.delete=Jr.YAMLMap.prototype.delete.bind(this),this.get=Jr.YAMLMap.prototype.get.bind(this),this.has=Jr.YAMLMap.prototype.has.bind(this),this.set=Jr.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(Hf.isPair(n)?(a=rc.toJS(n.key,"",i),o=rc.toJS(n.value,a,i)):a=rc.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=Df.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Ni.tag="tag:yaml.org,2002:omap";var ub={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ni,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Df.resolvePairs(e,t),r=[];for(let{key:n}of i.items)Hf.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Ni,i)},createNode:(e,t,i)=>Ni.from(e,t,i)};nc.YAMLOMap=Ni;nc.omap=ub});var qf=P(oc=>{"use strict";var Lf=re();function Bf({value:e,source:t},i){return t&&(e?Vf:Ff).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Vf={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 Lf.Scalar(!0),stringify:Bf},Ff={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 Lf.Scalar(!1),stringify:Bf};oc.falseTag=Ff;oc.trueTag=Vf});var Mf=P(Da=>{"use strict";var db=re(),sc=Fi(),fb={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:sc.stringifyNumber},pb={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():sc.stringifyNumber(e)}},hb={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 db.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:sc.stringifyNumber};Da.float=hb;Da.floatExp=pb;Da.floatNaN=fb});var zf=P(Ur=>{"use strict";var Wf=Fi(),Gr=e=>typeof e=="bigint"||Number.isInteger(e);function La(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function cc(e,t,i){let{value:r}=e;if(Gr(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Wf.stringifyNumber(e)}var mb={identify:Gr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>La(e,2,2,i),stringify:e=>cc(e,2,"0b")},vb={identify:Gr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>La(e,1,8,i),stringify:e=>cc(e,8,"0")},gb={identify:Gr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>La(e,0,10,i),stringify:Wf.stringifyNumber},wb={identify:Gr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>La(e,2,16,i),stringify:e=>cc(e,16,"0x")};Ur.int=gb;Ur.intBin=mb;Ur.intHex=wb;Ur.intOct=vb});var uc=P(lc=>{"use strict";var Fa=F(),Ba=qt(),Va=Wt(),bi=class e extends Va.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Fa.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Ba.Pair(t.key,null):i=new Ba.Pair(t,null),Va.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Va.findPair(this.items,t);return!i&&Fa.isPair(r)?Fa.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Va.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Ba.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Ba.createPair(o,null,r));return a}};bi.tag="tag:yaml.org,2002:set";var yb={collection:"map",identify:e=>e instanceof Set,nodeClass:bi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>bi.from(e,t,i),resolve(e,t){if(Fa.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new bi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};lc.YAMLSet=bi;lc.set=yb});var fc=P(qa=>{"use strict";var Nb=Fi();function dc(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Jf(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Nb.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var bb={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>dc(e,i),stringify:Jf},kb={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=>dc(e,!1),stringify:Jf},Gf={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(Gf.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=dc(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};qa.floatTime=kb;qa.intTime=bb;qa.timestamp=Gf});var Yf=P(Kf=>{"use strict";var Sb=Bi(),Eb=Aa(),Cb=Vi(),xb=Wr(),Pb=tc(),Uf=qf(),pc=Mf(),Ma=zf(),Rb=ba(),Ab=ac(),_b=Ha(),Ib=uc(),hc=fc(),Tb=[Sb.map,Cb.seq,xb.string,Eb.nullTag,Uf.trueTag,Uf.falseTag,Ma.intBin,Ma.intOct,Ma.int,Ma.intHex,pc.floatNaN,pc.floatExp,pc.float,Pb.binary,Rb.merge,Ab.omap,_b.pairs,Ib.set,hc.intTime,hc.floatTime,hc.timestamp];Kf.schema=Tb});var op=P(gc=>{"use strict";var ep=Bi(),jb=Aa(),tp=Vi(),$b=Wr(),Ob=Gs(),mc=Ks(),vc=Xs(),Hb=Af(),Db=Tf(),ip=tc(),Kr=ba(),rp=ac(),np=Ha(),Xf=Yf(),ap=uc(),Wa=fc(),Qf=new Map([["core",Hb.schema],["failsafe",[ep.map,tp.seq,$b.string]],["json",Db.schema],["yaml11",Xf.schema],["yaml-1.1",Xf.schema]]),Zf={binary:ip.binary,bool:Ob.boolTag,float:mc.float,floatExp:mc.floatExp,floatNaN:mc.floatNaN,floatTime:Wa.floatTime,int:vc.int,intHex:vc.intHex,intOct:vc.intOct,intTime:Wa.intTime,map:ep.map,merge:Kr.merge,null:jb.nullTag,omap:rp.omap,pairs:np.pairs,seq:tp.seq,set:ap.set,timestamp:Wa.timestamp},Lb={"tag:yaml.org,2002:binary":ip.binary,"tag:yaml.org,2002:merge":Kr.merge,"tag:yaml.org,2002:omap":rp.omap,"tag:yaml.org,2002:pairs":np.pairs,"tag:yaml.org,2002:set":ap.set,"tag:yaml.org,2002:timestamp":Wa.timestamp};function Bb(e,t,i){let r=Qf.get(t);if(r&&!e)return i&&!r.includes(Kr.merge)?r.concat(Kr.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Qf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(Kr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Zf[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Zf).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}gc.coreKnownTags=Lb;gc.getTags=Bb});var Nc=P(sp=>{"use strict";var wc=F(),Vb=Bi(),Fb=Vi(),qb=Wr(),za=op(),Mb=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,yc=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?za.getTags(t,"compat"):t?za.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?za.coreKnownTags:{},this.tags=za.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,wc.MAP,{value:Vb.map}),Object.defineProperty(this,wc.SCALAR,{value:qb.string}),Object.defineProperty(this,wc.SEQ,{value:Fb.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Mb:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};sp.Schema=yc});var lp=P(cp=>{"use strict";var Wb=F(),bc=Fr(),Yr=Dr();function zb(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=bc.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Yr.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Wb.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Yr.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=bc.stringify(e.contents,n,()=>s=null,c);s&&(l+=Yr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(bc.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
-
`)?(i.push("..."),i.push(
|
|
57
|
+
${a.comment}`:r.comment}r=n}e.items[i]=Oa.isPair(r)?r:new nc.Pair(r)}}else t("Expected a sequence for this tag");return e}function $f(e,t,i){let{replacer:r}=i,n=new sb.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(nc.createPair(s,c,i))}return n}var cb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:jf,createNode:$f};Ha.createPairs=$f;Ha.pairs=cb;Ha.resolvePairs=jf});var sc=P(oc=>{"use strict";var Of=F(),ac=Lt(),Ur=Wt(),lb=zt(),Hf=Da(),Ni=class e extends lb.YAMLSeq{constructor(){super(),this.add=Ur.YAMLMap.prototype.add.bind(this),this.delete=Ur.YAMLMap.prototype.delete.bind(this),this.get=Ur.YAMLMap.prototype.get.bind(this),this.has=Ur.YAMLMap.prototype.has.bind(this),this.set=Ur.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(Of.isPair(n)?(a=ac.toJS(n.key,"",i),o=ac.toJS(n.value,a,i)):a=ac.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=Hf.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Ni.tag="tag:yaml.org,2002:omap";var ub={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ni,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Hf.resolvePairs(e,t),r=[];for(let{key:n}of i.items)Of.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Ni,i)},createNode:(e,t,i)=>Ni.from(e,t,i)};oc.YAMLOMap=Ni;oc.omap=ub});var Ff=P(cc=>{"use strict";var Df=re();function Lf({value:e,source:t},i){return t&&(e?Bf:Vf).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Bf={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 Df.Scalar(!0),stringify:Lf},Vf={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 Df.Scalar(!1),stringify:Lf};cc.falseTag=Vf;cc.trueTag=Bf});var qf=P(La=>{"use strict";var db=re(),lc=qi(),fb={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:lc.stringifyNumber},pb={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():lc.stringifyNumber(e)}},hb={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 db.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:lc.stringifyNumber};La.float=hb;La.floatExp=pb;La.floatNaN=fb});var Wf=P(Yr=>{"use strict";var Mf=qi(),Kr=e=>typeof e=="bigint"||Number.isInteger(e);function Ba(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function uc(e,t,i){let{value:r}=e;if(Kr(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Mf.stringifyNumber(e)}var mb={identify:Kr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Ba(e,2,2,i),stringify:e=>uc(e,2,"0b")},vb={identify:Kr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Ba(e,1,8,i),stringify:e=>uc(e,8,"0")},gb={identify:Kr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Ba(e,0,10,i),stringify:Mf.stringifyNumber},wb={identify:Kr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Ba(e,2,16,i),stringify:e=>uc(e,16,"0x")};Yr.int=gb;Yr.intBin=mb;Yr.intHex=wb;Yr.intOct=vb});var fc=P(dc=>{"use strict";var qa=F(),Va=qt(),Fa=Wt(),bi=class e extends Fa.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;qa.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Va.Pair(t.key,null):i=new Va.Pair(t,null),Fa.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Fa.findPair(this.items,t);return!i&&qa.isPair(r)?qa.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Fa.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Va.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Va.createPair(o,null,r));return a}};bi.tag="tag:yaml.org,2002:set";var yb={collection:"map",identify:e=>e instanceof Set,nodeClass:bi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>bi.from(e,t,i),resolve(e,t){if(qa.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new bi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};dc.YAMLSet=bi;dc.set=yb});var hc=P(Ma=>{"use strict";var Nb=qi();function pc(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function zf(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Nb.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var bb={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>pc(e,i),stringify:zf},kb={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=>pc(e,!1),stringify:zf},Jf={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(Jf.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=pc(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Ma.floatTime=kb;Ma.intTime=bb;Ma.timestamp=Jf});var Kf=P(Uf=>{"use strict";var Sb=Vi(),Eb=_a(),Cb=Fi(),xb=Jr(),Pb=rc(),Gf=Ff(),mc=qf(),Wa=Wf(),Rb=ka(),Ab=sc(),_b=Da(),Ib=fc(),vc=hc(),Tb=[Sb.map,Cb.seq,xb.string,Eb.nullTag,Gf.trueTag,Gf.falseTag,Wa.intBin,Wa.intOct,Wa.int,Wa.intHex,mc.floatNaN,mc.floatExp,mc.float,Pb.binary,Rb.merge,Ab.omap,_b.pairs,Ib.set,vc.intTime,vc.floatTime,vc.timestamp];Uf.schema=Tb});var ap=P(yc=>{"use strict";var Zf=Vi(),jb=_a(),ep=Fi(),$b=Jr(),Ob=Ks(),gc=Xs(),wc=Zs(),Hb=Rf(),Db=If(),tp=rc(),Xr=ka(),ip=sc(),rp=Da(),Yf=Kf(),np=fc(),za=hc(),Xf=new Map([["core",Hb.schema],["failsafe",[Zf.map,ep.seq,$b.string]],["json",Db.schema],["yaml11",Yf.schema],["yaml-1.1",Yf.schema]]),Qf={binary:tp.binary,bool:Ob.boolTag,float:gc.float,floatExp:gc.floatExp,floatNaN:gc.floatNaN,floatTime:za.floatTime,int:wc.int,intHex:wc.intHex,intOct:wc.intOct,intTime:za.intTime,map:Zf.map,merge:Xr.merge,null:jb.nullTag,omap:ip.omap,pairs:rp.pairs,seq:ep.seq,set:np.set,timestamp:za.timestamp},Lb={"tag:yaml.org,2002:binary":tp.binary,"tag:yaml.org,2002:merge":Xr.merge,"tag:yaml.org,2002:omap":ip.omap,"tag:yaml.org,2002:pairs":rp.pairs,"tag:yaml.org,2002:set":np.set,"tag:yaml.org,2002:timestamp":za.timestamp};function Bb(e,t,i){let r=Xf.get(t);if(r&&!e)return i&&!r.includes(Xr.merge)?r.concat(Xr.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Xf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(Xr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Qf[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Qf).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}yc.coreKnownTags=Lb;yc.getTags=Bb});var kc=P(op=>{"use strict";var Nc=F(),Vb=Vi(),Fb=Fi(),qb=Jr(),Ja=ap(),Mb=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,bc=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Ja.getTags(t,"compat"):t?Ja.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ja.coreKnownTags:{},this.tags=Ja.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Nc.MAP,{value:Vb.map}),Object.defineProperty(this,Nc.SCALAR,{value:qb.string}),Object.defineProperty(this,Nc.SEQ,{value:Fb.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Mb:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};op.Schema=bc});var cp=P(sp=>{"use strict";var Wb=F(),Sc=Mr(),Qr=Br();function zb(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=Sc.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Qr.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Wb.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Qr.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Sc.stringify(e.contents,n,()=>s=null,c);s&&(l+=Qr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Sc.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
+
`)?(i.push("..."),i.push(Qr.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(Qr.indentComment(a(c),"")))}return i.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}sp.stringifyDocument=zb});var Zr=P(lp=>{"use strict";var Jb=Dr(),Mi=fa(),je=F(),Gb=qt(),Ub=Lt(),Kb=kc(),Yb=cp(),Ec=ca(),Xb=Rs(),Qb=Lr(),Cc=Ps(),xc=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,je.NODE_TYPE,{value:je.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Cc.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[je.NODE_TYPE]:{value:je.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=je.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Wi(this.contents)&&this.contents.add(t)}addIn(t,i){Wi(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=Ec.anchorNames(this);t.anchor=!i||r.has(i)?Ec.findNewAnchor(i||"a",r):i}return new Jb.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,S=i.filter(m).map(String);S.length>0&&(i=i.concat(S)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Ec.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=Qb.createNode(t,u,v);return s&&je.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new Gb.Pair(n,a)}delete(t){return Wi(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Mi.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Wi(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return je.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Mi.isEmptyPath(t)?!i&&je.isScalar(this.contents)?this.contents.value:this.contents:je.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return je.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Mi.isEmptyPath(t)?this.contents!==void 0:je.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Mi.collectionFromPath(this.schema,[t],i):Wi(this.contents)&&this.contents.set(t,i)}setIn(t,i){Mi.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Mi.collectionFromPath(this.schema,Array.from(t),i):Wi(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Cc.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Cc.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new Kb.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Ub.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?Xb.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return Yb.stringifyDocument(this,t)}};function Wi(e){if(je.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}lp.Document=xc});var rn=P(tn=>{"use strict";var en=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},Pc=class extends en{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Rc=class extends en{constructor(t,i,r){super("YAMLWarning",t,i,r)}},Zb=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};
|
|
66
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(
|
|
67
|
-
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||ak.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",
|
|
68
|
-
`+N.comment:y.comment=N.comment);let k=new
|
|
65
|
+
`}};tn.YAMLError=en;tn.YAMLParseError=Pc;tn.YAMLWarning=Rc;tn.prettifyError=Zb});var nn=P(up=>{"use strict";function ek(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,v=!1,h=null,m=null,S=null,y=null,N=null,k=null,E=null;for(let g of e)switch(v&&(g.type!=="space"&&g.type!=="newline"&&g.type!=="comma"&&a(g.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&g.type!=="comment"&&g.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),g.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&g.source.includes(" ")&&(h=g),u=!0;break;case"comment":{u||a(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=g.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=g.source:(!k||i!=="seq-item-ind")&&(c=!0):f+=g.source,l=!0,p=!0,(m||S)&&(y=g),u=!0;break;case"anchor":m&&a(g,"MULTIPLE_ANCHORS","A node can have at most one anchor"),g.source.endsWith(":")&&a(g.offset+g.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=g,E??(E=g.offset),l=!1,u=!1,v=!0;break;case"tag":{S&&a(g,"MULTIPLE_TAGS","A node can have at most one tag"),S=g,E??(E=g.offset),l=!1,u=!1,v=!0;break}case i:(m||S)&&a(g,"BAD_PROP_ORDER",`Anchors and tags must be after the ${g.source} indicator`),k&&a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.source} in ${t??"collection"}`),k=g,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){N&&a(g,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=g,l=!1,u=!1;break}default:a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.type} token`),l=!1,u=!1}let b=e[e.length-1],x=b?b.offset+b.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:N,found:k,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:S,newlineAfterProp:y,end:x,start:E??x}}up.resolveProps=ek});var Ga=P(dp=>{"use strict";function Ac(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(Ac(t.key)||Ac(t.value))return!0}return!1;default:return!0}}dp.containsNewline=Ac});var _c=P(fp=>{"use strict";var tk=Ga();function ik(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&tk.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}fp.flowIndentCheck=ik});var Ic=P(hp=>{"use strict";var pp=F();function rk(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||pp.isScalar(a)&&pp.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}hp.mapIncludes=rk});var Np=P(yp=>{"use strict";var mp=qt(),nk=Wt(),vp=nn(),ak=Ga(),gp=_c(),ok=Ic(),wp="All mapping items must start at the same column";function sk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??nk.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:p,value:v}=u,h=vp.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",wp)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||ak.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",wp);i.atKey=!0;let S=h.end,y=f?e(i,f,h,n):t(i,S,d,null,h,n);i.schema.compat&&gp.flowIndentCheck(r.indent,f,n),i.atKey=!1,ok.mapIncludes(i,s.items,y)&&n(S,"DUPLICATE_KEY","Map keys must be unique");let N=vp.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=N.end,N.found){m&&(v?.type==="block-map"&&!N.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<N.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 k=v?e(i,v,N,n):t(i,c,p,null,N,n);i.schema.compat&&gp.flowIndentCheck(r.indent,v,n),c=k.range[2];let E=new mp.Pair(y,k);i.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{m&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),N.comment&&(y.comment?y.comment+=`
|
|
68
|
+
`+N.comment:y.comment=N.comment);let k=new mp.Pair(y);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}yp.resolveBlockMap=sk});var kp=P(bp=>{"use strict";var ck=zt(),lk=nn(),uk=_c();function dk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??ck.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=lk.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&uk.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}bp.resolveBlockSeq=dk});var zi=P(Sp=>{"use strict";function fk(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Sp.resolveEnd=fk});var Pp=P(xp=>{"use strict";var pk=F(),hk=qt(),Ep=Wt(),mk=zt(),vk=zi(),Cp=nn(),gk=Ga(),wk=Ic(),Tc="Block collections are not allowed within flow collections",jc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function yk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Ep.YAMLMap:mk.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let S=r.items[m],{start:y,key:N,sep:k,value:E}=S,b=Cp.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:N??k?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!k&&!E){m===0&&b.comma?n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(b.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),b.comment&&(l.comment?l.comment+=`
|
|
69
69
|
`+b.comment:l.comment=b.comment),d=b.end;continue}!o&&i.options.strict&&gk.containsNewline(N)&&n(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)b.comma&&n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(b.comma||n(b.start,"MISSING_CHAR",`Missing , between ${s} items`),b.comment){let x="";e:for(let g of y)switch(g.type){case"comma":case"space":break;case"comment":x=g.source.substring(1);break e;default:break e}if(x){let g=l.items[l.items.length-1];pk.isPair(g)&&(g=g.value??g.key),g.comment?g.comment+=`
|
|
70
|
-
`+x:g.comment=x,b.comment=b.comment.substring(x.length+1)}}if(!o&&!k&&!b.found){let x=E?e(i,E,b,n):t(i,b.end,k,null,b,n);l.items.push(x),d=x.range[2],
|
|
71
|
-
`+w.comment:g.comment=w.comment);let O=new hk.Pair(g,C);if(i.options.keepSourceTokens&&(O.srcToken=S),o){let T=l;wk.mapIncludes(i,T.items,g)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),T.items.push(O)}else{let T=new
|
|
72
|
-
`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}
|
|
70
|
+
`+x:g.comment=x,b.comment=b.comment.substring(x.length+1)}}if(!o&&!k&&!b.found){let x=E?e(i,E,b,n):t(i,b.end,k,null,b,n);l.items.push(x),d=x.range[2],jc(E)&&n(x.range,"BLOCK_IN_FLOW",Tc)}else{i.atKey=!0;let x=b.end,g=N?e(i,N,b,n):t(i,x,y,null,b,n);jc(N)&&n(g.range,"BLOCK_IN_FLOW",Tc),i.atKey=!1;let w=Cp.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:E,offset:g.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(w.found){if(!o&&!b.found&&i.options.strict){if(k)for(let T of k){if(T===w.found)break;if(T.type==="newline"){n(T,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.start<w.found.offset-1024&&n(w.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(w.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=E?e(i,E,w,n):w.found?t(i,w.end,k,null,w,n):null;C?jc(E)&&n(C.range,"BLOCK_IN_FLOW",Tc):w.comment&&(g.comment?g.comment+=`
|
|
71
|
+
`+w.comment:g.comment=w.comment);let O=new hk.Pair(g,C);if(i.options.keepSourceTokens&&(O.srcToken=S),o){let T=l;wk.mapIncludes(i,T.items,g)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),T.items.push(O)}else{let T=new Ep.YAMLMap(i.schema);T.flow=!0,T.items.push(O);let he=(C??g).range;T.range=[g.range[0],he[1],he[2]],l.items.push(T)}d=C?C.range[2]:w.end}}let f=o?"}":"]",[p,...v]=r.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),S=u?`${m} must end with a ${f}`:`${m} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",S),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=vk.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}xp.resolveFlowCollection=yk});var Ap=P(Rp=>{"use strict";var Nk=F(),bk=re(),kk=Wt(),Sk=zt(),Ek=Np(),Ck=kp(),xk=Pp();function $c(e,t,i,r,n,a){let o=i.type==="block-map"?Ek.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?Ck.resolveBlockSeq(e,t,i,r,a):xk.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Pk(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!p||p.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===kk.YAMLMap.tagName&&s==="map"||o===Sk.YAMLSeq.tagName&&s==="seq")return $c(e,t,i,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),$c(e,t,i,n,o)}let l=$c(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=Nk.isNode(u)?u:new bk.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Rp.composeCollection=Pk});var Hc=P(_p=>{"use strict";var Oc=re();function Rk(e,t,i){let r=t.offset,n=Ak(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Oc.Scalar.BLOCK_FOLDED:Oc.Scalar.BLOCK_LITERAL,o=t.source?_k(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
|
|
73
73
|
`.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return t.source&&(m+=t.source.length),{value:h,type:a,comment:n.comment,range:[r,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[m,S]=o[h];if(S===""||S==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&i(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=m.length),u=h,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+S.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",f="",p=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
|
|
74
|
-
`;for(let h=u;h<s;++h){let[m,S]=o[h];l+=m.length+S.length+1;let y=S[S.length-1]==="\r";if(y&&(S=S.slice(0,-1)),S&&m.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-S.length-(y?2:1),"BAD_INDENT",k),m=""}a===
|
|
74
|
+
`;for(let h=u;h<s;++h){let[m,S]=o[h];l+=m.length+S.length+1;let y=S[S.length-1]==="\r";if(y&&(S=S.slice(0,-1)),S&&m.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-S.length-(y?2:1),"BAD_INDENT",k),m=""}a===Oc.Scalar.BLOCK_LITERAL?(d+=f+m.slice(c)+S,f=`
|
|
75
75
|
`):m.length>c||S[0]===" "?(f===" "?f=`
|
|
76
76
|
`:!p&&f===`
|
|
77
77
|
`&&(f=`
|
|
@@ -84,7 +84,7 @@ ${l}
|
|
|
84
84
|
`+o[h][0].slice(c);d[d.length-1]!==`
|
|
85
85
|
`&&(d+=`
|
|
86
86
|
`);break;default:d+=`
|
|
87
|
-
`}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function Ak({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let p=n[f];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":i&&!l&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",v);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function _k(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}
|
|
87
|
+
`}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function Ak({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let p=n[f];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":i&&!l&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",v);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function _k(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}_p.resolveBlockScalar=Rk});var Lc=P(Tp=>{"use strict";var Dc=re(),Ik=zi();function Tk(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,p,v)=>i(r+f,p,v);switch(n){case"scalar":s=Dc.Scalar.PLAIN,c=jk(a,l);break;case"single-quoted-scalar":s=Dc.Scalar.QUOTE_SINGLE,c=$k(a,l);break;case"double-quoted-scalar":s=Dc.Scalar.QUOTE_DOUBLE,c=Ok(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=Ik.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function jk(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),Ip(e)}function $k(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Ip(e.slice(1,-1)).replace(/''/g,"'")}function Ip(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
89
|
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let n=r[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;r=i.exec(e);)r[1]===""?a===`
|
|
90
90
|
`?n+=a:a=`
|
|
@@ -99,92 +99,92 @@ ${l}
|
|
|
99
99
|
`);)r===`
|
|
100
100
|
`&&(i+=`
|
|
101
101
|
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Dk={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Lk(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Lk(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Tp.resolveFlowScalar=Tk});var Op=P($p=>{"use strict";var ki=F(),jp=re(),Bk=Hc(),Vk=Lc();function Fk(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Bk.resolveBlockScalar(e,t,r):Vk.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[ki.SCALAR]:c?l=qk(e.schema,n,c,i,r):t.type==="scalar"?l=Mk(e,n,t,r):l=e.schema[ki.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=ki.isScalar(d)?d:new jp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new jp.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function qk(e,t,i,r,n){if(i==="!")return e[ki.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[ki.SCALAR])}function Mk({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[ki.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[ki.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}$p.composeScalar=Fk});var Dp=P(Hp=>{"use strict";function Wk(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}Hp.emptyScalarPosition=Wk});var Vp=P(Vc=>{"use strict";var zk=Dr(),Jk=F(),Gk=Ap(),Lp=Op(),Uk=zi(),Kk=Dp(),Yk={composeNode:Bp,composeEmptyNode:Bc};function Bp(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=Xk(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Lp.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Gk.composeCollection(Yk,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Bc(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Jk.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Bc(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Kk.emptyScalarPosition(t,i,r),indent:-1,source:""},d=Lp.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Xk({options:e},{offset:t,source:i,end:r},n){let a=new zk.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=Uk.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Vc.composeEmptyNode=Bc;Vc.composeNode=Bp});var Mp=P(qp=>{"use strict";var Qk=Zr(),Fp=Vp(),Zk=zi(),eS=nn();function tS(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Qk.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=eS.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Fp.composeNode(l,n,u,o):Fp.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=Zk.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}qp.composeDoc=tS});var qc=P(Jp=>{"use strict";var iS=ra("process"),rS=Ps(),nS=Zr(),an=rn(),Wp=F(),aS=Mp(),oS=zi();function on(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function zp(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var
|
|
106
|
-
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(
|
|
105
|
+
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var Fc=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=on(i);a?this.warnings.push(new an.YAMLWarning(o,r,n)):this.errors.push(new an.YAMLParseError(o,r,n))},this.directives=new rS.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=zp(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(Wp.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Wp.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
|
|
107
107
|
${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
|
|
108
|
-
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
109
|
-
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new
|
|
108
|
+
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:zp(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(iS.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=on(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=aS.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new an.YAMLParseError(on(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new an.YAMLParseError(on(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=oS.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
|
|
109
|
+
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new an.YAMLParseError(on(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new nS.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};Jp.Composer=Fc});var Kp=P(Ua=>{"use strict";var sS=Hc(),cS=Lc(),lS=rn(),Gp=qr();function uS(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new lS.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return cS.resolveFlowScalar(e,t,r);case"block-scalar":return sS.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function dS(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Gp.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
111
|
`),u=s.substring(0,l),d=s.substring(l+1)+`
|
|
112
|
-
`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function fS(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=
|
|
112
|
+
`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return Up(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function fS(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Gp.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">":pS(e,c);break;case'"':Mc(e,c,"double-quoted-scalar");break;case"'":Mc(e,c,"single-quoted-scalar");break;default:Mc(e,c,"scalar")}}function pS(e,t){let i=t.indexOf(`
|
|
114
114
|
`),r=t.substring(0,i),n=t.substring(i+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=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];
|
|
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:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}
|
|
115
|
+
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];Up(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 Up(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function Mc(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}Ua.createScalarToken=dS;Ua.resolveAsScalar=uS;Ua.setScalarValue=fS});var Xp=P(Yp=>{"use strict";var hS=e=>"type"in e?Ya(e):Ka(e);function Ya(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Ya(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Ka(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Ka(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Ka(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function Ka({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Ya(t)),i)for(let a of i)n+=a.source;return r&&(n+=Ya(r)),n}Yp.stringify=hS});var th=P(eh=>{"use strict";var Wc=Symbol("break visit"),mS=Symbol("skip children"),Qp=Symbol("remove item");function Si(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Zp(Object.freeze([]),e,t)}Si.BREAK=Wc;Si.SKIP=mS;Si.REMOVE=Qp;Si.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};Si.parentCollection=(e,t)=>{let i=Si.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Zp(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Zp(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===Wc)return Wc;s===Qp&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}eh.visit=Si});var Xa=P(Se=>{"use strict";var zc=Kp(),vS=Xp(),gS=th(),Jc="\uFEFF",Gc="",Uc="",Kc="",wS=e=>!!e&&"items"in e,yS=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function NS(e){switch(e){case Jc:return"<BOM>";case Gc:return"<DOC>";case Uc:return"<FLOW_END>";case Kc:return"<SCALAR>";default:return JSON.stringify(e)}}function bS(e){switch(e){case Jc:return"byte-order-mark";case Gc:return"doc-mode";case Uc:return"flow-error-end";case Kc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
118
|
`:case`\r
|
|
119
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Se.createScalarToken=
|
|
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}Se.createScalarToken=zc.createScalarToken;Se.resolveAsScalar=zc.resolveAsScalar;Se.setScalarValue=zc.setScalarValue;Se.stringify=vS.stringify;Se.visit=gS.visit;Se.BOM=Jc;Se.DOCUMENT=Gc;Se.FLOW_END=Uc;Se.SCALAR=Kc;Se.isCollection=wS;Se.isScalar=yS;Se.prettyToken=NS;Se.tokenType=bS});var Qc=P(rh=>{"use strict";var sn=Xa();function Ge(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var ih=new Set("0123456789ABCDEFabcdef"),kS=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Qa=new Set(",[]{}"),SS=new Set(` ,[]{}
|
|
121
|
+
\r `),Yc=e=>!e||SS.has(e),Xc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
|
|
122
122
|
`?!0:i==="\r"?this.buffer[t+1]===`
|
|
123
123
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
|
|
124
124
|
`||!n&&!this.atEnd)return t+r+1}return i===`
|
|
125
125
|
`||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&Ge(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]===sn.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,r=t.indexOf("#");for(;r!==-1;){let a=t[r-1];if(a===" "||a===" "){i=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield sn.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 i=this.peek(3);if((i==="---"||i==="...")&&Ge(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,i==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ge(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Ge(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);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(Yc),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&Ge(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield sn.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(Yc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ge(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),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
|
|
127
127
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=r.indexOf(`
|
|
128
128
|
`,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>Ge(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,r;e:for(let a=this.pos;r=this.buffer[a];++a)switch(r){case" ":i+=1;break;case`
|
|
129
129
|
`:t=a,i=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(!r&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i: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(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
132
132
|
`;)r=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+i>s)t=a;else break}while(!0);return yield
|
|
133
|
+
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield sn.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(Ge(a)||t&&Qa.has(a))break;i=r}else if(Ge(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(r+=1,n=`
|
|
135
|
-
`,a=this.buffer[r+1]):i=r),a==="#"||t&&
|
|
136
|
-
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&
|
|
135
|
+
`,a=this.buffer[r+1]):i=r),a==="#"||t&&Qa.has(a))break;if(n===`
|
|
136
|
+
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&Qa.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield sn.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Yc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ge(r)||i&&Qa.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!Ge(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(kS.has(i))i=this.buffer[++t];else if(i==="%"&&ih.has(this.buffer[t+1])&&ih.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
137
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};rh.Lexer=Xc});var el=P(nh=>{"use strict";var Zc=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};nh.LineCounter=Zc});var il=P(lh=>{"use strict";var ES=ra("process"),ah=Xa(),CS=Qc();function Jt(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function oh(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 ch(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 Za(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 Ji(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 eo(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function sh(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Jt(t.start,"explicit-key-ind")&&!Jt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,ch(t.value)?t.value.end?eo(t.value.end,t.sep):t.value.end=t.sep:eo(t.start,t.sep),delete t.sep)}var tl=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 CS.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,ES.env.LOG_TOKENS&&console.log("|",ah.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=ah.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&sh(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&oh(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{oh(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let i=Za(this.peek(2)),r=Ji(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
140
|
-
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){
|
|
140
|
+
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){eo(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Jt(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(ch(i.key)&&!Jt(i.sep,"newline")){let o=Ji(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(Jt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Ji(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Jt(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!Jt(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){eo(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||Jt(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=Za(r),a=Ji(n);sh(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
142
|
-
`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=
|
|
143
|
-
${
|
|
144
|
-
`,i)}var sl={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:"验证预期"}},
|
|
142
|
+
`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Za(t),r=Ji(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Za(t),r=Ji(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};lh.Parser=tl});var hh=P(ln=>{"use strict";var uh=qc(),xS=Zr(),cn=rn(),PS=Vs(),RS=F(),AS=el(),dh=il();function fh(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new AS.LineCounter||null,prettyErrors:t}}function _S(e,t={}){let{lineCounter:i,prettyErrors:r}=fh(t),n=new dh.Parser(i?.addNewLine),a=new uh.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(cn.prettifyError(e,i)),s.warnings.forEach(cn.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function ph(e,t={}){let{lineCounter:i,prettyErrors:r}=fh(t),n=new dh.Parser(i?.addNewLine),a=new uh.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 cn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(cn.prettifyError(e,i)),o.warnings.forEach(cn.prettifyError(e,i))),o}function IS(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=ph(e,i);if(!n)return null;if(n.warnings.forEach(a=>PS.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function TS(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return RS.isDocument(e)&&!r?e.toString(i):new xS.Document(e,r,i).toString(i)}ln.parse=IS;ln.parseAllDocuments=_S;ln.parseDocument=ph;ln.stringify=TS});var Gi=P(z=>{"use strict";var jS=qc(),$S=Zr(),OS=kc(),rl=rn(),HS=Dr(),Gt=F(),DS=qt(),LS=re(),BS=Wt(),VS=zt(),FS=Xa(),qS=Qc(),MS=el(),WS=il(),to=hh(),mh=jr();z.Composer=jS.Composer;z.Document=$S.Document;z.Schema=OS.Schema;z.YAMLError=rl.YAMLError;z.YAMLParseError=rl.YAMLParseError;z.YAMLWarning=rl.YAMLWarning;z.Alias=HS.Alias;z.isAlias=Gt.isAlias;z.isCollection=Gt.isCollection;z.isDocument=Gt.isDocument;z.isMap=Gt.isMap;z.isNode=Gt.isNode;z.isPair=Gt.isPair;z.isScalar=Gt.isScalar;z.isSeq=Gt.isSeq;z.Pair=DS.Pair;z.Scalar=LS.Scalar;z.YAMLMap=BS.YAMLMap;z.YAMLSeq=VS.YAMLSeq;z.CST=FS;z.Lexer=qS.Lexer;z.LineCounter=MS.LineCounter;z.Parser=WS.Parser;z.parse=to.parse;z.parseAllDocuments=to.parseAllDocuments;z.parseDocument=to.parseDocument;z.stringify=to.stringify;z.visit=mh.visit;z.visitAsync=mh.visitAsync});import vi from"node:path";import{realpathSync as lT}from"node:fs";import{execFileSync as py}from"child_process";import Ir from"path";function Oi(e,t){return py("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function hy(e,t){let i=Ir.normalize(e),r=Ir.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function be(e){try{let t=Ir.resolve(Oi(e,["rev-parse","--show-toplevel"])),r=Oi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?Ir.resolve(r.slice(9)):t,a=null;try{a=Oi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!hy(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function xd(e){try{Oi(e,["rev-parse","--is-inside-work-tree"]);let t=Oi(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:Ir.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function Dt(e){return xd(e).map(t=>t.root)}function gi(e,t){try{let i=Oi(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as my}from"crypto";function ze(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function vy(e,t){t.has(e)&&ze("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||ze("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&ze("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ze("symbol properties are not supported"),`[${e.map(r=>Ss(r,t)).join(",")}]`}finally{t.delete(e)}}function gy(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&ze("only plain objects are supported"),t.has(e)&&ze("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ze("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&ze("accessor properties are not supported"),`${JSON.stringify(o)}:${Ss(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Ss(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)||ze("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?vy(e,t):gy(e,t);case"bigint":case"function":case"symbol":case"undefined":return ze(`${typeof e} values are not supported`)}return ze("unsupported value type")}function Tr(e){return Ss(e,new Set)}function j(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 my("sha256").update(`${e}
|
|
143
|
+
${Tr(t)}`).digest("hex")}var iu=_r(Gi(),1);import{promises as Wm}from"fs";import Rt from"path";import{createHash as US}from"node:crypto";import{promises as Ue}from"node:fs";import Oe from"node:path";import{TextDecoder as KS}from"node:util";import nl from"path";var zS=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),JS=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function GS(e){return e.toLowerCase().startsWith(".env")}function ct(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>GS(r))?"environment-file":i.some(r=>JS.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>zS.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function al(e,t){let i=ct(t);if(i)return i;let r=nl.resolve(e.projectRoot,...t.split("/")),n=nl.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===nl.resolve(e.configFile)?"native-runtime":null}function Ut(e){return e!==0&&e!==0n&&e!=="0"}function $e(e,t){return Ut(e.dev)&&Ut(t.dev)&&Ut(e.ino)&&Ut(t.ino)}function M(e,t){let i=Ut(e.dev)&&Ut(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Ut(e.ino)&&Ut(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var un=1024*1024;function ol(e,t){let i=Oe.relative(e,t);return i===""||!Oe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Oe.sep}`)}function YS(e){let t=Oe.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})||Oe.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=ct(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function XS(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function QS(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function io(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function vh(e){let t=await Ue.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ue.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ZS(e,t){let i=Oe.resolve(e),r=Oe.resolve(t);if(!ol(i,r))throw new Error("Native artifact path is outside its root");let n=[await vh(i)],a=i;for(let o of Oe.relative(i,r).split(Oe.sep).filter(Boolean)){a=Oe.join(a,o);let s=await vh(a);if(!ol(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function gh(e){for(let t of e){let i=await Ue.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!QS(t,i)||await Ue.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ne(e){let t=YS(e.ref),i=e.maxBytes===null?null:XS(e.maxBytes??un),r=Oe.resolve(e.root,...t.split("/")),n=await ZS(e.root,Oe.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Ue.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Ue.realpath(r);if(!ol(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ue.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ue.lstat(r),Ue.realpath(r)]);if(await gh(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!io(a,c)||!io(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let N=i===null?p.length:i+1-f,k=await s.read(p,0,Math.min(p.length,N),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Ue.lstat(r),Ue.realpath(r)]);if(await gh(n),!h.isFile()||h.isSymbolicLink()||m!==o||!io(c,v)||!io(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),y;try{y=new KS("utf-8",{fatal:!0}).decode(S)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:f,hash:e.includeHash===!1?null:US("sha256").update(S).digest("hex"),text:y}}finally{await s.close()}}import{randomUUID as eE}from"crypto";import{promises as le}from"fs";import Ke from"path";function ro(e,t){let i=Ke.relative(e,t);return i===""||!Ke.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ke.sep}`)}function tE(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function no(e,t){return M({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function iE(e,t){return no(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function wh(e){let t=await le.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ui(e){for(let t of e){let i=await le.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!tE(t,i)||await le.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function rE(e,t,i){let[r,n]=await Promise.all([le.lstat(e),le.realpath(e),i?Ui(i):Promise.resolve()]);if(!r.isFile()||r.isSymbolicLink()||!no(r,t)||i&&!ro(i[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return r}async function nE(e,t){let i=Ke.resolve(e),r=Ke.resolve(t);if(!ro(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await wh(i)],a=Ke.relative(i,r).split(Ke.sep).filter(Boolean),o=i;for(let s of a){await Ui(n),o=Ke.join(o,s);try{await le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await wh(o);if(!ro(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ui(n),n}async function aE(e){let t;try{t=await le.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function oE(e,t,i={}){let r=Ke.dirname(e),n=i.containedRoot?await nE(i.containedRoot,r):null;n||await le.mkdir(r,{recursive:!0});let a=Ke.join(r,`.${Ke.basename(e)}.${eE()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await le.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([le.lstat(a),le.realpath(a)]);if(await Ui(n),!l.isFile()||l.isSymbolicLink()||!no(s,l)||!ro(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!no(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await rE(a,c,n),await i.beforeCommit?.(),n){await Ui(n);let l=await le.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!iE(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await le.link(a,e),await le.unlink(a)):await le.rename(a,e),await aE(r)}catch(l){if(await o?.close(),!n)await le.rm(a,{force:!0});else try{await Ui(n),await le.rm(a,{force:!0})}catch{}throw l}}async function Nt(e,t,i={}){await oE(e,t,i)}async function Ye(e,t,i={}){await Nt(e,JSON.stringify(t,null,2)+`
|
|
144
|
+
`,i)}var sl={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:"验证预期"}},sE={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:"结论"}},cE={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:"结论"}},yh=new Map,cl=new Map;for(let e of Object.keys(sl)){for(let[t,i]of Object.entries(sl[e]))yh.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(sE[e]))cl.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(cE[e]))cl.set(i.toLocaleLowerCase("en-US"),t)}function lE(e,t){return sl[e][t]}function ao(e){return yh.get(e.trim().toLocaleLowerCase("en-US"))??null}function Nh(e){return cl.get(e.trim().toLocaleLowerCase("en-US"))??null}function oo(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(i=>`# ${lE(e,i)}
|
|
145
145
|
`).join(`
|
|
146
|
-
`)}var dl=Rr(Ji(),1);import Kt from"path";var un=64*1024,no=1024,ao=64,kh=1024,Sh=64,xh=5,ll={learning:!0,retrieval:!0},lE={provider:"local"},uE=12e4,Eh=6e5,dE=[".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/**"],fE=["**/.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"],pE=[...dE,...fE].sort((e,t)=>e.localeCompare(t,"en"));var Xe={include:["**/*"],exclude:[...pE],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function hE(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Kt.posix.isAbsolute(i)||Kt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Gi(e){let t=hE(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Ph(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function oo(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||Kt.posix.isAbsolute(r)||Kt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function bt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Rh(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function so(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>no)throw new Error(`${t} exceeds ${no} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>ao)throw new Error(`${t} contains more than ${ao} wildcard tokens`);return e}function Ch(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>so(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function ul(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function mE(e){if(e===void 0)return{...Xe,include:[...Xe.include],exclude:[...Xe.exclude]};let t=bt(e,"native.snapshot");return{include:Ch(t.include,"native.snapshot.include",Xe.include),exclude:Ch(t.exclude,"native.snapshot.exclude",Xe.exclude),max_files:ul(t.max_files,Xe.max_files,"native.snapshot.max_files"),max_total_bytes:ul(t.max_total_bytes,Xe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ul(t.max_duration_ms,Xe.max_duration_ms,"native.snapshot.max_duration_ms")}}function vE(e){if(e===void 0)return;let t=bt(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=bt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Gi(r),toArtifactRoot:Gi(n),stage:a,...o?{cleanup:o}:{}}}function gE(e){if(e===void 0)return;let t=bt(e,"native.finish");if(t.pull_request===void 0)return{};let i=bt(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Kt.posix.isAbsolute(r[0])||Kt.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??uE;if(!Number.isSafeInteger(n)||n<1||n>Eh)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Eh}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function wE(e,t={}){let i=bt(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??xh;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=vE(i.pending_root_move),c=gE(i.finish);return{artifact_root:Gi(r),language:Rh(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:mE(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function yE(e){let t=bt(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Ph(t.artifact_layout),language:Rh(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function NE(e){let i=bt(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>oo(r,`hook.allow_paths[${n}]`)))]}}function bE(e){if(e===void 0)return{...ll};let t=bt(e,"memory"),i=t.learning??ll.learning,r=t.retrieval??ll.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function fl(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function kE(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||Kt.posix.isAbsolute(i)||Kt.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>kh)throw new Error(`${t} exceeds ${kh} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>Sh)throw new Error(`${t} contains more than ${Sh} wildcard tokens`);return i}function SE(e){let i=fl(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>kE(r,`knowledge.local.include[${n}]`)))]}}function EE(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function CE(e){let t=fl(e,"knowledge.remote"),i=EE(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function xE(e){if(e===void 0)return{...lE};let t=fl(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:SE(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:CE(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function PE(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function RE(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function dn(e,t={}){let i=(0,dl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=PE(n.ambient_resume),o=n.hook===void 0?void 0:NE(n.hook),s=bE(n.memory),c=xE(n.knowledge),l=n.native===void 0?void 0:wE(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:yE(n.classic),d=RE(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}import{createHash as _E}from"crypto";import{promises as uo}from"fs";import Yt from"path";import{constants as co,promises as Ei}from"fs";var lt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function pl(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ah(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function fn(e){return{dev:e.dev,ino:e.ino,birthtime:pl(e)}}function lo(e,t){let i=fn(e),r=fn(t);return $e(i,r)?M(i,r):M(i,r)&&pl(e)===pl(t)&&Ah(e)===Ah(t)&&e.size===t.size}async function Ui(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await Ei.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new lt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new lt("too-large",`${r} exceeds ${t} bytes`);let o=await Ei.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:fn(a)});let s=process.platform==="win32"?co.O_RDONLY:co.O_RDONLY|co.O_NOFOLLOW|co.O_NONBLOCK,c;try{c=await Ei.open(e,s)}catch(l){throw l.code==="ELOOP"?new lt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Ei.lstat(e,{bigint:n}),Ei.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!lo(a,l)||!lo(a,u))throw new lt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:fn(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:N}=await c.read(v,0,Math.min(v.length,y),null);if(N===0)break;if(p+=N,p>t)throw new lt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([c.stat({bigint:n}),Ei.lstat(e,{bigint:n}),Ei.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||S!==o||!lo(a,h)||!lo(a,m))throw new lt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:fn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:S}}finally{await c.close()}}function AE(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function hl(e,t){let i=Yt.relative(e,t);return i===""||!Yt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Yt.sep}`)}async function _h(e,t){let i=Yt.resolve(e),r=await uo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return uo.realpath(i)}async function Ih(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Yt.join(n,i[a]);let o;try{o=await uo.lstat(n)}catch(u){if(AE(u))return{exists:!1,kind:"missing"};throw u}let s=Yt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await uo.realpath(n);if(!hl(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Ki(e,t,i){let r=oo(t,i.label),n=Yt.resolve(e),a=await _h(n,i.label),o=r.split("/"),s=Yt.resolve(n,...o);if(!hl(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Ih(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Xt(e,t,i,r){let n=await Ki(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await _h(n.projectRoot,r.label);return Ui(n.target,i,{...r,verify:async(o,s)=>{if(!hl(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Ih(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var pn=".comet/config.yaml";function IE(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function fo(e,t={}){return(await po(e,t)).document}async function TE(e){try{return(await Xt(e,pn,un,{label:pn})).bytes}catch(t){if(IE(t))return null;throw t}}function jE(e){return e?{exists:!0,sha256:_E("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function po(e,t={}){let i=await TE(e);return{document:i?dn(i.toString("utf8"),t):null,identity:jE(i)}}async function ml(e){return(await fo(e))?.config??null}var V$=16*1024;import{existsSync as jh,promises as Qt}from"fs";import W from"path";import LE from"os";var Nl=".comet/config.yaml",BE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function wl(e){try{return await Qt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function VE(e){try{let t=await Qt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Xi(e,t){let i=W.relative(e,t);return i===""||!W.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${W.sep}`)}async function Yi(e){let t=[],i=e;for(;!await wl(i);){let n=W.dirname(i);if(n===i)break;t.push(W.basename(i)),i=n}let r=await Qt.realpath(i);return W.resolve(r,...t.reverse())}async function yl(e){try{return(await Qt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function bl(e){let t=W.resolve(e);try{(await Qt.stat(t)).isDirectory()||(t=W.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=W.resolve(LE.homedir());for(;;){if(!(t===r&&i!==r)){let o=W.join(t,...Nl.split("/")),s=t===i||await VE(o);if(await wl(o)&&s)return t}if(await wl(W.join(t,".git")))return t;let a=W.dirname(t);if(a===t)return i;t=a}}function kl(e){return Gi(e)}async function FE(e,t){let i=kl(t),r=W.resolve(e,...i.split("/")),n=await Qt.realpath(e),a=await Yi(r);if(!Xi(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function kt(e,t){let i=kl(t),r=await FE(e,i),n=W.join(r,"comet");if(await yl(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Yi(r),Yi(n)]);if(!Xi(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=W.resolve(e),c=W.join(s,".comet","runtime","native");if(await yl(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Qt.realpath(s),Yi(c)]);if(!Xi(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:W.join(e,...Nl.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:W.join(n,"specs"),changesDir:W.join(n,"changes"),archiveDir:W.join(n,"archive"),runtimeDir:c,changesRuntimeDir:W.join(c,"changes"),locksDir:W.join(c,"locks"),transactionsDir:W.join(c,"transactions")}}function Oh(e){if(!BE.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Zt(e,t){Oh(t);let i=W.join(e.changesRuntimeDir,t);if(!V(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Hh(e,t){Oh(t);let i=W.join(e.changesDir,t,"runtime");if(!V(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function U(e,t){let i=Zt(e,t);if(jh(i))return i;let r=Hh(e,t);return jh(r)?r:i}async function $h(e){try{let t=await Qt.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Sl(e,t){let i=Zt(e,t),r=Hh(e,t),[n,a]=await Promise.all([$h(i),$h(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function ei(e,t){if(!t.startsWith("runtime/")||W.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=W.resolve(e,...t.slice(8).split("/"));if(!V(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function le(e,t){let i=W.resolve(t);if(V(e.runtimeDir,i))return e.runtimeDir;if(V(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function V(e,t){return Xi(W.resolve(e),W.resolve(t))}async function J(e,t){let i=W.resolve(e),r=W.resolve(t);if(!Xi(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await yl(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Yi(i),Yi(r)]);if(!Xi(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var El=Xe;var ho=so;async function Ee(e){let t=(await fo(e))?.config??null;return t?.native?t:null}import{AsyncLocalStorage as ME}from"async_hooks";var dO=16*1024;var fO=new ME;import Lh from"node:path";var WE="comet.native.acceptance.v1",zE=/^acceptance-[a-f0-9]{64}$/u,JE=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),GE=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,UE=/^[a-f0-9]{64}$/u,KE=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function YE(e,t){return e<t?-1:e>t?1:0}var St=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),mn=Object.freeze({maxCriteria:1024}),Bh="<!-- comet-native:acceptance-evidence:start -->",Vh="<!-- comet-native:acceptance-evidence:end -->";function Fh(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function qh(e,t){let i=t.toString(36),r=j("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function XE(e){if(!UE.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=KE.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==j("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function QE(e,t){let i=Fh(e.text,St.maxTextBytes),r=e.context.slice(0,St.maxContextItems).map(n=>Fh(n,St.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function Wh(e){let t=XE({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(YE),n=r.slice(0,St.maxFailedCheckIds),a=e.criteria.slice(t,t+St.maxItems);for(let c of a){let l=[...i,QE(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?qh(e.acceptanceHash,u):null,limits:{...St}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>St.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?qh(e.acceptanceHash,o):null,limits:{...St}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>St.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function xl(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 Cl(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function Mh(e){return e.includes("-->")||e.includes("--!>")}function*Qi(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
146
|
+
`)}var dl=_r(Gi(),1);import Kt from"path";var dn=64*1024,so=1024,co=64,bh=1024,kh=64,Ch=5,ll={learning:!0,retrieval:!0},uE={provider:"local"},dE=12e4,Sh=6e5,fE=[".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/**"],pE=["**/.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"],hE=[...fE,...pE].sort((e,t)=>e.localeCompare(t,"en"));var Xe={include:["**/*"],exclude:[...hE],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function mE(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Kt.posix.isAbsolute(i)||Kt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Ki(e){let t=mE(e,"native.artifact_root");return t.length===0?".":t.join("/")}function xh(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function lo(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||Kt.posix.isAbsolute(r)||Kt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function bt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Ph(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function uo(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>so)throw new Error(`${t} exceeds ${so} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>co)throw new Error(`${t} contains more than ${co} wildcard tokens`);return e}function Eh(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>uo(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function ul(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function vE(e){if(e===void 0)return{...Xe,include:[...Xe.include],exclude:[...Xe.exclude]};let t=bt(e,"native.snapshot");return{include:Eh(t.include,"native.snapshot.include",Xe.include),exclude:Eh(t.exclude,"native.snapshot.exclude",Xe.exclude),max_files:ul(t.max_files,Xe.max_files,"native.snapshot.max_files"),max_total_bytes:ul(t.max_total_bytes,Xe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ul(t.max_duration_ms,Xe.max_duration_ms,"native.snapshot.max_duration_ms")}}function gE(e){if(e===void 0)return;let t=bt(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=bt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Ki(r),toArtifactRoot:Ki(n),stage:a,...o?{cleanup:o}:{}}}function wE(e){if(e===void 0)return;let t=bt(e,"native.finish");if(t.pull_request===void 0)return{};let i=bt(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Kt.posix.isAbsolute(r[0])||Kt.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??dE;if(!Number.isSafeInteger(n)||n<1||n>Sh)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Sh}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function yE(e,t={}){let i=bt(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Ch;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=gE(i.pending_root_move),c=wE(i.finish);return{artifact_root:Ki(r),language:Ph(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:vE(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function NE(e){let t=bt(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:xh(t.artifact_layout),language:Ph(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function bE(e){let i=bt(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>lo(r,`hook.allow_paths[${n}]`)))]}}function kE(e){if(e===void 0)return{...ll};let t=bt(e,"memory"),i=t.learning??ll.learning,r=t.retrieval??ll.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function fl(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function SE(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||Kt.posix.isAbsolute(i)||Kt.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>bh)throw new Error(`${t} exceeds ${bh} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>kh)throw new Error(`${t} contains more than ${kh} wildcard tokens`);return i}function EE(e){let i=fl(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>SE(r,`knowledge.local.include[${n}]`)))]}}function CE(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function xE(e){let t=fl(e,"knowledge.remote"),i=CE(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function PE(e){if(e===void 0)return{...uE};let t=fl(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:EE(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:xE(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function RE(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function AE(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function fn(e,t={}){let i=(0,dl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=RE(n.ambient_resume),o=n.hook===void 0?void 0:bE(n.hook),s=kE(n.memory),c=PE(n.knowledge),l=n.native===void 0?void 0:yE(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:NE(n.classic),d=AE(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}import{createHash as IE}from"crypto";import{promises as ho}from"fs";import Yt from"path";import{constants as fo,promises as Ei}from"fs";var lt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function pl(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Rh(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function pn(e){return{dev:e.dev,ino:e.ino,birthtime:pl(e)}}function po(e,t){let i=pn(e),r=pn(t);return $e(i,r)?M(i,r):M(i,r)&&pl(e)===pl(t)&&Rh(e)===Rh(t)&&e.size===t.size}async function Yi(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await Ei.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new lt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new lt("too-large",`${r} exceeds ${t} bytes`);let o=await Ei.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:pn(a)});let s=process.platform==="win32"?fo.O_RDONLY:fo.O_RDONLY|fo.O_NOFOLLOW|fo.O_NONBLOCK,c;try{c=await Ei.open(e,s)}catch(l){throw l.code==="ELOOP"?new lt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Ei.lstat(e,{bigint:n}),Ei.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!po(a,l)||!po(a,u))throw new lt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:pn(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:N}=await c.read(v,0,Math.min(v.length,y),null);if(N===0)break;if(p+=N,p>t)throw new lt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([c.stat({bigint:n}),Ei.lstat(e,{bigint:n}),Ei.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||S!==o||!po(a,h)||!po(a,m))throw new lt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:pn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:S}}finally{await c.close()}}function _E(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function hl(e,t){let i=Yt.relative(e,t);return i===""||!Yt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Yt.sep}`)}async function Ah(e,t){let i=Yt.resolve(e),r=await ho.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ho.realpath(i)}async function _h(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Yt.join(n,i[a]);let o;try{o=await ho.lstat(n)}catch(u){if(_E(u))return{exists:!1,kind:"missing"};throw u}let s=Yt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await ho.realpath(n);if(!hl(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Xi(e,t,i){let r=lo(t,i.label),n=Yt.resolve(e),a=await Ah(n,i.label),o=r.split("/"),s=Yt.resolve(n,...o);if(!hl(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await _h(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Xt(e,t,i,r){let n=await Xi(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await Ah(n.projectRoot,r.label);return Yi(n.target,i,{...r,verify:async(o,s)=>{if(!hl(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await _h(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var hn=".comet/config.yaml";function TE(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function mo(e,t={}){return(await vo(e,t)).document}async function jE(e){try{return(await Xt(e,hn,dn,{label:hn})).bytes}catch(t){if(TE(t))return null;throw t}}function $E(e){return e?{exists:!0,sha256:IE("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function vo(e,t={}){let i=await jE(e);return{document:i?fn(i.toString("utf8"),t):null,identity:$E(i)}}async function ml(e){return(await mo(e))?.config??null}var F$=16*1024;import{existsSync as Th,promises as Qt}from"fs";import W from"path";import BE from"os";var Nl=".comet/config.yaml",VE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function wl(e){try{return await Qt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function FE(e){try{let t=await Qt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Zi(e,t){let i=W.relative(e,t);return i===""||!W.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${W.sep}`)}async function Qi(e){let t=[],i=e;for(;!await wl(i);){let n=W.dirname(i);if(n===i)break;t.push(W.basename(i)),i=n}let r=await Qt.realpath(i);return W.resolve(r,...t.reverse())}async function yl(e){try{return(await Qt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function bl(e){let t=W.resolve(e);try{(await Qt.stat(t)).isDirectory()||(t=W.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=W.resolve(BE.homedir());for(;;){if(!(t===r&&i!==r)){let o=W.join(t,...Nl.split("/")),s=t===i||await FE(o);if(await wl(o)&&s)return t}if(await wl(W.join(t,".git")))return t;let a=W.dirname(t);if(a===t)return i;t=a}}function kl(e){return Ki(e)}async function qE(e,t){let i=kl(t),r=W.resolve(e,...i.split("/")),n=await Qt.realpath(e),a=await Qi(r);if(!Zi(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function kt(e,t){let i=kl(t),r=await qE(e,i),n=W.join(r,"comet");if(await yl(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Qi(r),Qi(n)]);if(!Zi(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=W.resolve(e),c=W.join(s,".comet","runtime","native");if(await yl(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Qt.realpath(s),Qi(c)]);if(!Zi(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:W.join(e,...Nl.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:W.join(n,"specs"),changesDir:W.join(n,"changes"),archiveDir:W.join(n,"archive"),runtimeDir:c,changesRuntimeDir:W.join(c,"changes"),locksDir:W.join(c,"locks"),transactionsDir:W.join(c,"transactions")}}function $h(e){if(!VE.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Zt(e,t){$h(t);let i=W.join(e.changesRuntimeDir,t);if(!V(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Oh(e,t){$h(t);let i=W.join(e.changesDir,t,"runtime");if(!V(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function U(e,t){let i=Zt(e,t);if(Th(i))return i;let r=Oh(e,t);return Th(r)?r:i}async function jh(e){try{let t=await Qt.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Sl(e,t){let i=Zt(e,t),r=Oh(e,t),[n,a]=await Promise.all([jh(i),jh(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function ei(e,t){if(!t.startsWith("runtime/")||W.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=W.resolve(e,...t.slice(8).split("/"));if(!V(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function ue(e,t){let i=W.resolve(t);if(V(e.runtimeDir,i))return e.runtimeDir;if(V(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function V(e,t){return Zi(W.resolve(e),W.resolve(t))}async function J(e,t){let i=W.resolve(e),r=W.resolve(t);if(!Zi(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await yl(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Qi(i),Qi(r)]);if(!Zi(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var El=Xe;var go=uo;async function Ee(e){let t=(await mo(e))?.config??null;return t?.native?t:null}import{AsyncLocalStorage as WE}from"async_hooks";var fO=16*1024;var pO=new WE;import Dh from"node:path";var zE="comet.native.acceptance.v1",JE=/^acceptance-[a-f0-9]{64}$/u,GE=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),UE=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,KE=/^[a-f0-9]{64}$/u,YE=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function XE(e,t){return e<t?-1:e>t?1:0}var St=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),vn=Object.freeze({maxCriteria:1024}),Lh="<!-- comet-native:acceptance-evidence:start -->",Bh="<!-- comet-native:acceptance-evidence:end -->";function Vh(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function Fh(e,t){let i=t.toString(36),r=j("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function QE(e){if(!KE.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=YE.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==j("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function ZE(e,t){let i=Vh(e.text,St.maxTextBytes),r=e.context.slice(0,St.maxContextItems).map(n=>Vh(n,St.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function Mh(e){let t=QE({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(XE),n=r.slice(0,St.maxFailedCheckIds),a=e.criteria.slice(t,t+St.maxItems);for(let c of a){let l=[...i,ZE(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?Fh(e.acceptanceHash,u):null,limits:{...St}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>St.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?Fh(e.acceptanceHash,o):null,limits:{...St}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>St.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function xl(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 Cl(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function qh(e){return e.includes("-->")||e.includes("--!>")}function*er(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
147
147
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
148
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=Cl(l,t);else if(i)
|
|
149
|
-
`),[],r)),"Brief",r)}function _l(e,t="spec.md",i=
|
|
150
|
-
`),o.context,r)),o=null}};for(let{line:c,body:l}of
|
|
151
|
-
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=Jh(o),c=nC(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function nC(e){let t=Jh([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var Tl=Rr(Ji(),1);import{promises as oC}from"node:fs";var vn="comet.native.v4",vo="comet.native.local-execution.v4";var Uh=["multi-session","single-session"];var sC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,cC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lC=/^A[1-9][0-9]*$/u,uC=/^[a-f0-9]{64}$/u,dC=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"]);function ye(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ne(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function ue(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Il(e,t){return e===null?null:ue(e,t)}function fC(e,t){let i=ue(e,t);if(!uC.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Zi(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ie(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function pC(e,t){return e===null?null:ie(e,t,Number.MIN_SAFE_INTEGER)}function ae(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ut(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function go(e,t){return ut(e,t,(i,r)=>ue(i,`${t}[${r}]`))}function Ci(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function er(e,t){let i=ue(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function jl(e,t,i=!1){let r=ue(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function He(e,t){let i=ye(e,t);return Ne(i,new Set(["text","truncated"]),t),{text:ue(i.text,`${t}.text`,{empty:!0}),truncated:Zi(i.truncated,`${t}.truncated`)}}function hC(e,t){let i=`Native spec_changes[${t}]`,r=ye(e,i);Ne(r,new Set(["capability","operation","source"]),i);let n=ue(r.capability,`${i}.capability`);if(!cC.test(n))throw new Error(`${i}.capability is invalid`);let a=ae(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:jl(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function mC(e){let t="Native workspace",i=ye(e,t);Ne(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=ae(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Il(i.change_branch,`${t}.change_branch`),a=Il(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:ae(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function vC(e){let t="Native loop",i=ye(e,t);Ne(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=go(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Ci(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:ae(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ae(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ie(i.goal_cycle,`${t}.goal_cycle`,1),iteration:ie(i.iteration,`${t}.iteration`),attempt:ie(i.attempt,`${t}.attempt`),retry_epoch:ie(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ie(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ie(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ie(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Il(i.next_action,`${t}.next_action`)}}function gC(e,t){let i=`Native acceptance[${t}]`,r=ye(e,i);Ne(r,new Set(["id","source","text","result","reason"]),i);let n=ue(r.id,`${i}.id`);if(!lC.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:jl(r.source,`${i}.source`),text:ue(r.text,`${i}.text`),result:ae(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:He(r.reason,`${i}.reason`)}}function wC(e,t){let i=`Native builder_handoff.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["name","result","note"]),i),{name:He(r.name,`${i}.name`),result:ae(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:He(r.note,`${i}.note`)}}function yC(e){let t="Native builder_handoff",i=ye(e,t);Ne(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=go(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ci(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:ye(i.review,`${t}.review`);return n&&Ne(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ue(i.candidate_id,`${t}.candidate_id`),identity_provider:ue(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:ue(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),summary:He(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ut(i.checks,`${t}.checks`,wC),checks_truncated:Zi(i.checks_truncated,`${t}.checks_truncated`),known_limits:ut(i.known_limits,`${t}.known_limits`,(a,o)=>He(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Zi(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ae(n.status,["passed"],`${t}.review.status`),summary:He(n.summary,`${t}.review.summary`),reviewer_execution_ref:ue(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:er(i.submitted_at,`${t}.submitted_at`)}}function NC(e,t){let i=`Native blockers[${t}]`,r=ye(e,i);Ne(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=go(r.acceptance_ids,`${i}.acceptance_ids`);return Ci(n,`${i}.acceptance_ids`),{owner:ae(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:He(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:ae(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function bC(e,t){let i=`Native verification.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:ue(r.id,`${i}.id`),name:He(r.name,`${i}.name`),argv_display:ut(r.argv_display,`${i}.argv_display`,(n,a)=>He(n,`${i}.argv_display[${a}]`)),argv_truncated:Zi(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:jl(r.cwd_ref,`${i}.cwd_ref`,!0),status:ae(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:pC(r.exit_code,`${i}.exit_code`),duration_ms:ie(r.duration_ms,`${i}.duration_ms`)}}function kC(e){let t="Native verification",i=ye(e,t);Ne(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ut(i.checks,`${t}.checks`,bC);Ci(r.map(a=>a.id),`${t}.checks IDs`);let n=ue(i.identity_provider,`${t}.identity_provider`);return{candidate_id:ue(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ue(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),attempt:ie(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ae(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ae(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:He(i.summary,`${t}.summary`),risks:ut(i.risks,`${t}.risks`,(a,o)=>He(a,`${t}.risks[${o}]`)),risks_truncated:Zi(i.risks_truncated,`${t}.risks_truncated`),completed_at:er(i.completed_at,`${t}.completed_at`)}}function SC(e,t){let i=`Native history[${t}]`,r=ye(e,i);Ne(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=go(r.unresolved_ids,`${i}.unresolved_ids`);return Ci(n,`${i}.unresolved_ids`),{goal_cycle:ie(r.goal_cycle,`${i}.goal_cycle`,1),iteration:ie(r.iteration,`${i}.iteration`),attempt:ie(r.attempt,`${i}.attempt`),outcome:ae(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:He(r.summary,`${i}.summary`),completed_at:er(r.completed_at,`${i}.completed_at`)}}function EC(e){let t="Native history_overflow.outcome_counts",i=ye(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Ne(i,new Set(r),t),{pass:ie(i.pass,`${t}.pass`),fail:ie(i.fail,`${t}.fail`),blocked:ie(i.blocked,`${t}.blocked`),"execution-error":ie(i["execution-error"],`${t}.execution-error`),recovery:ie(i.recovery,`${t}.recovery`)}}function CC(e){let t="Native history_overflow",i=ye(e,t);Ne(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=ie(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:er(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:er(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=EC(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function xC(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function PC(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function gn(e){let t=ye(e,"Native portable state");if(Ne(t,dC,"Native portable state"),t.schema!==vn)throw new Error(`Native portable state schema must be ${vn}`);let i=ue(t.name,"Native state name");if(!sC.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ut(t.spec_changes,"Native spec_changes",hC);Ci(r.map(s=>s.capability),"Native spec change capabilities");let n=ut(t.acceptance,"Native acceptance",gC);Ci(n.map(s=>s.id),"Native acceptance IDs");let a=ut(t.history,"Native history",SC);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:vn,name:i,language:ae(t.language,["en","zh-CN"],"Native state language"),phase:ae(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ae(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ie(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:fC(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ae(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:mC(t.workspace),loop:vC(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:yC(t.builder_handoff),blockers:ut(t.blockers,"Native blockers",NC),verification:t.verification===null?null:kC(t.verification),history:a,history_overflow:CC(t.history_overflow),verification_result:ae(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ae(t.verification_report,["verification.md"],"Native verification_report"),archived:Zi(t.archived,"Native archived"),created_at:er(t.created_at,"Native created_at")};return xC(o),PC(o),o}function RC(e,t){let i=(0,Tl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function wn(e){let t=await oC.readFile(e,"utf8");return gn(RC(t,"Native portable state"))}var ti="comet.native.v3",ii="comet.native.v2",ri="comet.native.v1",tr="comet.native.transition.v3",ir="comet.native.transition.v2",yn="comet.native.transition.v1";var Xh="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",LO=new RegExp(`^portable-archive-(${Xh})\\.json$`,"u"),BO=new RegExp(`^portable-migration-(${Xh})\\.json$`,"u");import{TextDecoder as OC}from"util";import{createHash as AC}from"node:crypto";import{constants as wo,promises as Ae}from"node:fs";import Qe from"node:path";import{TextDecoder as _C}from"node:util";function No(e,t){let i=Qe.relative(e,t);return i===""||!Qe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qe.sep}`)}function Qh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function IC(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function TC(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function yo(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function $l(e,t){let i=await Ae.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ae.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Ol(e,t,i){let r=Qe.resolve(e),n=Qe.resolve(t);if(!No(r,n))throw new Error(`${i} is outside its managed root`);let a=[await $l(r,i)],o=r;for(let s of Qe.relative(r,n).split(Qe.sep).filter(Boolean)){await dt(a,i),o=Qe.join(o,s);let c=await $l(o,i);if(!No(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await dt(a,i),a}async function dt(e,t){for(let i of e){let r=await Ae.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!IC(i,r)||await Ae.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function jC(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Et(e){let t=Qh(e.maxBytes),i=Qe.resolve(e.file),r=await Ol(e.root,Qe.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>$l(Qe.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await dt(r,e.label);let a=await Ae.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=TC(a),s=await Ae.realpath(i);if(!No(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>No(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?wo.O_RDONLY:wo.O_RDONLY|wo.O_NOFOLLOW|wo.O_NONBLOCK,l=await Ae.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Ae.lstat(i),Ae.realpath(i)]);if(await dt(r,e.label),await dt(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!yo(o,u)||!yo(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await jC(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),Ae.lstat(i),Ae.realpath(i)]);if(await dt(r,e.label),await dt(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!yo(o,v)||!yo(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:AC("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Zh(e){let t=await Et(e),i;try{i=new _C("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function Nn(e){let t=await Ol(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await Ae.readdir(e.directory,{withFileTypes:!0});else{let r=Qh(e.maxEntries);i=[];let n=await Ae.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await dt(t,e.label),{entries:i,verify:()=>dt(t,e.label)}}async function Hl(e){let t=await Ol(e.root,e.directory,e.label);return{verify:()=>dt(t,e.label)}}var t0=256*1024,i0=1024*1024,r0=16*1024;var n0=64*1024*1024;var a0=new OC("utf-8",{fatal:!0});import{createHash as Co}from"crypto";import{spawn as pm}from"node:child_process";import{promises as X}from"fs";import D from"path";import{createHash as nm}from"crypto";import{createReadStream as DC}from"fs";async function Dl(e){let t=nm("sha256");for await(let i of DC(e))t.update(i);return t.digest("hex")}function K(e){return nm("sha256").update(e).digest("hex")}var bo={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Ml=1e3,LC=8*1024*1024,BC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VC=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),FC=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),qC=new Set(["schema","include","exclude","hash"]),MC=new Set(["provider","gitSelection","physicalSelection","projection"]),WC=new Set(["provider","selection"]),zC=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),JC=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),GC=new Set(["schema","status","before","after"]),UC=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),KC=new Set(["path","hash","size","type","gitObjectId"]),YC=new Set(["path","size","type","reason"]),XC=new Set(["ref","hash","count"]),QC=new Set(["change-created","legacy-migration","explicit"]),ZC=new Set(["file","directory","other"]),ex=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),xo=/^[a-f0-9]{64}$/u,hm=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,tx=new Set(["EACCES","EPERM"]),lr=64*1024,Fl=64*1024,ix=6e4,rx=1e3,nx=2,Wl={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},ax={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function mm(e){let t=e.deadlineMs??ix;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Ze(e){return Math.max(0,e.deadlineAt-Date.now())}function $(e){return Ze(e)>=1}function Ll(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function sr(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function ox(e){let t={...ax,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function sx(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&D.win32.isAbsolute(r)?D.win32.resolve(r):"C:\\Windows",a=D.win32.join(n,"System32","taskkill.exe");if(!D.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=pm(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),rx),u.unref()}catch{d(!1)}});for(let s=0;s<nx;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function zl(e,t,i,r){let n=Ze(e);if(n<1)throw Ll();let a=e.gitProcess,o=pm(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=sx(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?Ll(v.error):Ll()}return{code:p,spawnError:s}});return{child:o,completion:f}}function vm(e){let t={...Wl,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function ko(e,t,i,r=Fl){let{child:n,completion:a}=zl(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>r&&(u=!0)}),n.stderr.on("data",p=>{if(c>=lr)return;let v=lr-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Bl(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function kn(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=zl(e,t,i,r.stdin!==void 0),c=[],l=Co("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,S=!1,y=!1,N=k=>{let E=0;for(;E<k.byteLength;){let b=k.indexOf(0,E),x=b<0?k.byteLength:b,g=k.subarray(E,x);if(!m&&g.byteLength>0&&(h.byteLength+g.byteLength>r.maxRecordBytes?(h=Buffer.alloc(0),m=!0,S=!0):h=Buffer.concat([h,g])),b<0)break;v+=1,h.byteLength===0&&!m&&(y=!0);let w=h.byteLength+1;!m&&v<=r.maxRecords&&p+w<=r.maxBytes?(c.push(h),p+=w):S=!0,h=Buffer.alloc(0),m=!1,E=b+1}};o.stdout.on("data",k=>{l.update(k),f+=k.byteLength,f>r.maxBytes&&(S=!0);let E=r.outputChunkBytes;if(E===void 0){N(k);return}for(let b=0;b<k.byteLength;b+=E)N(k.subarray(b,Math.min(k.byteLength,b+E)))}),o.stderr.on("data",k=>{if(d>=lr)return;let E=lr-d,b=Buffer.from(k).subarray(0,E);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:k,spawnError:E})=>{let b=r.acceptedExitCodes??[0];if(k!==null&&b.includes(k)&&E===null&&!y&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:S,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${E?`: ${E.message}`:y||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function So(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function cx(e,t,i){if(i.length===0)return new Set;let r=await kn(e,t,["check-ignore","--no-index","-z","--stdin"],{...Wl,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=So(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function lx(e,t,i){let{child:r,completion:n}=zl(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=lr)return;let d=lr-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function cr(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||D.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||D.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function ux(e,t){return e.map(i=>{let r=cr(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function dx(e){let t=D.resolve(e);for(;;){try{return await X.lstat(D.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=D.dirname(t);if(i===t)return!1;t=i}}async function gm(e,t,i,r={}){let n=D.resolve(t.projectRoot),a=D.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=D.relative(n,D.resolve(f)).replaceAll("\\","/"),v=cr(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await kn(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await kn(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await kn(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function wm(e){return{stageBefore:Bl(e.stagedBefore),combined:Bl(e.combined),stageAfter:Bl(e.stagedAfter)}}async function ym(e,t,i=Wl,r={}){let n=D.resolve(t.projectRoot);if(!await dx(n))return null;let a;try{a=await ko(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw sr(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await gm(e,t,i,r)}catch(y){throw sr(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=y=>{for(let N of y){let k=So(N),E=k.indexOf(" ");if(E<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(k.slice(0,E))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let x=cr(k.slice(E+1));if(x===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(x),b.stage==="0"&&d.set(x,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(x)}};p(s.records),p(l.records);let v=c.records.map(So),h=ux(v,"combined"),m=new Set(h.filter(y=>!u.has(y))),S=new Set(h.filter((y,N)=>!u.has(y)&&v[N].endsWith("/")));for(let y of f)S.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:wm(o)}}function oi(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function am(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function fx(e,t){return!oi(e.stageBefore,e.stageAfter)||!oi(e.stageAfter,t.stageBefore)||!oi(e.combined,t.combined)||!oi(t.stageBefore,t.stageAfter)}async function Nm(e,t,i,r,n){let a;try{a=await gm(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw sr(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=wm(a),c=am(o)||am(s),l=fx(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:K(`comet.native.git-selection-overflow.v2
|
|
152
|
-
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var
|
|
148
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=Cl(l,t);else if(i)qh(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=Cl(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!qh(f))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&n.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function eC(e){return[...er(e)].map(({line:t,body:i})=>({line:t,body:i}))}function wo(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function tC(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Pl(e,t,i,r=[],n="content-hash"){let a=wo(i),o=t.replaceAll("\\","/").trim(),s=r.map(wo);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-${j(zE,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Rl(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function iC(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of er(e)){n=s+1;let c=o?xl(a):null;c?.level===1&&(ao(c.text)==="acceptanceExamples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function Al(e,t="brief.md",i=vn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=iC(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of er(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let p=f[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of er(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),Rl(o.map(l=>Pl("brief-example",t,l.join(`
|
|
149
|
+
`),[],r)),"Brief",r)}function _l(e,t="spec.md",i=vn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Pl("spec-scenario",t,[o.title,...o.body].join(`
|
|
150
|
+
`),o.context,r)),o=null}};for(let{line:c,body:l}of er(e)){let u=l?xl(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=wo(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),Rl(n,"Specification",r)}function Wh(e,t="spec.md",i=vn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Pl("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of er(e)){let f=d?xl(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let p=u.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||Cl(u,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),Rl(n,"Specification mandatory requirements",r)}function rC(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||tC(i)||Dh.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=Dh.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!UE.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function nC(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!GE.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function zh(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=nC(i,r),a=n.acceptance_id;if(typeof a!="string"||!JE.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return rC(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function Jh(e){let t=eC(e);if(t.some(({line:l,body:u})=>!u&&(l===Lh||l===Bh)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===Lh?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===Bh?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
|
|
151
|
+
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=zh(o),c=aC(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function aC(e){let t=zh([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var Tl=_r(Gi(),1);import{promises as sC}from"node:fs";var gn="comet.native.v4",yo="comet.native.local-execution.v4";var Gh=["multi-session","single-session"];var cC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uC=/^A[1-9][0-9]*$/u,dC=/^[a-f0-9]{64}$/u,fC=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"]);function ye(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ne(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function de(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Il(e,t){return e===null?null:de(e,t)}function pC(e,t){let i=de(e,t);if(!dC.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function tr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ie(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function hC(e,t){return e===null?null:ie(e,t,Number.MIN_SAFE_INTEGER)}function ae(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ut(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function No(e,t){return ut(e,t,(i,r)=>de(i,`${t}[${r}]`))}function Ci(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function ir(e,t){let i=de(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function jl(e,t,i=!1){let r=de(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function He(e,t){let i=ye(e,t);return Ne(i,new Set(["text","truncated"]),t),{text:de(i.text,`${t}.text`,{empty:!0}),truncated:tr(i.truncated,`${t}.truncated`)}}function mC(e,t){let i=`Native spec_changes[${t}]`,r=ye(e,i);Ne(r,new Set(["capability","operation","source"]),i);let n=de(r.capability,`${i}.capability`);if(!lC.test(n))throw new Error(`${i}.capability is invalid`);let a=ae(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:jl(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function vC(e){let t="Native workspace",i=ye(e,t);Ne(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=ae(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Il(i.change_branch,`${t}.change_branch`),a=Il(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:ae(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function gC(e){let t="Native loop",i=ye(e,t);Ne(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=No(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Ci(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:ae(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ae(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ie(i.goal_cycle,`${t}.goal_cycle`,1),iteration:ie(i.iteration,`${t}.iteration`),attempt:ie(i.attempt,`${t}.attempt`),retry_epoch:ie(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ie(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ie(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ie(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Il(i.next_action,`${t}.next_action`)}}function wC(e,t){let i=`Native acceptance[${t}]`,r=ye(e,i);Ne(r,new Set(["id","source","text","result","reason"]),i);let n=de(r.id,`${i}.id`);if(!uC.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:jl(r.source,`${i}.source`),text:de(r.text,`${i}.text`),result:ae(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:He(r.reason,`${i}.reason`)}}function yC(e,t){let i=`Native builder_handoff.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["name","result","note"]),i),{name:He(r.name,`${i}.name`),result:ae(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:He(r.note,`${i}.note`)}}function NC(e){let t="Native builder_handoff",i=ye(e,t);Ne(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=No(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ci(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:ye(i.review,`${t}.review`);return n&&Ne(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:de(i.candidate_id,`${t}.candidate_id`),identity_provider:de(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:de(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),summary:He(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ut(i.checks,`${t}.checks`,yC),checks_truncated:tr(i.checks_truncated,`${t}.checks_truncated`),known_limits:ut(i.known_limits,`${t}.known_limits`,(a,o)=>He(a,`${t}.known_limits[${o}]`)),known_limits_truncated:tr(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ae(n.status,["passed"],`${t}.review.status`),summary:He(n.summary,`${t}.review.summary`),reviewer_execution_ref:de(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:ir(i.submitted_at,`${t}.submitted_at`)}}function bC(e,t){let i=`Native blockers[${t}]`,r=ye(e,i);Ne(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=No(r.acceptance_ids,`${i}.acceptance_ids`);return Ci(n,`${i}.acceptance_ids`),{owner:ae(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:He(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:ae(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function kC(e,t){let i=`Native verification.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:de(r.id,`${i}.id`),name:He(r.name,`${i}.name`),argv_display:ut(r.argv_display,`${i}.argv_display`,(n,a)=>He(n,`${i}.argv_display[${a}]`)),argv_truncated:tr(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:jl(r.cwd_ref,`${i}.cwd_ref`,!0),status:ae(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:hC(r.exit_code,`${i}.exit_code`),duration_ms:ie(r.duration_ms,`${i}.duration_ms`)}}function SC(e){let t="Native verification",i=ye(e,t);Ne(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ut(i.checks,`${t}.checks`,kC);Ci(r.map(a=>a.id),`${t}.checks IDs`);let n=de(i.identity_provider,`${t}.identity_provider`);return{candidate_id:de(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:de(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),attempt:ie(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ae(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ae(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:He(i.summary,`${t}.summary`),risks:ut(i.risks,`${t}.risks`,(a,o)=>He(a,`${t}.risks[${o}]`)),risks_truncated:tr(i.risks_truncated,`${t}.risks_truncated`),completed_at:ir(i.completed_at,`${t}.completed_at`)}}function EC(e,t){let i=`Native history[${t}]`,r=ye(e,i);Ne(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=No(r.unresolved_ids,`${i}.unresolved_ids`);return Ci(n,`${i}.unresolved_ids`),{goal_cycle:ie(r.goal_cycle,`${i}.goal_cycle`,1),iteration:ie(r.iteration,`${i}.iteration`),attempt:ie(r.attempt,`${i}.attempt`),outcome:ae(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:He(r.summary,`${i}.summary`),completed_at:ir(r.completed_at,`${i}.completed_at`)}}function CC(e){let t="Native history_overflow.outcome_counts",i=ye(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Ne(i,new Set(r),t),{pass:ie(i.pass,`${t}.pass`),fail:ie(i.fail,`${t}.fail`),blocked:ie(i.blocked,`${t}.blocked`),"execution-error":ie(i["execution-error"],`${t}.execution-error`),recovery:ie(i.recovery,`${t}.recovery`)}}function xC(e){let t="Native history_overflow",i=ye(e,t);Ne(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=ie(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:ir(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:ir(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=CC(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function PC(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function RC(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function wn(e){let t=ye(e,"Native portable state");if(Ne(t,fC,"Native portable state"),t.schema!==gn)throw new Error(`Native portable state schema must be ${gn}`);let i=de(t.name,"Native state name");if(!cC.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ut(t.spec_changes,"Native spec_changes",mC);Ci(r.map(s=>s.capability),"Native spec change capabilities");let n=ut(t.acceptance,"Native acceptance",wC);Ci(n.map(s=>s.id),"Native acceptance IDs");let a=ut(t.history,"Native history",EC);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:gn,name:i,language:ae(t.language,["en","zh-CN"],"Native state language"),phase:ae(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ae(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ie(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:pC(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ae(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:vC(t.workspace),loop:gC(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:NC(t.builder_handoff),blockers:ut(t.blockers,"Native blockers",bC),verification:t.verification===null?null:SC(t.verification),history:a,history_overflow:xC(t.history_overflow),verification_result:ae(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ae(t.verification_report,["verification.md"],"Native verification_report"),archived:tr(t.archived,"Native archived"),created_at:ir(t.created_at,"Native created_at")};return PC(o),RC(o),o}function AC(e,t){let i=(0,Tl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function yn(e){let t=await sC.readFile(e,"utf8");return wn(AC(t,"Native portable state"))}var ti="comet.native.v3",ii="comet.native.v2",ri="comet.native.v1",rr="comet.native.transition.v3",nr="comet.native.transition.v2",Nn="comet.native.transition.v1";var Yh="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",BO=new RegExp(`^portable-archive-(${Yh})\\.json$`,"u"),VO=new RegExp(`^portable-migration-(${Yh})\\.json$`,"u");import{TextDecoder as HC}from"util";import{createHash as _C}from"node:crypto";import{constants as bo,promises as Ae}from"node:fs";import Qe from"node:path";import{TextDecoder as IC}from"node:util";function So(e,t){let i=Qe.relative(e,t);return i===""||!Qe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qe.sep}`)}function Xh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function TC(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function jC(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ko(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function $l(e,t){let i=await Ae.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ae.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Ol(e,t,i){let r=Qe.resolve(e),n=Qe.resolve(t);if(!So(r,n))throw new Error(`${i} is outside its managed root`);let a=[await $l(r,i)],o=r;for(let s of Qe.relative(r,n).split(Qe.sep).filter(Boolean)){await dt(a,i),o=Qe.join(o,s);let c=await $l(o,i);if(!So(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await dt(a,i),a}async function dt(e,t){for(let i of e){let r=await Ae.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!TC(i,r)||await Ae.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function $C(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Et(e){let t=Xh(e.maxBytes),i=Qe.resolve(e.file),r=await Ol(e.root,Qe.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>$l(Qe.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await dt(r,e.label);let a=await Ae.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=jC(a),s=await Ae.realpath(i);if(!So(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>So(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?bo.O_RDONLY:bo.O_RDONLY|bo.O_NOFOLLOW|bo.O_NONBLOCK,l=await Ae.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Ae.lstat(i),Ae.realpath(i)]);if(await dt(r,e.label),await dt(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!ko(o,u)||!ko(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await $C(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),Ae.lstat(i),Ae.realpath(i)]);if(await dt(r,e.label),await dt(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!ko(o,v)||!ko(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:_C("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Qh(e){let t=await Et(e),i;try{i=new IC("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function bn(e){let t=await Ol(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await Ae.readdir(e.directory,{withFileTypes:!0});else{let r=Xh(e.maxEntries);i=[];let n=await Ae.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await dt(t,e.label),{entries:i,verify:()=>dt(t,e.label)}}async function Hl(e){let t=await Ol(e.root,e.directory,e.label);return{verify:()=>dt(t,e.label)}}var i0=256*1024,r0=1024*1024,n0=16*1024;var a0=64*1024*1024;var o0=new HC("utf-8",{fatal:!0});import{createHash as Ro}from"crypto";import{spawn as fm}from"node:child_process";import{promises as X}from"fs";import D from"path";import{createHash as rm}from"crypto";import{createReadStream as LC}from"fs";async function Dl(e){let t=rm("sha256");for await(let i of LC(e))t.update(i);return t.digest("hex")}function K(e){return rm("sha256").update(e).digest("hex")}var Eo={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Ml=1e3,BC=8*1024*1024,VC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FC=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),qC=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),MC=new Set(["schema","include","exclude","hash"]),WC=new Set(["provider","gitSelection","physicalSelection","projection"]),zC=new Set(["provider","selection"]),JC=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),GC=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),UC=new Set(["schema","status","before","after"]),KC=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),YC=new Set(["path","hash","size","type","gitObjectId"]),XC=new Set(["path","size","type","reason"]),QC=new Set(["ref","hash","count"]),ZC=new Set(["change-created","legacy-migration","explicit"]),ex=new Set(["file","directory","other"]),tx=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),Ao=/^[a-f0-9]{64}$/u,pm=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,ix=new Set(["EACCES","EPERM"]),dr=64*1024,Fl=64*1024,rx=6e4,nx=1e3,ax=2,Wl={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},ox={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function hm(e){let t=e.deadlineMs??rx;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Ze(e){return Math.max(0,e.deadlineAt-Date.now())}function $(e){return Ze(e)>=1}function Ll(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function lr(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function sx(e){let t={...ox,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function cx(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&D.win32.isAbsolute(r)?D.win32.resolve(r):"C:\\Windows",a=D.win32.join(n,"System32","taskkill.exe");if(!D.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=fm(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),nx),u.unref()}catch{d(!1)}});for(let s=0;s<ax;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function zl(e,t,i,r){let n=Ze(e);if(n<1)throw Ll();let a=e.gitProcess,o=fm(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=cx(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?Ll(v.error):Ll()}return{code:p,spawnError:s}});return{child:o,completion:f}}function mm(e){let t={...Wl,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Co(e,t,i,r=Fl){let{child:n,completion:a}=zl(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>r&&(u=!0)}),n.stderr.on("data",p=>{if(c>=dr)return;let v=dr-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Bl(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Sn(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=zl(e,t,i,r.stdin!==void 0),c=[],l=Ro("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,S=!1,y=!1,N=k=>{let E=0;for(;E<k.byteLength;){let b=k.indexOf(0,E),x=b<0?k.byteLength:b,g=k.subarray(E,x);if(!m&&g.byteLength>0&&(h.byteLength+g.byteLength>r.maxRecordBytes?(h=Buffer.alloc(0),m=!0,S=!0):h=Buffer.concat([h,g])),b<0)break;v+=1,h.byteLength===0&&!m&&(y=!0);let w=h.byteLength+1;!m&&v<=r.maxRecords&&p+w<=r.maxBytes?(c.push(h),p+=w):S=!0,h=Buffer.alloc(0),m=!1,E=b+1}};o.stdout.on("data",k=>{l.update(k),f+=k.byteLength,f>r.maxBytes&&(S=!0);let E=r.outputChunkBytes;if(E===void 0){N(k);return}for(let b=0;b<k.byteLength;b+=E)N(k.subarray(b,Math.min(k.byteLength,b+E)))}),o.stderr.on("data",k=>{if(d>=dr)return;let E=dr-d,b=Buffer.from(k).subarray(0,E);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:k,spawnError:E})=>{let b=r.acceptedExitCodes??[0];if(k!==null&&b.includes(k)&&E===null&&!y&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:S,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${E?`: ${E.message}`:y||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function xo(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function lx(e,t,i){if(i.length===0)return new Set;let r=await Sn(e,t,["check-ignore","--no-index","-z","--stdin"],{...Wl,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=xo(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function ux(e,t,i){let{child:r,completion:n}=zl(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=dr)return;let d=dr-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function ur(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||D.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||D.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function dx(e,t){return e.map(i=>{let r=ur(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function fx(e){let t=D.resolve(e);for(;;){try{return await X.lstat(D.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=D.dirname(t);if(i===t)return!1;t=i}}async function vm(e,t,i,r={}){let n=D.resolve(t.projectRoot),a=D.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=D.relative(n,D.resolve(f)).replaceAll("\\","/"),v=ur(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Sn(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Sn(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Sn(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function gm(e){return{stageBefore:Bl(e.stagedBefore),combined:Bl(e.combined),stageAfter:Bl(e.stagedAfter)}}async function wm(e,t,i=Wl,r={}){let n=D.resolve(t.projectRoot);if(!await fx(n))return null;let a;try{a=await Co(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw lr(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await vm(e,t,i,r)}catch(y){throw lr(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=y=>{for(let N of y){let k=xo(N),E=k.indexOf(" ");if(E<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(k.slice(0,E))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let x=ur(k.slice(E+1));if(x===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(x),b.stage==="0"&&d.set(x,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(x)}};p(s.records),p(l.records);let v=c.records.map(xo),h=dx(v,"combined"),m=new Set(h.filter(y=>!u.has(y))),S=new Set(h.filter((y,N)=>!u.has(y)&&v[N].endsWith("/")));for(let y of f)S.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:gm(o)}}function oi(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function nm(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function px(e,t){return!oi(e.stageBefore,e.stageAfter)||!oi(e.stageAfter,t.stageBefore)||!oi(e.combined,t.combined)||!oi(t.stageBefore,t.stageAfter)}async function ym(e,t,i,r,n){let a;try{a=await vm(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw lr(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=gm(a),c=nm(o)||nm(s),l=px(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:K(`comet.native.git-selection-overflow.v2
|
|
152
|
+
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var hx=(1n<<256n)-1n;function mx(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function am(e){let t=D.resolve(e.paths.projectRoot),i=D.resolve(e.paths.nativeRoot),r=D.resolve(e.paths.runtimeDir),n=D.resolve(e.paths.configFile),a=D.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>Ze(e.execution)>=1?!0:(p=!0,h=!0,!1),S=k=>{let E=Buffer.from(`${k.type}\0${k.path}`,"utf8"),b=Ro("sha256").update("comet.native.physical-selection-record.v1\0").update(E).digest();for(let x=0;x<c.length;x+=1)c[x]^=b[x];if(l=l+BigInt(`0x${b.toString("hex")}`)&hx,d+=1,f+=E.byteLength,Buffer.byteLength(k.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(k)},y=async k=>{if(h||!m())return;let E;try{E=await X.opendir(k)}catch(C){if(!m())return;if(!se(C)&&!oe(C)||k===t&&se(C))throw C;v||=oe(C),p||=se(C),h=!0;return}if(!m()){try{await E.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let b=!1,x;try{for(;!h&&m();){let C;try{C=await E.read()}catch(G){if(!m())break;if(!se(G)&&!oe(G)||k===t&&se(G))throw G;v||=oe(G),p||=se(G),h=!0;break}if(!m()||C===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let O=D.join(k,C.name),T=gx(t,O);if(O===n||O===a||et(i,O)||et(r,O)||e.denylist.some(G=>et(G,O))||ct(T)!==null)continue;if(!m())break;let he;try{he=await X.lstat(O)}catch(G){if(!m())break;if(!se(G)&&!oe(G))throw G;if(v=!0,S({path:T,type:"other"}),s.push({path:T,size:null,type:"file",reason:se(G)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!m())break;continue}if(!m())break;let Q=mx(he);if(Q==="directory"){if(bx(e.policy,T))continue;if(!m())break;let G;try{G=await X.realpath(O)}catch(at){if(!m())break;if(!se(at)&&!oe(at))throw at;if(v=!0,S({path:T,type:Q}),s.push({path:T,size:null,type:"directory",reason:se(at)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!m())break;continue}if(!m())break;if(!V(e.physicalProjectRoot,G)||et(e.physicalNativeRoot,G))continue;if(S({path:T,type:Q}),await e.hooks?.afterNode?.(T),!m()||(await y(O),h))break;continue}if(S({path:T,type:Q}),await e.hooks?.afterNode?.(T),!m()||h)break}}catch(C){b=!0,x=C}let g;try{await E.close()}catch(C){g=C}let w=m();if(b)throw x;if(w&&g!==void 0&&g.code!=="ERR_DIR_CLOSED")throw g};await y(t),m(),p?(o.length=0,d=0,f=0):(o.sort((k,E)=>k.path.localeCompare(E.path,"en")),s.sort((k,E)=>k.path.localeCompare(E.path,"en")));let N=p?K(`comet.native.physical-selection-incomplete.v1
|
|
153
153
|
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):K(`comet.native.physical-selection.v1
|
|
154
|
-
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:N,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function
|
|
155
|
-
`)}function
|
|
156
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Vl(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function
|
|
154
|
+
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:N,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function Nm(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function vx(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!Nm(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function bm(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function om(e,t){let r=(await Co(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!pm.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return K(`gitlink:${r}`)}async function sm(e,t){let i=await om(e,t),r=await ux(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await om(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function kn(e,t){if(ct(t)!==null)return!1;let i=D.resolve(e.projectRoot,...t.split("/"));return!et(D.resolve(e.nativeRoot),i)&&!et(D.resolve(e.runtimeDir),i)}function gx(e,t){return D.relative(e,t).split(D.sep).join("/")}function wx(e,t){return t.map(i=>D.resolve(e,...i.split(/[\\/]/u)))}function et(e,t){let i=D.resolve(e),r=D.resolve(t);return r===i||V(i,r)}function se(e){return ix.has(e.code??"")}function oe(e){return e.code==="ENOENT"}function Jl(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
155
|
+
`)}function yx(e,t){return K(`comet.native.snapshot-policy.v1
|
|
156
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Vl(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function Nx(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function cm(e){let t=go(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?Nx(n):void 0;if(a&&!a())return!1;let o=Vl(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Vl(i,c,a),o===null||o.size===0)return!1}return Vl(i,o,a)?.has(i.length)??!1}}function km(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>go(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>go(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=yx(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(cm),excludeMatchers:i.map(cm),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function bx(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function lm(e,t,i){if(!e)return!0;let r=()=>$(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function En(e,t,i){let r=JSON.stringify(i);return K(`${e}
|
|
157
157
|
${Buffer.byteLength(t)}:${t}
|
|
158
|
-
${Buffer.byteLength(r)}:${r}`)}function ql(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Eo(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!ql(i))return e.splice(t,1),i}return null}function ai(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function bx(e,t,i,r){if(!$(r))return{status:"budget-exhausted"};let n;try{n=await X.open(e,"r")}catch(c){if(!$(r))return{status:"budget-exhausted"};throw c}if(!$(r))return await n.close(),{status:"budget-exhausted"};let a=Co("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!$(r))return{status:"budget-exhausted"};let c=await n.stat();if(!$(r))return{status:"budget-exhausted"};if(!c.isFile()||!ai(i,c))return{status:"changed"};for(;;){if(!$(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!$(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!$(r))return{status:"budget-exhausted"};let d=await n.stat();return $(r)?!d.isFile()||!ai(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function De(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Le(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function or(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ft(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Em(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=D.posix.normalize(e);if(i!==e||D.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function kx(e,t){let i=De(e,`Native snapshot entry ${t}`);Le(i,KC,`Native snapshot entry ${t}`);let r=Em(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!xo.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:ft(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!hm.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function Sx(e,t){let i=De(e,`Native snapshot omission ${t}`);if(Le(i,YC,`Native snapshot omission ${t}`),!ZC.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!ex.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Em(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:ft(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function Ex(e){let t=De(e,"Native snapshot omission overflow");if(Le(t,XC,"Native snapshot omission overflow"),typeof t.hash!="string"||!xo.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:or(t.count,"Native snapshot omission overflow count")}}function ar(e,t){let i=De(e,t);if(Le(i,JC,t),typeof i.hash!="string"||!xo.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=ft(i.recordCount,`${t} recordCount`),n=ft(i.storedRecordCount,`${t} storedRecordCount`),a=ft(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function dm(e){let t=De(e,"Native Git selection evidence");if(Le(t,zC,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=ar(t.stageBefore,"Native Git selection stageBefore"),r=ar(t.combined,"Native Git selection combined"),n=ar(t.stageAfter,"Native Git selection stageAfter"),a=ar(t.finalStageBefore,"Native Git selection finalStageBefore"),o=ar(t.finalCombined,"Native Git selection finalCombined"),s=ar(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!oi(i,n)||!oi(n,a)||!oi(r,o)||!oi(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function fm(e,t){let i=De(e,t);if(Le(i,UC,t),typeof i.hash!="string"||!xo.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=ft(i.visitedNodeCount,`${t} visitedNodeCount`),n=ft(i.recordCount,`${t} recordCount`),a=ft(i.storedRecordCount,`${t} storedRecordCount`),o=ft(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function Cx(e){let t=De(e,"Native physical selection evidence");if(Le(t,GC,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=fm(t.before,"Native physical selection before"),r=fm(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!bm(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function xi(e){let t=De(e,"Native content snapshot manifest");if(Le(t,VC,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!QC.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=De(t.capture,"Native content snapshot capture");if(Le(b,MC,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=b.gitSelection===void 0?void 0:dm(b.gitSelection),g=b.physicalSelection===void 0?void 0:Cx(b.physicalSelection),w=null;if(b.projection!==void 0){let C=De(b.projection,"Native content snapshot projection");if(Le(C,WC,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...C.selection===void 0?{}:{selection:dm(C.selection)}}}if(b.provider==="git"){if(g||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...g?{physicalSelection:g}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=De(t.limits,"Native content snapshot limits");Le(r,FC,"Native content snapshot limits");let n={maxFiles:or(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:or(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:or(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:or(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:or(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=De(t.policy,"Native snapshot policy");if(Le(b,qC,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Sm({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(kx),s=t.omitted.map(Sx),c=ft(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:Ex(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,x)=>b+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Ml||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(b=>b.reason==="physical-enumeration-limit"),S=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...S])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,N=y?.status==="overflow"||y?.status==="overflow-and-changed",k=y?.status==="changed"||y?.status==="overflow-and-changed";if(N!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(k!==(S.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Jl(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}async function Cm(e,t,i={}){let r=xi(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=D.resolve(e.projectRoot),a=mm(i),o=vm(i.gitSelectionLimits),s=await ym(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(km(s).filter(g=>bn(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>bn(e,g)),d=(g,w)=>w.some(C=>g===C||g.startsWith(`${C}/`)),f=g=>d(g,l),p=g=>d(g,u),v=[...r.entries.map(g=>g.path),...r.omitted.flatMap(g=>g.type==="directory"?[g.path,`${g.path}/`]:[g.path])].filter(g=>!c.has(g)&&!f(g)&&!p(g)),h=await cx(a,n,v),m=r.entries.filter(g=>!f(g.path)&&!p(g.path)&&bn(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await Nm(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let S=[...s.omissions];for(let g of l)S.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((g,w)=>g.path.localeCompare(w.path,"en"));let y=r.omitted.filter(g=>f(g.path)||p(g.path)||!bn(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(w=>w.startsWith(`${g.path}/`)):!0);for(let g of S)y.some(w=>w.path===g.path&&w.reason===g.reason)||y.push(g);y.sort((g,w)=>g.path.localeCompare(w.path,"en"));let N=r.omissionOverflow?.count??0,k=r.omissionOverflow?.hash??K("comet.native.snapshot-omission-overflow.v1");s.overflow&&(N+=s.overflow.count,k=Sn(k,"git-selection",{source:"git-selection",...s.overflow}));let E=g=>{N+=1,k=Sn(k,"omission",g)};for(;y.length>Ml;){let g=Eo(y);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");E(g)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+N===0,entries:m,omitted:y,omittedCount:y.length+N,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:N}}:{}}),x=b();for(;Jl(x)>r.limits.maxManifestBytes;){let g=Eo(y);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");E(g),x=b()}return xi(x)}function xx(e,t){if(!BC.test(t))throw new Error(`Invalid Native change name: ${t}`);return D.join(U(e,t),"baseline-manifest.json")}async function xm(e,t={}){let i={maxFiles:t.limits?.maxFiles??bo.maxFiles,maxFileBytes:t.limits?.maxFileBytes??bo.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??bo.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??bo.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=Sm(t.policy),n=mm({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=vm(t.gitSelectionLimits),o=ox(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=D.resolve(e.projectRoot),c=await X.realpath(s),l=D.resolve(e.nativeRoot),u=await X.realpath(l),d=D.resolve(e.runtimeDir),f=D.resolve(e.configFile),p=D.join(s,".comet","current-change.json"),v=gx(s,t.denylist??[]),h=[],m=[],S=new Map,y=new Map,N=0,k=0,E=K("comet.native.snapshot-omission-overflow.v1"),b=0,x=!1,g=null,w=_=>{k+=1,E=Sn(E,"omission",_)},C=_=>{if(N+=1,m.length<Ml){m.push(_);return}if(ql(_)){let A=Eo(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),m.push(_);return}w(_)},O=_=>{N+=_.count,k+=_.count,E=Sn(E,"git-selection",{source:"git-selection",..._})},T=_=>{k+=1,E=Sn(E,"manifest-entry",{reason:"manifest-size",entry:_})},pe=async(_,A)=>{h.push(_),b+=_.size,S.set(_.path,A),x||(x=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Q=(_,A)=>{let I=h.findIndex(Y=>Y.path===_);if(I<0)return;let[L]=h.splice(I,1);b-=L.size,S.delete(_),C(A)},G=async(_,A,I,L)=>{if(!I.isFile()||I.isSymbolicLink()||!$(n))return;let Y;try{Y=await X.realpath(_)}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!$(n)||!V(c,Y)||et(u,Y))return;if(h.length>=i.maxFiles){C({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){C({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){C({path:A,size:I.size,type:"file",reason:"total-size"});return}let q,H,ee;try{if(q=await bx(Y,I.size,I,n),q.status==="budget-exhausted"||!$(n))return;if(q.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!$(n)||(ee=await X.realpath(_),!$(n)))return;H=await X.lstat(_)}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if($(n)){if(q.bytes!==I.size||ee!==Y||!ai(I,q.finalStat)||!ai(q.finalStat,H)||!H.isFile()||H.isSymbolicLink()||H.size!==I.size||H.mtimeMs!==I.mtimeMs||H.ctimeMs!==I.ctimeMs){C({path:A,size:H.isFile()?H.size:null,type:H.isFile()?"file":"other",reason:"changed-during-read"});return}$(n)&&await pe({path:A,hash:q.hash,size:H.size,type:"file",...L===void 0?{}:{gitObjectId:L}},{kind:"file",target:_,realTarget:Y,stat:H})}},at=async(_,A,I)=>{if(!$(n))return;let L,Y,q;try{if(L=await X.readlink(_,{encoding:"buffer"}),!$(n)||(q=await X.lstat(_),!$(n)))return;Y=await X.readlink(_,{encoding:"buffer"})}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:null,type:"other",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!$(n))return;if(!q.isSymbolicLink()||!ai(I,q)||q.mtimeMs!==I.mtimeMs||q.ctimeMs!==I.ctimeMs||!L.equals(Y)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let H=L.byteLength;if(h.length>=i.maxFiles){C({path:A,size:H,type:"other",reason:"file-count"});return}if(H>i.maxFileBytes){C({path:A,size:H,type:"other",reason:"file-size"});return}if(b+H>i.maxTotalBytes){C({path:A,size:H,type:"other",reason:"total-size"});return}let ee=Co("sha256").update("symlink\0").update(L).digest("hex");$(n)&&await pe({path:A,hash:ee,size:H,type:"file"},{kind:"symlink",target:_,rawTarget:L,stat:q})},We=async()=>{for(let[_,A]of[...S]){if(!$(n))return;if(A.kind==="file"){let H,ee;try{if(H=await X.realpath(A.target),!$(n))return;ee=await X.lstat(A.target)}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"file",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!$(n))return;(H!==A.realTarget||!ee.isFile()||ee.isSymbolicLink()||!ai(A.stat,ee)||ee.size!==A.stat.size||ee.mtimeMs!==A.stat.mtimeMs||ee.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:ee.isFile()?ee.size:null,type:ee.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let H,ee;try{if(H=await X.lstat(A.target),!$(n))return;ee=await X.readlink(A.target,{encoding:"buffer"})}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"other",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!$(n))return;(!H.isSymbolicLink()||!ai(A.stat,H)||H.mtimeMs!==A.stat.mtimeMs||H.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ee))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,L;try{if(I=await X.realpath(A.target),!$(n))return;L=await X.lstat(A.target)}catch{if(!$(n))return;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!$(n))return;if(!(I===A.realTarget&&L.isDirectory()&&!L.isSymbolicLink()&&ai(A.stat,L)&&V(c,I)&&!et(u,I))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let q;try{if(!$(n))return;q=await cm(n,I)}catch(H){if(sr(H))throw H;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!$(n))return;q.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):q.hash!==A.hash&&Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!$(n))return;try{let I=await X.lstat(A);if(!$(n))return;C({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!$(n))return;if(oe(I))continue;if(!se(I))throw I;C({path:_,size:null,type:"file",reason:"unreadable"})}}},Pe=await ym(n,e,a,t.gitSelectionHooks);if(Pe===null){let _=await om({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let L of _.records){if(L.type!=="file"&&L.type!=="symlink"||S.has(L.path))continue;if(Ze(n)<1)break;if(!um(r,L.path,n))continue;if(Ze(n)<1)break;let Y=D.resolve(s,...L.path.split("/")),q;try{q=await X.lstat(Y)}catch(H){if(!$(n))break;if(!se(H)&&!oe(H))throw H;C({path:L.path,size:null,type:"file",reason:oe(H)?"changed-during-read":"unreadable"});continue}if(Ze(n)<1)break;if(L.type==="symlink"&&q.isSymbolicLink()){if(await at(Y,L.path,q),Ze(n)<1)break;continue}if(L.type!=="file"||!q.isFile()||q.isSymbolicLink()){C({path:L.path,size:q.isFile()?q.size:null,type:q.isDirectory()?"directory":q.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await G(Y,L.path,q),Ze(n)<1)break}Ze(n)>=1&&await We();let A=await om({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=mx(_.evidence,A.evidence);g=I.evidence;for(let L of[..._.omissions,...A.omissions,...I.omissions])m.some(Y=>Y.path===L.path&&Y.reason===L.reason)||C(L)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let R=xi(_);for(let Z of R.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);I=A.size>0}let L=new Set,Y=!0;try{let R=await kn(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)I=!1,Y=!1,A.clear();else for(let Z of R.records){let te=So(Z),we=te.indexOf(" "),he=we<0?null:cr(te.slice(we+1));if(we!==1||he===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");te[0]!=="H"&&L.add(he)}}catch(R){if(sr(R))throw R;I=!1,Y=!1,A.clear()}let q=new Set;try{let R=await ko(n,s,["ls-files","--modified","-z"],Fl);for(let Z of R.toString("utf8").split("\0")){let te=cr(Z);te!==null&&q.add(te)}}catch{I=!1,Y=!1,A.clear()}let H=new Set,ee=new Set;for(let R of km(Pe)){if(S.has(R)||!bn(e,R))continue;if(Ze(n)<1)break;if(!um(r,R,n))continue;if(Ze(n)<1)break;let Z=D.resolve(s,...R.split("/"));if(Z===f||Z===p||et(d,Z)||v.some(Re=>et(Re,Z)))continue;if(Pe.gitlinks.has(R)){if(h.length>=i.maxFiles){C({path:R,size:0,type:"file",reason:"file-count"});continue}let Re,ta;try{[Re,ta]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(ta.isSymbolicLink()||!ta.isDirectory()||!V(c,Re)||et(u,Re)){C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let ji=await cm(n,Re);if(ji.dirty){C({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await pe({path:R,hash:ji.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:Re,stat:ta,hash:ji.hash})}catch(ji){if(sr(ji))throw ji;C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let te;try{te=await X.lstat(Z)}catch(Re){if(oe(Re)&&Pe.tracked.has(R)){y.set(R,Z);continue}if(!se(Re)&&!oe(Re))throw Re;C({path:R,size:null,type:"file",reason:oe(Re)?"changed-during-read":"unreadable"});continue}if(te.isSymbolicLink()){await at(Z,R,te);continue}if(!te.isFile()){Pe.nestedRepositories.has(R)||C({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let we=Pe.trackedObjectIds.get(R),he=we?A.get(R):void 0;if(I&&he?.gitObjectId!==void 0&&he.gitObjectId===we&&!L.has(R)&&!q.has(R)){if(h.length>=i.maxFiles){C({path:R,size:he.size,type:"file",reason:"file-count"});continue}if(he.size>i.maxFileBytes){C({path:R,size:he.size,type:"file",reason:"file-size"});continue}if(b+he.size>i.maxTotalBytes){C({path:R,size:he.size,type:"file",reason:"total-size"});continue}h.push({...he}),b+=he.size,H.add(R);continue}let Cd=Y&&!L.has(R)&&!q.has(R)?we:void 0;await G(Z,R,te,Cd),Cd!==void 0&&ee.add(R)}if(await We(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Nm(n,e,a,Pe,t.gitSelectionHooks?.outputChunkBytes),H.size>0||I&&ee.size>0){let R=await ko(n,s,["ls-files","--modified","-z"],Fl),Z=new Set;for(let te of R.toString("utf8").split("\0")){let we=cr(te);we!==null&&Z.add(we)}for(let te of H){if(!Z.has(te))continue;let we=h.find(he=>he.path===te);Q(te,{path:te,size:we?.size??null,type:"file",reason:"changed-during-read"})}for(let te of ee){if(!Z.has(te))continue;let we=h.find(he=>he.path===te);we&&delete we.gitObjectId}}for(let R of Pe.omissions)C(R);Pe.overflow&&O(Pe.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let oy=Pe===null?{provider:"physical-tree",...g?{physicalSelection:g}:{}}:{provider:"git",...Pe.evidence?{gitSelection:Pe.evidence}:{}},Ed=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:oy,createdAt:(t.now??new Date).toISOString(),complete:N===0,limits:i,...r?{policy:r.manifest}:{},entries:h,omitted:m,omittedCount:N,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:k}}:{}}),Ns=Ed();for(;Jl(Ns)>i.maxManifestBytes;){if(m.filter(A=>!ql(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I<A;I+=1){let L=Eo(m);if(L===null)break;w(L)}}else if(h.length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let I of h.splice(-A))N+=1,T(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Ns=Ed()}return Ns}async function Gl(e,t,i={}){let n=(await Ee(e.projectRoot))?.native.snapshot??El;return xm(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Po(e,t){let i=xx(e,t),r=le(e,i);await J(r,i);try{let n=await Zh({root:r,file:i,maxBytes:LC,label:"Native baseline snapshot manifest"});return xi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as zx}from"crypto";import Jx from"path";var Be=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{constants as Ro,promises as tt}from"node:fs";import it from"node:path";import{TextDecoder as Vx}from"node:util";import Hx from"path";var Tx=Rr(Ji(),1);var J0=4*1024*1024;var jx=null;function $x(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Pm(e,t){return(...i)=>{let r=jx;if(r===null)return t(...i);let n=$x(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var X0=Pm("hookWritePolicy",async e=>(await ml(e))?.hook??{allow_paths:[]});var Rm=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Cn(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function En(e,t){let i=Cn(e,t);if(Hx.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function Dx(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Am(e){if(!e.run_id)return null;let t=Cn(e,"run_id"),i=Cn(e,"skill"),r=Cn(e,"skill_version"),n=Cn(e,"skill_hash"),a=En(e,"pending_ref"),o=En(e,"trajectory_ref"),s=En(e,"context_ref"),c=En(e,"artifacts_ref"),l=En(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:Rm(e,"current_step"),iteration:u,pending:Rm(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:Dx(e)}}var GH=256*1024;var Lx=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function Bx(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=Am(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Ul(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!Lx.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return Bx(t)}var ur={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function _o(e,t){let i=it.relative(e,t);return i===""||!it.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${it.sep}`)}function Fx(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ao(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function qx(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Io(e,t,i){let r=Be[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=it.resolve(e),a=it.resolve(n,...r.slice(8).split("/"));if(!_o(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function _m(e){let t=await tt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await tt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Mx(e,t){let i=it.resolve(e),r=it.resolve(t);if(!_o(i,r))throw new Error("Native Run path is outside its change");let n=[await _m(i)],a=i;for(let o of it.relative(i,r).split(it.sep).filter(Boolean)){a=it.join(a,o);let s;try{s=await _m(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!_o(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Im(e){for(let t of e){let i=await tt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!qx(t,i)||await tt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function Wx(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function To(e,t,i,r,n){let a=await Mx(e,it.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await tt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=Fx(o),c=await tt.realpath(t);if(!_o(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Ro.O_RDONLY:Ro.O_RDONLY|Ro.O_NOFOLLOW|Ro.O_NONBLOCK,u;try{u=await tt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Im(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Ao(s,d)||!Ao(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await Wx(u,i,r);await n?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Im(a),!m.isFile()||m.isSymbolicLink()||S!==c||!Ao(s,h)||!Ao(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new Vx("utf-8",{fatal:!0}).decode(v)}catch(N){throw new Error(`${r} is not valid UTF-8`,{cause:N})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function Tm(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Kl(e){return Ul(e)}async function dr(e,t){let i=Io(e,"stateRef"),r=await To(e,i,ur.runStateBytes,"Native Run state",t);return r?Ul(Tm(r.text,"Native Run state")):null}async function Pi(e,t,i){let r=Io(e,"trajectoryRef",t),n=await To(e,r,ur.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>ur.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ur.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function jm(e,t,i){return(await To(e,Io(e,"trajectoryRef",t),ur.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function jo(e,t,i){let r=await To(e,Io(e,"checkpointRef",t),ur.checkpointBytes,"Native Run checkpoint",i);return r?Tm(r.text,"Native Run checkpoint"):null}var Gx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Yl(e){return zx("sha256").update(e).digest("hex")}function Ux(e,t){if(!Gx.test(t))throw new Error(`Invalid Native change name: ${t}`);return Jx.join(U(e,t),"trajectory.jsonl")}function Kx(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function Yx(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function Xx(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=Kx(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
|
|
159
|
-
`)])}catch(d){if(!
|
|
160
|
-
${t}`).digest("hex")}async function
|
|
158
|
+
${Buffer.byteLength(r)}:${r}`)}function ql(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Po(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!ql(i))return e.splice(t,1),i}return null}function ai(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kx(e,t,i,r){if(!$(r))return{status:"budget-exhausted"};let n;try{n=await X.open(e,"r")}catch(c){if(!$(r))return{status:"budget-exhausted"};throw c}if(!$(r))return await n.close(),{status:"budget-exhausted"};let a=Ro("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!$(r))return{status:"budget-exhausted"};let c=await n.stat();if(!$(r))return{status:"budget-exhausted"};if(!c.isFile()||!ai(i,c))return{status:"changed"};for(;;){if(!$(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!$(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!$(r))return{status:"budget-exhausted"};let d=await n.stat();return $(r)?!d.isFile()||!ai(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function De(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Le(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function cr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ft(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Sm(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=D.posix.normalize(e);if(i!==e||D.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function Sx(e,t){let i=De(e,`Native snapshot entry ${t}`);Le(i,YC,`Native snapshot entry ${t}`);let r=Sm(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Ao.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:ft(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!pm.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function Ex(e,t){let i=De(e,`Native snapshot omission ${t}`);if(Le(i,XC,`Native snapshot omission ${t}`),!ex.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!tx.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Sm(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:ft(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function Cx(e){let t=De(e,"Native snapshot omission overflow");if(Le(t,QC,"Native snapshot omission overflow"),typeof t.hash!="string"||!Ao.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:cr(t.count,"Native snapshot omission overflow count")}}function sr(e,t){let i=De(e,t);if(Le(i,GC,t),typeof i.hash!="string"||!Ao.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=ft(i.recordCount,`${t} recordCount`),n=ft(i.storedRecordCount,`${t} storedRecordCount`),a=ft(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function um(e){let t=De(e,"Native Git selection evidence");if(Le(t,JC,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=sr(t.stageBefore,"Native Git selection stageBefore"),r=sr(t.combined,"Native Git selection combined"),n=sr(t.stageAfter,"Native Git selection stageAfter"),a=sr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=sr(t.finalCombined,"Native Git selection finalCombined"),s=sr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!oi(i,n)||!oi(n,a)||!oi(r,o)||!oi(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function dm(e,t){let i=De(e,t);if(Le(i,KC,t),typeof i.hash!="string"||!Ao.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=ft(i.visitedNodeCount,`${t} visitedNodeCount`),n=ft(i.recordCount,`${t} recordCount`),a=ft(i.storedRecordCount,`${t} storedRecordCount`),o=ft(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function xx(e){let t=De(e,"Native physical selection evidence");if(Le(t,UC,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=dm(t.before,"Native physical selection before"),r=dm(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!Nm(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function xi(e){let t=De(e,"Native content snapshot manifest");if(Le(t,FC,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!ZC.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=De(t.capture,"Native content snapshot capture");if(Le(b,WC,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=b.gitSelection===void 0?void 0:um(b.gitSelection),g=b.physicalSelection===void 0?void 0:xx(b.physicalSelection),w=null;if(b.projection!==void 0){let C=De(b.projection,"Native content snapshot projection");if(Le(C,zC,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...C.selection===void 0?{}:{selection:um(C.selection)}}}if(b.provider==="git"){if(g||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...g?{physicalSelection:g}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=De(t.limits,"Native content snapshot limits");Le(r,qC,"Native content snapshot limits");let n={maxFiles:cr(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:cr(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:cr(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:cr(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:cr(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=De(t.policy,"Native snapshot policy");if(Le(b,MC,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=km({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(Sx),s=t.omitted.map(Ex),c=ft(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:Cx(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,x)=>b+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Ml||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(b=>b.reason==="physical-enumeration-limit"),S=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...S])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,N=y?.status==="overflow"||y?.status==="overflow-and-changed",k=y?.status==="changed"||y?.status==="overflow-and-changed";if(N!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(k!==(S.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Jl(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}async function Em(e,t,i={}){let r=xi(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=D.resolve(e.projectRoot),a=hm(i),o=mm(i.gitSelectionLimits),s=await wm(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(bm(s).filter(g=>kn(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>kn(e,g)),d=(g,w)=>w.some(C=>g===C||g.startsWith(`${C}/`)),f=g=>d(g,l),p=g=>d(g,u),v=[...r.entries.map(g=>g.path),...r.omitted.flatMap(g=>g.type==="directory"?[g.path,`${g.path}/`]:[g.path])].filter(g=>!c.has(g)&&!f(g)&&!p(g)),h=await lx(a,n,v),m=r.entries.filter(g=>!f(g.path)&&!p(g.path)&&kn(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await ym(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let S=[...s.omissions];for(let g of l)S.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((g,w)=>g.path.localeCompare(w.path,"en"));let y=r.omitted.filter(g=>f(g.path)||p(g.path)||!kn(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(w=>w.startsWith(`${g.path}/`)):!0);for(let g of S)y.some(w=>w.path===g.path&&w.reason===g.reason)||y.push(g);y.sort((g,w)=>g.path.localeCompare(w.path,"en"));let N=r.omissionOverflow?.count??0,k=r.omissionOverflow?.hash??K("comet.native.snapshot-omission-overflow.v1");s.overflow&&(N+=s.overflow.count,k=En(k,"git-selection",{source:"git-selection",...s.overflow}));let E=g=>{N+=1,k=En(k,"omission",g)};for(;y.length>Ml;){let g=Po(y);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");E(g)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+N===0,entries:m,omitted:y,omittedCount:y.length+N,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:N}}:{}}),x=b();for(;Jl(x)>r.limits.maxManifestBytes;){let g=Po(y);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");E(g),x=b()}return xi(x)}function Px(e,t){if(!VC.test(t))throw new Error(`Invalid Native change name: ${t}`);return D.join(U(e,t),"baseline-manifest.json")}async function Cm(e,t={}){let i={maxFiles:t.limits?.maxFiles??Eo.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Eo.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Eo.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Eo.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=km(t.policy),n=hm({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=mm(t.gitSelectionLimits),o=sx(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=D.resolve(e.projectRoot),c=await X.realpath(s),l=D.resolve(e.nativeRoot),u=await X.realpath(l),d=D.resolve(e.runtimeDir),f=D.resolve(e.configFile),p=D.join(s,".comet","current-change.json"),v=wx(s,t.denylist??[]),h=[],m=[],S=new Map,y=new Map,N=0,k=0,E=K("comet.native.snapshot-omission-overflow.v1"),b=0,x=!1,g=null,w=_=>{k+=1,E=En(E,"omission",_)},C=_=>{if(N+=1,m.length<Ml){m.push(_);return}if(ql(_)){let A=Po(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),m.push(_);return}w(_)},O=_=>{N+=_.count,k+=_.count,E=En(E,"git-selection",{source:"git-selection",..._})},T=_=>{k+=1,E=En(E,"manifest-entry",{reason:"manifest-size",entry:_})},he=async(_,A)=>{h.push(_),b+=_.size,S.set(_.path,A),x||(x=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Q=(_,A)=>{let I=h.findIndex(Y=>Y.path===_);if(I<0)return;let[L]=h.splice(I,1);b-=L.size,S.delete(_),C(A)},G=async(_,A,I,L)=>{if(!I.isFile()||I.isSymbolicLink()||!$(n))return;let Y;try{Y=await X.realpath(_)}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!$(n)||!V(c,Y)||et(u,Y))return;if(h.length>=i.maxFiles){C({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){C({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){C({path:A,size:I.size,type:"file",reason:"total-size"});return}let q,H,ee;try{if(q=await kx(Y,I.size,I,n),q.status==="budget-exhausted"||!$(n))return;if(q.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!$(n)||(ee=await X.realpath(_),!$(n)))return;H=await X.lstat(_)}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if($(n)){if(q.bytes!==I.size||ee!==Y||!ai(I,q.finalStat)||!ai(q.finalStat,H)||!H.isFile()||H.isSymbolicLink()||H.size!==I.size||H.mtimeMs!==I.mtimeMs||H.ctimeMs!==I.ctimeMs){C({path:A,size:H.isFile()?H.size:null,type:H.isFile()?"file":"other",reason:"changed-during-read"});return}$(n)&&await he({path:A,hash:q.hash,size:H.size,type:"file",...L===void 0?{}:{gitObjectId:L}},{kind:"file",target:_,realTarget:Y,stat:H})}},at=async(_,A,I)=>{if(!$(n))return;let L,Y,q;try{if(L=await X.readlink(_,{encoding:"buffer"}),!$(n)||(q=await X.lstat(_),!$(n)))return;Y=await X.readlink(_,{encoding:"buffer"})}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:null,type:"other",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!$(n))return;if(!q.isSymbolicLink()||!ai(I,q)||q.mtimeMs!==I.mtimeMs||q.ctimeMs!==I.ctimeMs||!L.equals(Y)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let H=L.byteLength;if(h.length>=i.maxFiles){C({path:A,size:H,type:"other",reason:"file-count"});return}if(H>i.maxFileBytes){C({path:A,size:H,type:"other",reason:"file-size"});return}if(b+H>i.maxTotalBytes){C({path:A,size:H,type:"other",reason:"total-size"});return}let ee=Ro("sha256").update("symlink\0").update(L).digest("hex");$(n)&&await he({path:A,hash:ee,size:H,type:"file"},{kind:"symlink",target:_,rawTarget:L,stat:q})},We=async()=>{for(let[_,A]of[...S]){if(!$(n))return;if(A.kind==="file"){let H,ee;try{if(H=await X.realpath(A.target),!$(n))return;ee=await X.lstat(A.target)}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"file",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!$(n))return;(H!==A.realTarget||!ee.isFile()||ee.isSymbolicLink()||!ai(A.stat,ee)||ee.size!==A.stat.size||ee.mtimeMs!==A.stat.mtimeMs||ee.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:ee.isFile()?ee.size:null,type:ee.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let H,ee;try{if(H=await X.lstat(A.target),!$(n))return;ee=await X.readlink(A.target,{encoding:"buffer"})}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"other",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!$(n))return;(!H.isSymbolicLink()||!ai(A.stat,H)||H.mtimeMs!==A.stat.mtimeMs||H.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ee))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,L;try{if(I=await X.realpath(A.target),!$(n))return;L=await X.lstat(A.target)}catch{if(!$(n))return;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!$(n))return;if(!(I===A.realTarget&&L.isDirectory()&&!L.isSymbolicLink()&&ai(A.stat,L)&&V(c,I)&&!et(u,I))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let q;try{if(!$(n))return;q=await sm(n,I)}catch(H){if(lr(H))throw H;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!$(n))return;q.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):q.hash!==A.hash&&Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!$(n))return;try{let I=await X.lstat(A);if(!$(n))return;C({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!$(n))return;if(oe(I))continue;if(!se(I))throw I;C({path:_,size:null,type:"file",reason:"unreadable"})}}},Pe=await wm(n,e,a,t.gitSelectionHooks);if(Pe===null){let _=await am({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let L of _.records){if(L.type!=="file"&&L.type!=="symlink"||S.has(L.path))continue;if(Ze(n)<1)break;if(!lm(r,L.path,n))continue;if(Ze(n)<1)break;let Y=D.resolve(s,...L.path.split("/")),q;try{q=await X.lstat(Y)}catch(H){if(!$(n))break;if(!se(H)&&!oe(H))throw H;C({path:L.path,size:null,type:"file",reason:oe(H)?"changed-during-read":"unreadable"});continue}if(Ze(n)<1)break;if(L.type==="symlink"&&q.isSymbolicLink()){if(await at(Y,L.path,q),Ze(n)<1)break;continue}if(L.type!=="file"||!q.isFile()||q.isSymbolicLink()){C({path:L.path,size:q.isFile()?q.size:null,type:q.isDirectory()?"directory":q.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await G(Y,L.path,q),Ze(n)<1)break}Ze(n)>=1&&await We();let A=await am({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=vx(_.evidence,A.evidence);g=I.evidence;for(let L of[..._.omissions,...A.omissions,...I.omissions])m.some(Y=>Y.path===L.path&&Y.reason===L.reason)||C(L)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let R=xi(_);for(let Z of R.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);I=A.size>0}let L=new Set,Y=!0;try{let R=await Sn(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)I=!1,Y=!1,A.clear();else for(let Z of R.records){let te=xo(Z),we=te.indexOf(" "),me=we<0?null:ur(te.slice(we+1));if(we!==1||me===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");te[0]!=="H"&&L.add(me)}}catch(R){if(lr(R))throw R;I=!1,Y=!1,A.clear()}let q=new Set;try{let R=await Co(n,s,["ls-files","--modified","-z"],Fl);for(let Z of R.toString("utf8").split("\0")){let te=ur(Z);te!==null&&q.add(te)}}catch{I=!1,Y=!1,A.clear()}let H=new Set,ee=new Set;for(let R of bm(Pe)){if(S.has(R)||!kn(e,R))continue;if(Ze(n)<1)break;if(!lm(r,R,n))continue;if(Ze(n)<1)break;let Z=D.resolve(s,...R.split("/"));if(Z===f||Z===p||et(d,Z)||v.some(Re=>et(Re,Z)))continue;if(Pe.gitlinks.has(R)){if(h.length>=i.maxFiles){C({path:R,size:0,type:"file",reason:"file-count"});continue}let Re,ia;try{[Re,ia]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(ia.isSymbolicLink()||!ia.isDirectory()||!V(c,Re)||et(u,Re)){C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let $i=await sm(n,Re);if($i.dirty){C({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await he({path:R,hash:$i.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:Re,stat:ia,hash:$i.hash})}catch($i){if(lr($i))throw $i;C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let te;try{te=await X.lstat(Z)}catch(Re){if(oe(Re)&&Pe.tracked.has(R)){y.set(R,Z);continue}if(!se(Re)&&!oe(Re))throw Re;C({path:R,size:null,type:"file",reason:oe(Re)?"changed-during-read":"unreadable"});continue}if(te.isSymbolicLink()){await at(Z,R,te);continue}if(!te.isFile()){Pe.nestedRepositories.has(R)||C({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let we=Pe.trackedObjectIds.get(R),me=we?A.get(R):void 0;if(I&&me?.gitObjectId!==void 0&&me.gitObjectId===we&&!L.has(R)&&!q.has(R)){if(h.length>=i.maxFiles){C({path:R,size:me.size,type:"file",reason:"file-count"});continue}if(me.size>i.maxFileBytes){C({path:R,size:me.size,type:"file",reason:"file-size"});continue}if(b+me.size>i.maxTotalBytes){C({path:R,size:me.size,type:"file",reason:"total-size"});continue}h.push({...me}),b+=me.size,H.add(R);continue}let Ed=Y&&!L.has(R)&&!q.has(R)?we:void 0;await G(Z,R,te,Ed),Ed!==void 0&&ee.add(R)}if(await We(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await ym(n,e,a,Pe,t.gitSelectionHooks?.outputChunkBytes),H.size>0||I&&ee.size>0){let R=await Co(n,s,["ls-files","--modified","-z"],Fl),Z=new Set;for(let te of R.toString("utf8").split("\0")){let we=ur(te);we!==null&&Z.add(we)}for(let te of H){if(!Z.has(te))continue;let we=h.find(me=>me.path===te);Q(te,{path:te,size:we?.size??null,type:"file",reason:"changed-during-read"})}for(let te of ee){if(!Z.has(te))continue;let we=h.find(me=>me.path===te);we&&delete we.gitObjectId}}for(let R of Pe.omissions)C(R);Pe.overflow&&O(Pe.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let oy=Pe===null?{provider:"physical-tree",...g?{physicalSelection:g}:{}}:{provider:"git",...Pe.evidence?{gitSelection:Pe.evidence}:{}},Sd=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:oy,createdAt:(t.now??new Date).toISOString(),complete:N===0,limits:i,...r?{policy:r.manifest}:{},entries:h,omitted:m,omittedCount:N,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:k}}:{}}),ks=Sd();for(;Jl(ks)>i.maxManifestBytes;){if(m.filter(A=>!ql(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I<A;I+=1){let L=Po(m);if(L===null)break;w(L)}}else if(h.length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let I of h.splice(-A))N+=1,T(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");ks=Sd()}return ks}async function Gl(e,t,i={}){let n=(await Ee(e.projectRoot))?.native.snapshot??El;return Cm(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function _o(e,t){let i=Px(e,t),r=ue(e,i);await J(r,i);try{let n=await Qh({root:r,file:i,maxBytes:BC,label:"Native baseline snapshot manifest"});return xi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as Jx}from"crypto";import Gx from"path";var Be=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{constants as Io,promises as tt}from"node:fs";import it from"node:path";import{TextDecoder as Fx}from"node:util";import Dx from"path";var jx=_r(Gi(),1);var G0=4*1024*1024;var $x=null;function Ox(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function xm(e,t){return(...i)=>{let r=$x;if(r===null)return t(...i);let n=Ox(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var Q0=xm("hookWritePolicy",async e=>(await ml(e))?.hook??{allow_paths:[]});var Pm=(e,t)=>{let i=e[t];return i==null?null:String(i)};function xn(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Cn(e,t){let i=xn(e,t);if(Dx.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function Lx(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Rm(e){if(!e.run_id)return null;let t=xn(e,"run_id"),i=xn(e,"skill"),r=xn(e,"skill_version"),n=xn(e,"skill_hash"),a=Cn(e,"pending_ref"),o=Cn(e,"trajectory_ref"),s=Cn(e,"context_ref"),c=Cn(e,"artifacts_ref"),l=Cn(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:Pm(e,"current_step"),iteration:u,pending:Pm(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:Lx(e)}}var YH=256*1024;var Bx=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function Vx(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=Rm(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Ul(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!Bx.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return Vx(t)}var fr={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function jo(e,t){let i=it.relative(e,t);return i===""||!it.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${it.sep}`)}function qx(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function To(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Mx(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function $o(e,t,i){let r=Be[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=it.resolve(e),a=it.resolve(n,...r.slice(8).split("/"));if(!jo(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function Am(e){let t=await tt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await tt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Wx(e,t){let i=it.resolve(e),r=it.resolve(t);if(!jo(i,r))throw new Error("Native Run path is outside its change");let n=[await Am(i)],a=i;for(let o of it.relative(i,r).split(it.sep).filter(Boolean)){a=it.join(a,o);let s;try{s=await Am(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!jo(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function _m(e){for(let t of e){let i=await tt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Mx(t,i)||await tt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function zx(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Oo(e,t,i,r,n){let a=await Wx(e,it.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await tt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=qx(o),c=await tt.realpath(t);if(!jo(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Io.O_RDONLY:Io.O_RDONLY|Io.O_NOFOLLOW|Io.O_NONBLOCK,u;try{u=await tt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await _m(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!To(s,d)||!To(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await zx(u,i,r);await n?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await _m(a),!m.isFile()||m.isSymbolicLink()||S!==c||!To(s,h)||!To(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new Fx("utf-8",{fatal:!0}).decode(v)}catch(N){throw new Error(`${r} is not valid UTF-8`,{cause:N})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function Im(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Kl(e){return Ul(e)}async function pr(e,t){let i=$o(e,"stateRef"),r=await Oo(e,i,fr.runStateBytes,"Native Run state",t);return r?Ul(Im(r.text,"Native Run state")):null}async function Pi(e,t,i){let r=$o(e,"trajectoryRef",t),n=await Oo(e,r,fr.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>fr.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${fr.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function Tm(e,t,i){return(await Oo(e,$o(e,"trajectoryRef",t),fr.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Ho(e,t,i){let r=await Oo(e,$o(e,"checkpointRef",t),fr.checkpointBytes,"Native Run checkpoint",i);return r?Im(r.text,"Native Run checkpoint"):null}var Ux=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Yl(e){return Jx("sha256").update(e).digest("hex")}function Kx(e,t){if(!Ux.test(t))throw new Error(`Invalid Native change name: ${t}`);return Gx.join(U(e,t),"trajectory.jsonl")}function Yx(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function Xx(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function Qx(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=Yx(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
|
|
159
|
+
`)])}catch(d){if(!Xx(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Yl(t),targetHash:Yl(l),tailHash:Yl(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Zx(e,t){let i=Kx(e,t);await J(ue(e,i),i);let r=U(e,t),n=await Tm(r,Be.trajectoryRef);return n===null?{status:"clean",file:i}:Qx(i,Buffer.from(n))}async function jm(e,t){let i=await Zx(e,t);return"inspection"in i?i.inspection:i}import{createHash as eP}from"node:crypto";import{promises as Do}from"node:fs";import xt from"node:path";var Pn=/^[a-f0-9]{64}$/u,$m=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,tP=16*1024,Ql=process.platform,iP=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function hr(e){return iP.has(e)}function Lm(e,t){let i=xt.relative(e,t);return xt.isAbsolute(i)||i===".."||i.startsWith(`..${xt.sep}`)?null:i.replaceAll("\\","/")||"."}function Bm(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Vm(e,t){if(e.length===0||Bm(e)||e.includes("\\")||xt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=xt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Zl(e,t){return eP("sha256").update(`${e}
|
|
160
|
+
${t}`).digest("hex")}async function Om(e,t){let i=await Do.realpath(t),r=await Do.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Ql==="win32"?xt.normalize(i).toLowerCase():i;return Zl(e,`${n}
|
|
161
161
|
${r.dev}
|
|
162
162
|
${r.ino}
|
|
163
|
-
${r.birthtimeMs}`)}async function
|
|
163
|
+
${r.birthtimeMs}`)}async function Hm(e,t){let i=await Do.realpath(t),r=await Do.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Ql==="win32"?xt.normalize(i).toLowerCase():i;return Zl(e,n)}function rP(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 Xl(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Bm(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Fm(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Xl(e.changeBranch,"Native workspace change branch"),Xl(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 nP(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!$m.test(t.baseCommit)||typeof t.targetCommit!="string"||!$m.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Xl(t.targetBranch,"Native workspace Git target branch")}function Lo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Pn.test(String(t.projectRootId))||!Pn.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");rP(t.capturedAt),Vm(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&&!Pn.test(String(t.projectRootPathId))||a&&!Pn.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Pn.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&nP(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(Fm(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 aP(e,t){return xt.join(U(e,t),"workspace.json")}function oP(e,t){let i=aP(e,t),r=ue(e,i),n=Lm(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Vm(n,"Native workspace file ref")}}async function sP(e,t){try{let i=oP(e,t),r=await ne({root:i.root,ref:i.ref,maxBytes:tP});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Rn(e,t){let i=be(e.projectRoot),r={projectRoot:xt.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await Pt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await An({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function cP(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Lm(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=be(e.paths.projectRoot),r=i.isGitWorktree?gi(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:gi(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([Om("comet.native.workspace-project-root.v2",e.paths.projectRoot),Om("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Hm("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Hm("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&Fm(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Zl("comet.native.workspace-session.v2",`${s}
|
|
164
164
|
${c}
|
|
165
|
-
${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Oo(p),p}async function Pt(e,t){let i=await oP(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Oo(i),i)}async function Ho(e){Oo(e.identity);let t=await sP({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Ql==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function Rn(e){if(Oo(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Ho(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=be(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function Mm(e,t){let i=await Pt(e,t);if(i===null)return null;let r=await Rn({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var Jm=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],lP=new Set(Jm),Gm=new Set([...Jm,"minimum_runtime_version","revision"]),uP=new Set([...Gm,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),dP=new Set(["capability","operation","source","base_hash"]),fP=new Set(["shape","build","verify","archive"]),pP=new Set(["implicit","confirmed"]),hP=new Set(["pending","pass","fail"]),si="comet-state.yaml",tu=/^[a-f0-9]{64}$/u,Um=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mP=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Do=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Ri=class extends Error{constructor(i,r){super(i!==ti||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Lo=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},An=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Bo=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},zD=ro("en");function In(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Km(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Vo(e){if(!Um.test(e))throw new Error(`Invalid Native change name: ${e}`)}function vP(e){if(!Um.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Ym(e,t){if(e.length===0||Rt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function gP(e,t){let i=In(e,`spec_changes[${t}]`);if(Km(i,dP,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(vP(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&Ym(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!tu.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!tu.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function wP(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 ru(e,t){if(Km(e,t,si),typeof e.name!="string")throw new Error("Native change name is required");if(Vo(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"||!fP.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&&!pP.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(gP),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!hP.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"&&Ym(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!wP(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function rr(e){let t=In(e,si);if(t.schema!==ri)throw new Error(`Expected ${ri}`);return{schema:ri,...ru(t,lP)}}function _n(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function eu(e,t,i){if(e===null)return null;let r=typeof e=="string"?mP.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function yP(e){if(e==null)return null;if(typeof e!="string"||!tu.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function NP(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 nr(e){let t=In(e,si);if(t.schema!==ii)throw new Error(`Expected ${ii}`);if(_n(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ii} minimum_runtime_version must be 2`);return{schema:ii,minimum_runtime_version:2,revision:_n(t.revision,"Native v2 revision"),...ru(t,Gm)}}function ni(e){let t=In(e,si);if(t.schema!==ti){if(t.schema===ri||t.schema===ii){let o=t.schema===ri?rr(t):nr(t);throw new Do(o.name,o.schema)}throw new Ri(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=_n(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Ri(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=_n(t.revision,"Native revision"),n=ru(t,uP),a=yP(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ti,minimum_runtime_version:3,revision:r,verification_protocol:NP(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:eu(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:eu(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:eu(t.partial_allowance,"Native partial_allowance","allowances")}}function Xm(e){let t=In(e,si);if(t.schema===ri){let n=rr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ti}`}}if(t.schema===ii){let n=nr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ti}`}}if(t.schema!==ti){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 Ri(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=_n(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Ri(t.schema,i).message};let r=ni(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function fe(e,t){Vo(t);let i=Rt.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Fo(e,t){let i=U(e,t),r=Rt.join(i,"schema-migration.json");await J(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await zm.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Qm(e,t){let i=U(e,t),r=Rt.join(i,"checkpoint-journal.json");await J(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await zm.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Zm(e,t=Rt.dirname(e)){let i=Rt.relative(t,e).split(Rt.sep).join("/"),r=await ne({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,iu.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function nu(e,t){let i=Rt.join(fe(e,t),si);await J(e.nativeRoot,i);let r=Xm(await Zm(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Fo(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await bP(e,r.state),r)}async function ev(e,t){let i=Rt.join(fe(e,t),si);await J(e.nativeRoot,i);let r=Xm(await Zm(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function bP(e,t){if(await Po(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function At(e,t){let i=await nu(e,t);if(i.status==="migration-required")throw new Do(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Ri(i.schema,i.minimumRuntimeVersion);return await Mm(e,t),i.state}import{promises as WI}from"fs";import{promises as au}from"fs";import tv from"path";var iv=["outcome","scope","nonGoals","acceptanceExamples"],kP=[...iv,"constraints","decisions","openQuestions","verificationExpectations"],SP=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],rv={maxFileBytes:cn};function nv(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
|
|
166
|
-
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function
|
|
167
|
-
`))}function PP(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(sv))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(sv))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=cv(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:lv(e.markdown)},markdown:e.markdown}}function RP(e,t){return uv(e.id,t.id)}function uv(e,t){return e<t?-1:e>t?1:0}function dv(e){let t=cv(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(PP).sort((d,f)=>uv(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Al(e.briefMarkdown,t,jn.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(..._l(f,d.source,jn.maxAcceptanceCriteria-a.length)),a.push(...zh(f,d.source,jn.maxAcceptanceCriteria-a.length)));if(a.sort(RP),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>jn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${jn.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:lv(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=j(xP,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(CP,u)}}var Mo={maxSpecs:64,maxFileBytes:cn,maxTotalBytes:4*1024*1024};async function pr(e){if(e.specChanges.length>Mo.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ne({root:e.changeDir,ref:e.briefRef,maxBytes:Mo.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ne({root:e.changeDir,ref:n.source,maxBytes:Mo.maxFileBytes});if(i+=a.size,i>Mo.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:dv({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import AP from"path";var cu="comet.selection.v2",_P=16*1024;function pv(e){return AP.join(e,".comet","current-change.json")}function IP(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function fv(e){return e===null||typeof e=="string"}function TP(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!IP(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&&!fv(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:cu,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==cu)throw new Error(`current change selection schema must be ${cu}`);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(!fv(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 hv(e){let t;try{let r=pv(e),{bytes:n}=await Ui(r,_P,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...TP(t)}}import{promises as ER}from"node:fs";import yu from"node:path";var mu=Rr(Ji(),1);import{promises as Pv}from"node:fs";import Ve from"node:path";import{execFileSync as jP}from"node:child_process";var $P=3e4,OP=8*1024*1024,lu=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function HP(e,t){try{return jP("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:$P,maxBuffer:OP,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new lu(e,t,r)}}function Wo(e,t){return HP(e,t).trim()}import du from"node:path";import{promises as mv}from"node:fs";var zo=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var uu="comet.native.supervisor.v2",LP=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function BP(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 VP(e,t){return du.join(Zt(e,t),"supervisor")}function vv(e,t){return du.join(VP(e,t),"state.json")}function gv(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!==uu)throw new Error(`Native Supervisor state schema must be ${uu}`);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($n(t.integration.targetCommit,"Native Supervisor target commit"),$n(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&$n(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($n(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function On(e,t){try{let i=await mv.readFile(vv(e,t),"utf8"),r=JSON.parse(i);return gv(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function fu(e,t){gv(t),await mv.mkdir(e.changesRuntimeDir,{recursive:!0}),await Ye(vv(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function $n(e,t){if(!LP.test(e))throw new Error(`${t} must be a Git commit`)}function FP(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function wv(e){$n(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:uu,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function pu(e){let t=BP(e.parent),i=gi(e.paths.projectRoot,t);if(!i)return null;let r=gi(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Dt(e.paths.projectRoot).map(o=>du.resolve(o)).find(o=>be(o).currentBranch===t);if(!n)return null;let a=wv({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return FP(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function yv(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var Nv="children.yaml",Hn="comet.native.children.v1",hr="comet.native.children.v2",Rv=hr,qP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bv=new Set(["schema","children"]),MP=new Set(["schema","acceptance_index","children"]),WP=new Set(["name","depends_on","covers"]),zP=new Set(["name","summary","depends_on"]),JP=new Set(["name","depends_on","covers"]);function Go(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function Jo(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function kv(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function hu(e,t){let i=Ve.normalize(Ve.resolve(e)),r=Ve.normalize(Ve.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function GP(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function Sv(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function UP(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Rv&&e.acceptance_index){let n=i.requiredAcceptanceIds??t??[],a=Object.keys(e.acceptance_index);r.missing=n.filter(c=>!(c in e.acceptance_index)),r.extra=a.filter(c=>!n.includes(c));let o=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of n){let l=o.get(c),u=e.acceptance_index[c];l&&u&&(u.source!==l.source||u.text!==l.text)&&r.mismatched.push(c)}let s=new Set(a);for(let c of e.children)r.unknownCovers.push(...c.covers.filter(l=>!s.has(l)));return r.uncovered=a.filter(c=>!Ev(e.children,c)),Cv(r)?r:null}if(e.schema===Hn&&t){let n=new Set(t);for(let a of e.children)r.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return r.uncovered=t.filter(a=>!Ev(e.children,a)),Cv(r)?r:null}return null}function Ev(e,t){return e.some(i=>i.covers.includes(t))}function Cv(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Av(e){let t=new Set(e.acceptance.filter(({source:i})=>i===e.brief).map(({id:i})=>i));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let i=[...e.history].reverse().find(({outcome:r})=>r==="fail");for(let r of i?.unresolved_ids??[])t.add(r)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function KP(e){let t=Go(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=Go(n,`Native children acceptance_index.${r}`);if(Jo(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function YP(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=Object.keys(e),a=r.filter(c=>!(c in e)),o=n.filter(c=>!r.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((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of r){let l=s.get(c);if(!l)continue;let u=e[c];if(u.source!==l.source||u.text!==l.text){let d=["source","text"].filter(f=>u[f]!==l[f]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function XP(e,t,i={}){let r=(0,mu.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=Go(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Hn&&a!==hr)throw Jo(n,bv,"Native children contract"),new Error(`Native children schema must be ${Hn} or ${hr}`);let o=a===Hn?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Jo(n,o==="indexed-v2"?MP:bv,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,p)=>{let v=Go(f,`Native child ${p}`);if(Jo(v,o==="indexed-v2"?JP:o==="summary-v2"?zP:WP,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!qP.test(v.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:h?v.summary:null,depends_on:kv(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?kv(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let p=f.depends_on.filter(v=>!u.has(v));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}GP(c);let d=i.policy==="advisory";if(a===Rv){if(o==="indexed-v2"){let f=KP(n.acceptance_index);d||YP(f,t,i);let p=Object.keys(f);return d||Sv(c,p,p),{schema:hr,acceptance_index:f,children:c}}return{schema:hr,children:c}}return t&&!d&&Sv(c,t),{schema:Hn,children:c}}async function _v(e){let t=Ve.join(e.changeDir,Nv);try{await Pv.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await ne({root:e.changeDir,ref:Nv}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=XP(i.text,e.acceptanceIds,n);return{contract:a,size:i.size,drift:r?UP(a,e.acceptanceIds,e.validation??{}):null}}function QP(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function ZP(e){let t=QP(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function Iv(e){try{let t=await ne({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return ZP(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Tv(e){return j("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function eR(e){let t=Dt(e.projectRoot);t.some(r=>hu(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Ve.resolve(n)))]){let n=await Ee(r);n&&i.push({projectRoot:r,paths:await kt(r,n.native.artifact_root),parent:hu(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function tR(e,t){let i=Ve.join(e.paths.changesDir,t,"comet-state.yaml");try{return await wn(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function iR(e,t){let i;try{i=await Pv.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Ve.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await wn(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function rR(e,t,i){let r=Ve.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Ve.sep}`))return null;let n=r.split(Ve.sep).join("/");try{let a=(0,mu.parseDocument)(Wo(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:gn(a.toJS({mapAsMap:!1}))}catch{return null}}function nR(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function xv(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function vu(e){let t=Ve.join(e.paths.changesDir,e.state.name),i=await Iv(t),r=await _v({changeDir:t,validation:Av(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:m})=>m)}:{},policy:"advisory"});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=Tv({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!r.drift;if(r.contract.schema===hr){let m=await On(e.paths,e.state.name);if(!m){let N=e.state.workspace.target_branch??e.state.workspace.change_branch;if(N){let k=await pu({paths:e.paths,parent:e.state.name,targetBranch:N,contract:r.contract});k&&(m=k,await fu(e.paths,k))}}if(m){let N=yv(m);return e.state.children_contract_hash!==n||r.drift?{...N,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(k=>({...k,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let S=new Map(r.contract.children.map(N=>[N.name,N])),y=r.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:o&&N.depends_on.every(k=>r.contract.children.filter(({name:E})=>E!==N.name).every(({name:E})=>E!==k))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let N of y){if(N.status!=="ready")continue;S.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:y,readyChildren:y.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let s=await eR(e.paths),c=new Set(r.contract.children.map(({name:m})=>m)),l=new Map,u=new Map;for(let m of s){let S=m.parent&&a?`refs/heads/${a}`:"HEAD";for(let y of await iR(m,c)){let N={...y,source:m,committedState:rR(m,y.file,S)};l.set(y.state.name,[...l.get(y.state.name)??[],N])}for(let y of c){let N=await tR(m,y);N&&u.set(y,[...u.get(y)??[],{source:m,state:N}])}}let d=new Map;for(let m of r.contract.children){let S=(l.get(m.name)??[]).find(({source:k,committedState:E})=>k.parent&&E?.name===m.name&&xv(E,a));if(S){d.set(m.name,{kind:"done",phase:S.state.phase,projectRoot:S.source.projectRoot,message:null});continue}let y=l.get(m.name)?.[0];if(y){d.set(m.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${m.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let N=u.get(m.name)??[];N.length>1?d.set(m.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${m.name} has multiple active workspace owners`}):N[0]&&d.set(m.name,nR(N[0].state,N[0].source,a))}let f=new Map(r.contract.children.map(m=>[m.name,m])),p=new Map,v=m=>{let S=p.get(m);if(S)return S;let y=f.get(m),k=y.depends_on.map(v).every(({status:C})=>C==="done"),E=d.get(m),b=E?.kind==="active"&&k?y.depends_on.filter(C=>!(l.get(C)??[]).some(({source:O,committedState:T})=>hu(O.projectRoot,E.projectRoot)&&T?.name===C&&xv(T,a))):[],x,g=E?.message??null;E?.kind==="done"?(x=k?"done":"blocked",k||(g=`Native child ${m} was merged before its dependencies`)):E?.kind==="active"?(x=k&&b.length===0?"active":"blocked",k?b.length>0&&(g=`Native child ${m} does not include merged dependencies: ${b.join(", ")}`):g=`Native child ${m} started before its dependencies merged`):E?.kind==="blocked"?x="blocked":(x=o&&k?"ready":"pending",o||(g="Parent Shape confirmation is required"));let w={name:m,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:x,phase:E?.phase??null,projectRoot:E?.projectRoot??null,message:g};return p.set(m,w),w},h=r.contract.children.map(({name:m})=>v(m));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:h,readyChildren:h.filter(({status:m})=>m==="ready").map(({name:m})=>m),allDone:h.every(({status:m})=>m==="done")}}var JL=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var aR=/\b(Bearer|Basic)\s+[^\s"']+/giu,oR=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,sR=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,cR=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,lR=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,uR=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,dR=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function Fe(e){return e.replace(aR,"$1 [REDACTED]").replace(oR,"[REDACTED PRIVATE KEY]").replace(sR,"$1[REDACTED]@").replace(cR,"[REDACTED TOKEN]").replace(lR,'$1"[REDACTED]"').replace(uR,"$1$2$1$3$4[REDACTED]$4").replace(dR,"$1$2[REDACTED]")}import{promises as gR}from"node:fs";import jv from"node:path";function Uo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ko(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function pt(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function $v(e,t){return e===null?null:pt(e,t)}function Xo(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function wR(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 yR(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Yo(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function gu(e,t){if(e===null)return null;let i=pt(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function wu(e,t){let i=pt(e,t);if(!jv.isAbsolute(i))throw new Error(`${t} must be absolute`);return jv.resolve(i)}function NR(e,t){let i=`Native local checks[${t}]`,r=Uo(e,i);if(Ko(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>pt(l,`${i}.argv[${u}]`,!0)),a=Yo(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=gu(r.startedAt,`${i}.startedAt`),s=gu(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=Xo(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:pt(r.id,`${i}.id`),name:pt(r.name,`${i}.name`),operationId:pt(r.operationId,`${i}.operationId`),status:a,repeatable:yR(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Xo(r.executionCount,`${i}.executionCount`),argv:n,cwd:wu(r.cwd,`${i}.cwd`),exitCode:wR(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:pt(r.log,`${i}.log`)}}function bR(e){let t="Native local execution state",i=Uo(e,t);if(Ko(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==vo)throw new Error(`Native local execution schema must be ${vo}`);let r=Uo(i.workspace,"Native local workspace");Ko(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Uo(i.execution,"Native local execution");Ko(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=gu(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:pt(o.operationId,"Native local execution.operationId"),stage:Yo(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Yo(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:$v(o.executionId,"Native local execution.executionId"),status:Yo(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Xo(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(NR);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:vo,change:pt(i.change,"Native local change"),basedOnStateVersion:Xo(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:wu(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:wu(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:$v(r.branch,"Native local workspace.branch")},execution:n,checks:a}}async function Ov(e){let t;try{t=await gR.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return bR(i)}var CR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xR="comet-state.yaml",PR="state.json",y1=ro("en");function Hv(e,t){if(!CR.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=yu.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}function Dv(e,t){return yu.join(Hv(e,t),xR)}function RR(e,t){return yu.join(Zt(e,t),PR)}async function Nu(e,t){try{let i=await ER.readFile(Dv(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function Lv(e,t){return wn(Dv(e,t))}async function Bv(e){let t=await Lv(e.paths,e.name),i=RR(e.paths,e.name);try{let r=await Ov(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var A1=16*1024;async function Vv(e){let t=await hv(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Vo(t.selection.change),t.selection)}async function Fv(e,t){let i=[],r=U(e,t.name),n=ei(r,Be.stateRef),a;try{a=await dr(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=ei(r,a.trajectoryRef),s=await $m(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await Pi(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=ei(r,a.checkpointRef);try{let u=await jo(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import NA from"path";import{isDeepStrictEqual as Vu}from"util";var mr={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var AR=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function _R(e,t){return e<t?-1:e>t?1:0}function IR(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!AR.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(_R)}function bu(e=[]){return IR(e,"Native repair failed check IDs",mr.maxFailedCheckIds,!0)}function qv(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function TR(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:qv(e.failedAcceptanceIds,t.failedAcceptanceIds)&&qv(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function ku(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(TR(r,a))break;i+=1,r=a}return i}import cg from"node:path";import{createHash as Yv}from"node:crypto";import Mv from"path";var Su="comet.native.implementation-scope.v2",Xv="comet.native.content-snapshot-projection.v1",Dn="comet.native.content-snapshot-projection.v1",Qv="comet.native.implementation-scope.v2",jR="comet.native.unresolved-scope-id.v1",$R="comet.native.scope-detail-overflow.v1",OR="comet.native.snapshot-projection-overflow.v2",Pu=/^[a-f0-9]{64}$/u,_i=1024*1024,HR=128,DR=128;function ve(e,t){return e<t?-1:e>t?1:0}function Eu(e){if(!Pu.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function LR(e,t){return e===t?0:e===null?-1:t===null?1:ve(e,t)}function li(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=Mv.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Mv.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Zv(e,t){return e==="."?e:li(e,t)}function vr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function BR(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:li(e.path,`${t} path`),hash:e.hash,size:vr(e.size,`${t} size`),type:"file"}}function VR(e,t){return{path:Zv(e.path,`${t} path`),size:e.size===null?null:vr(e.size,`${t} size`),type:e.type,reason:e.reason}}function FR(e,t){return ve(e.path,t.path)||ve(e.hash,t.hash)||e.size-t.size}function qR(e,t){return ve(e.path,t.path)||ve(e.reason,t.reason)||ve(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Bn(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
165
|
+
${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Lo(p),p}async function Pt(e,t){let i=await sP(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Lo(i),i)}async function Bo(e){Lo(e.identity);let t=await cP({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Ql==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function An(e){if(Lo(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Bo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=be(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function qm(e,t){let i=await Pt(e,t);if(i===null)return null;let r=await An({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var zm=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],uP=new Set(zm),Jm=new Set([...zm,"minimum_runtime_version","revision"]),dP=new Set([...Jm,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),fP=new Set(["capability","operation","source","base_hash"]),pP=new Set(["shape","build","verify","archive"]),hP=new Set(["implicit","confirmed"]),mP=new Set(["pending","pass","fail"]),si="comet-state.yaml",tu=/^[a-f0-9]{64}$/u,Gm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vP=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Vo=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Ri=class extends Error{constructor(i,r){super(i!==ti||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Fo=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},_n=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},qo=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},UD=oo("en");function Tn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Um(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Mo(e){if(!Gm.test(e))throw new Error(`Invalid Native change name: ${e}`)}function gP(e){if(!Gm.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Km(e,t){if(e.length===0||Rt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function wP(e,t){let i=Tn(e,`spec_changes[${t}]`);if(Um(i,fP,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(gP(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&Km(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!tu.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!tu.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function yP(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 ru(e,t){if(Um(e,t,si),typeof e.name!="string")throw new Error("Native change name is required");if(Mo(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"||!pP.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&&!hP.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(wP),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!mP.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"&&Km(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!yP(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function ar(e){let t=Tn(e,si);if(t.schema!==ri)throw new Error(`Expected ${ri}`);return{schema:ri,...ru(t,uP)}}function In(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function eu(e,t,i){if(e===null)return null;let r=typeof e=="string"?vP.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function NP(e){if(e==null)return null;if(typeof e!="string"||!tu.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function bP(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 or(e){let t=Tn(e,si);if(t.schema!==ii)throw new Error(`Expected ${ii}`);if(In(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ii} minimum_runtime_version must be 2`);return{schema:ii,minimum_runtime_version:2,revision:In(t.revision,"Native v2 revision"),...ru(t,Jm)}}function ni(e){let t=Tn(e,si);if(t.schema!==ti){if(t.schema===ri||t.schema===ii){let o=t.schema===ri?ar(t):or(t);throw new Vo(o.name,o.schema)}throw new Ri(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=In(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Ri(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=In(t.revision,"Native revision"),n=ru(t,dP),a=NP(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ti,minimum_runtime_version:3,revision:r,verification_protocol:bP(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:eu(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:eu(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:eu(t.partial_allowance,"Native partial_allowance","allowances")}}function Ym(e){let t=Tn(e,si);if(t.schema===ri){let n=ar(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ti}`}}if(t.schema===ii){let n=or(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ti}`}}if(t.schema!==ti){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 Ri(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=In(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Ri(t.schema,i).message};let r=ni(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function pe(e,t){Mo(t);let i=Rt.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Wo(e,t){let i=U(e,t),r=Rt.join(i,"schema-migration.json");await J(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Wm.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Xm(e,t){let i=U(e,t),r=Rt.join(i,"checkpoint-journal.json");await J(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Wm.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Qm(e,t=Rt.dirname(e)){let i=Rt.relative(t,e).split(Rt.sep).join("/"),r=await ne({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,iu.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function nu(e,t){let i=Rt.join(pe(e,t),si);await J(e.nativeRoot,i);let r=Ym(await Qm(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Wo(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await kP(e,r.state),r)}async function Zm(e,t){let i=Rt.join(pe(e,t),si);await J(e.nativeRoot,i);let r=Ym(await Qm(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function kP(e,t){if(await _o(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function At(e,t){let i=await nu(e,t);if(i.status==="migration-required")throw new Vo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Ri(i.schema,i.minimumRuntimeVersion);return await qm(e,t),i.state}import{promises as zI}from"fs";import{promises as au}from"fs";import ev from"path";var tv=["outcome","scope","nonGoals","acceptanceExamples"],SP=[...tv,"constraints","decisions","openQuestions","verificationExpectations"],EP=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],iv={maxFileBytes:un};function rv(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
|
|
166
|
+
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function CP(e,t){let i=ev.resolve(e,...t.split(/[\\/]/u));if(!V(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await au.realpath(e),n=await au.realpath(i);if(!V(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await au.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function jn(e){return{valid:e.length===0,findings:e}}async function ou(e,t){let i=[],r;try{r=(await ne({root:e,ref:t,maxBytes:iv.maxFileBytes})).text}catch(o){return jn([{code:"brief-missing",message:o.message,path:t}])}let n=new Map;for(let[o,s]of rv(r))n.set(ao(o)??o,s);for(let o of SP)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of tv)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("openQuestions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),jn(i)}async function su(e,t){let i=[],r;try{r=(await ne({root:e,ref:t,maxBytes:iv.maxFileBytes})).text}catch(a){return jn([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of rv(r))n.set(Nh(a)??a,o);for(let a of EP)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return jn(i)}function zo(e,t){return ev.join(e.specsDir,t,"spec.md")}async function nv(e,t){let i=[],r=pe(e,t.name);for(let n of t.spec_changes){let a=zo(e,n.capability),o=null;try{await J(e.nativeRoot,a),o=await Dl(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await CP(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return jn(i)}import av from"node:path";var xP="comet.native.contract.v1",PP="comet.native.acceptance-set.v1",ov=/^[a-f0-9]{64}$/u,$n={maxAcceptanceCriteria:vn.maxCriteria};function sv(e,t){let i=av.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||av.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function cv(e){return j("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
167
|
+
`))}function RP(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(ov))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(ov))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=sv(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:cv(e.markdown)},markdown:e.markdown}}function AP(e,t){return lv(e.id,t.id)}function lv(e,t){return e<t?-1:e>t?1:0}function uv(e){let t=sv(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(RP).sort((d,f)=>lv(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Al(e.briefMarkdown,t,$n.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(..._l(f,d.source,$n.maxAcceptanceCriteria-a.length)),a.push(...Wh(f,d.source,$n.maxAcceptanceCriteria-a.length)));if(a.sort(AP),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>$n.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${$n.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:cv(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=j(PP,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(xP,u)}}var Jo={maxSpecs:64,maxFileBytes:un,maxTotalBytes:4*1024*1024};async function mr(e){if(e.specChanges.length>Jo.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ne({root:e.changeDir,ref:e.briefRef,maxBytes:Jo.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ne({root:e.changeDir,ref:n.source,maxBytes:Jo.maxFileBytes});if(i+=a.size,i>Jo.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:uv({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import _P from"path";var cu="comet.selection.v2",IP=16*1024;function fv(e){return _P.join(e,".comet","current-change.json")}function TP(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function dv(e){return e===null||typeof e=="string"}function jP(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!TP(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&&!dv(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:cu,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==cu)throw new Error(`current change selection schema must be ${cu}`);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(!dv(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 pv(e){let t;try{let r=fv(e),{bytes:n}=await Yi(r,IP,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...jP(t)}}import{promises as CR}from"node:fs";import yu from"node:path";var mu=_r(Gi(),1);import{promises as xv}from"node:fs";import Ve from"node:path";import{execFileSync as $P}from"node:child_process";var OP=3e4,HP=8*1024*1024,lu=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function DP(e,t){try{return $P("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:OP,maxBuffer:HP,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new lu(e,t,r)}}function Go(e,t){return DP(e,t).trim()}import du from"node:path";import{promises as hv}from"node:fs";var Uo=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var uu="comet.native.supervisor.v2",BP=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function VP(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 FP(e,t){return du.join(Zt(e,t),"supervisor")}function mv(e,t){return du.join(FP(e,t),"state.json")}function vv(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!==uu)throw new Error(`Native Supervisor state schema must be ${uu}`);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(On(t.integration.targetCommit,"Native Supervisor target commit"),On(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&On(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(On(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Hn(e,t){try{let i=await hv.readFile(mv(e,t),"utf8"),r=JSON.parse(i);return vv(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function fu(e,t){vv(t),await hv.mkdir(e.changesRuntimeDir,{recursive:!0}),await Ye(mv(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function On(e,t){if(!BP.test(e))throw new Error(`${t} must be a Git commit`)}function qP(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function gv(e){On(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:uu,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function pu(e){let t=VP(e.parent),i=gi(e.paths.projectRoot,t);if(!i)return null;let r=gi(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Dt(e.paths.projectRoot).map(o=>du.resolve(o)).find(o=>be(o).currentBranch===t);if(!n)return null;let a=gv({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return qP(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function wv(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var yv="children.yaml",Dn="comet.native.children.v1",vr="comet.native.children.v2",Pv=vr,MP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Nv=new Set(["schema","children"]),WP=new Set(["schema","acceptance_index","children"]),zP=new Set(["name","depends_on","covers"]),JP=new Set(["name","summary","depends_on"]),GP=new Set(["name","depends_on","covers"]);function Yo(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function Ko(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function bv(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function hu(e,t){let i=Ve.normalize(Ve.resolve(e)),r=Ve.normalize(Ve.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function UP(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function kv(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function KP(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Pv&&e.acceptance_index){let n=i.requiredAcceptanceIds??t??[],a=i.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);r.missing=n.filter(l=>!(l in e.acceptance_index)),r.extra=o.filter(l=>!a.includes(l));let s=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&r.mismatched.push(l)}let c=new Set(o);for(let l of e.children)r.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return r.uncovered=o.filter(l=>!Sv(e.children,l)),Ev(r)?r:null}if(e.schema===Dn&&t){let n=new Set(t);for(let a of e.children)r.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return r.uncovered=t.filter(a=>!Sv(e.children,a)),Ev(r)?r:null}return null}function Sv(e,t){return e.some(i=>i.covers.includes(t))}function Ev(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Rv(e){let t=new Set(e.acceptance.map(({id:n})=>n)),i=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),r=new Set(i);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&r.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])i.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...i],allowedAcceptanceIds:[...r]}}function YP(e){let t=Yo(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=Yo(n,`Native children acceptance_index.${r}`);if(Ko(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function XP(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=i.allowedAcceptanceIds??r,a=Object.keys(e),o=r.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(p=>d[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function QP(e,t,i={}){let r=(0,mu.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=Yo(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Dn&&a!==vr)throw Ko(n,Nv,"Native children contract"),new Error(`Native children schema must be ${Dn} or ${vr}`);let o=a===Dn?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Ko(n,o==="indexed-v2"?WP:Nv,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,p)=>{let v=Yo(f,`Native child ${p}`);if(Ko(v,o==="indexed-v2"?GP:o==="summary-v2"?JP:zP,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!MP.test(v.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:h?v.summary:null,depends_on:bv(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?bv(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let p=f.depends_on.filter(v=>!u.has(v));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}UP(c);let d=i.policy==="advisory";if(a===Pv){if(o==="indexed-v2"){let f=YP(n.acceptance_index);d||XP(f,t,i);let p=Object.keys(f);return d||kv(c,p,p),{schema:vr,acceptance_index:f,children:c}}return{schema:vr,children:c}}return t&&!d&&kv(c,t),{schema:Dn,children:c}}async function Av(e){let t=Ve.join(e.changeDir,yv);try{await xv.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await ne({root:e.changeDir,ref:yv}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=QP(i.text,e.acceptanceIds,n);return{contract:a,size:i.size,drift:r?KP(a,e.acceptanceIds,e.validation??{}):null}}function ZP(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function eR(e){let t=ZP(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function _v(e){try{let t=await ne({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return eR(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Iv(e){return j("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function tR(e){let t=Dt(e.projectRoot);t.some(r=>hu(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Ve.resolve(n)))]){let n=await Ee(r);n&&i.push({projectRoot:r,paths:await kt(r,n.native.artifact_root),parent:hu(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function iR(e,t){let i=Ve.join(e.paths.changesDir,t,"comet-state.yaml");try{return await yn(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function rR(e,t){let i;try{i=await xv.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Ve.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await yn(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function nR(e,t,i){let r=Ve.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Ve.sep}`))return null;let n=r.split(Ve.sep).join("/");try{let a=(0,mu.parseDocument)(Go(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:wn(a.toJS({mapAsMap:!1}))}catch{return null}}function aR(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Cv(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function vu(e){let t=Ve.join(e.paths.changesDir,e.state.name),i=await _v(t),r=await Av({changeDir:t,validation:Rv(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:m})=>m)}:{},policy:"advisory"});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=Iv({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!r.drift;if(r.contract.schema===vr){let m=await Hn(e.paths,e.state.name);if(!m){let N=e.state.workspace.target_branch??e.state.workspace.change_branch;if(N){let k=await pu({paths:e.paths,parent:e.state.name,targetBranch:N,contract:r.contract});k&&(m=k,await fu(e.paths,k))}}if(m){let N=wv(m);return e.state.children_contract_hash!==n||r.drift?{...N,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(k=>({...k,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let S=new Map(r.contract.children.map(N=>[N.name,N])),y=r.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:o&&N.depends_on.every(k=>r.contract.children.filter(({name:E})=>E!==N.name).every(({name:E})=>E!==k))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let N of y){if(N.status!=="ready")continue;S.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:y,readyChildren:y.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let s=await tR(e.paths),c=new Set(r.contract.children.map(({name:m})=>m)),l=new Map,u=new Map;for(let m of s){let S=m.parent&&a?`refs/heads/${a}`:"HEAD";for(let y of await rR(m,c)){let N={...y,source:m,committedState:nR(m,y.file,S)};l.set(y.state.name,[...l.get(y.state.name)??[],N])}for(let y of c){let N=await iR(m,y);N&&u.set(y,[...u.get(y)??[],{source:m,state:N}])}}let d=new Map;for(let m of r.contract.children){let S=(l.get(m.name)??[]).find(({source:k,committedState:E})=>k.parent&&E?.name===m.name&&Cv(E,a));if(S){d.set(m.name,{kind:"done",phase:S.state.phase,projectRoot:S.source.projectRoot,message:null});continue}let y=l.get(m.name)?.[0];if(y){d.set(m.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${m.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let N=u.get(m.name)??[];N.length>1?d.set(m.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${m.name} has multiple active workspace owners`}):N[0]&&d.set(m.name,aR(N[0].state,N[0].source,a))}let f=new Map(r.contract.children.map(m=>[m.name,m])),p=new Map,v=m=>{let S=p.get(m);if(S)return S;let y=f.get(m),k=y.depends_on.map(v).every(({status:C})=>C==="done"),E=d.get(m),b=E?.kind==="active"&&k?y.depends_on.filter(C=>!(l.get(C)??[]).some(({source:O,committedState:T})=>hu(O.projectRoot,E.projectRoot)&&T?.name===C&&Cv(T,a))):[],x,g=E?.message??null;E?.kind==="done"?(x=k?"done":"blocked",k||(g=`Native child ${m} was merged before its dependencies`)):E?.kind==="active"?(x=k&&b.length===0?"active":"blocked",k?b.length>0&&(g=`Native child ${m} does not include merged dependencies: ${b.join(", ")}`):g=`Native child ${m} started before its dependencies merged`):E?.kind==="blocked"?x="blocked":(x=o&&k?"ready":"pending",o||(g="Parent Shape confirmation is required"));let w={name:m,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:x,phase:E?.phase??null,projectRoot:E?.projectRoot??null,message:g};return p.set(m,w),w},h=r.contract.children.map(({name:m})=>v(m));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:h,readyChildren:h.filter(({status:m})=>m==="ready").map(({name:m})=>m),allDone:h.every(({status:m})=>m==="done")}}var KL=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var oR=/\b(Bearer|Basic)\s+[^\s"']+/giu,sR=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,cR=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,lR=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,uR=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,dR=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,fR=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function Fe(e){return e.replace(oR,"$1 [REDACTED]").replace(sR,"[REDACTED PRIVATE KEY]").replace(cR,"$1[REDACTED]@").replace(lR,"[REDACTED TOKEN]").replace(uR,'$1"[REDACTED]"').replace(dR,"$1$2$1$3$4[REDACTED]$4").replace(fR,"$1$2[REDACTED]")}import{promises as wR}from"node:fs";import Tv from"node:path";function Xo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qo(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function pt(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function jv(e,t){return e===null?null:pt(e,t)}function es(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function yR(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 NR(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Zo(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function gu(e,t){if(e===null)return null;let i=pt(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function wu(e,t){let i=pt(e,t);if(!Tv.isAbsolute(i))throw new Error(`${t} must be absolute`);return Tv.resolve(i)}function bR(e,t){let i=`Native local checks[${t}]`,r=Xo(e,i);if(Qo(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>pt(l,`${i}.argv[${u}]`,!0)),a=Zo(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=gu(r.startedAt,`${i}.startedAt`),s=gu(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=es(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:pt(r.id,`${i}.id`),name:pt(r.name,`${i}.name`),operationId:pt(r.operationId,`${i}.operationId`),status:a,repeatable:NR(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:es(r.executionCount,`${i}.executionCount`),argv:n,cwd:wu(r.cwd,`${i}.cwd`),exitCode:yR(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:pt(r.log,`${i}.log`)}}function kR(e){let t="Native local execution state",i=Xo(e,t);if(Qo(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==yo)throw new Error(`Native local execution schema must be ${yo}`);let r=Xo(i.workspace,"Native local workspace");Qo(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Xo(i.execution,"Native local execution");Qo(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=gu(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:pt(o.operationId,"Native local execution.operationId"),stage:Zo(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Zo(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:jv(o.executionId,"Native local execution.executionId"),status:Zo(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:es(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(bR);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:yo,change:pt(i.change,"Native local change"),basedOnStateVersion:es(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:wu(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:wu(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:jv(r.branch,"Native local workspace.branch")},execution:n,checks:a}}async function $v(e){let t;try{t=await wR.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return kR(i)}var xR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,PR="comet-state.yaml",RR="state.json",xV=oo("en");function Ov(e,t){if(!xR.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=yu.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}function Hv(e,t){return yu.join(Ov(e,t),PR)}function AR(e,t){return yu.join(Zt(e,t),RR)}async function Nu(e,t){try{let i=await CR.readFile(Hv(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function Dv(e,t){return yn(Hv(e,t))}async function Lv(e){let t=await Dv(e.paths,e.name),i=AR(e.paths,e.name);try{let r=await $v(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var HV=16*1024;async function Bv(e){let t=await pv(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Mo(t.selection.change),t.selection)}async function Vv(e,t){let i=[],r=U(e,t.name),n=ei(r,Be.stateRef),a;try{a=await pr(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=ei(r,a.trajectoryRef),s=await jm(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await Pi(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=ei(r,a.checkpointRef);try{let u=await Ho(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import bA from"path";import{isDeepStrictEqual as Vu}from"util";var gr={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var _R=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function IR(e,t){return e<t?-1:e>t?1:0}function TR(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!_R.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(IR)}function bu(e=[]){return TR(e,"Native repair failed check IDs",gr.maxFailedCheckIds,!0)}function Fv(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function jR(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Fv(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Fv(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function ku(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(jR(r,a))break;i+=1,r=a}return i}import sg from"node:path";import{createHash as Kv}from"node:crypto";import qv from"path";var Su="comet.native.implementation-scope.v2",Yv="comet.native.content-snapshot-projection.v1",Ln="comet.native.content-snapshot-projection.v1",Xv="comet.native.implementation-scope.v2",$R="comet.native.unresolved-scope-id.v1",OR="comet.native.scope-detail-overflow.v1",HR="comet.native.snapshot-projection-overflow.v2",Pu=/^[a-f0-9]{64}$/u,_i=1024*1024,DR=128,LR=128;function ve(e,t){return e<t?-1:e>t?1:0}function Eu(e){if(!Pu.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function BR(e,t){return e===t?0:e===null?-1:t===null?1:ve(e,t)}function li(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=qv.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||qv.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Qv(e,t){return e==="."?e:li(e,t)}function wr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function VR(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:li(e.path,`${t} path`),hash:e.hash,size:wr(e.size,`${t} size`),type:"file"}}function FR(e,t){return{path:Qv(e.path,`${t} path`),size:e.size===null?null:wr(e.size,`${t} size`),type:e.type,reason:e.reason}}function qR(e,t){return ve(e.path,t.path)||ve(e.hash,t.hash)||e.size-t.size}function MR(e,t){return ve(e.path,t.path)||ve(e.reason,t.reason)||ve(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Vn(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
168
168
|
`,"utf8")}function ci(e,t,i){let r=`${t}
|
|
169
|
-
${
|
|
170
|
-
`),e.omissionOverflow&&ci(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(r+=1),n+=1,ci(a,"omission",f)},s=f=>{r+=1,n+=1,ci(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let p=i[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(f,1),p}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;
|
|
171
|
-
`);let i=0;Ru(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){ci(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Fn(o,n.path)&&(a+=1,ci(t,"change-attribution",o));ci(t,"change-end",{attributionCount:a}),a===0&&ci(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&ci(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function ag(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=GR(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let x=new Set(i.externalDrift.paths),g=new Set(o.changePaths),w=i.externalDrift.paths.filter(C=>!g.has(C)||n.some(O=>Fn(O,C)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(x.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=j(Dn,e),c=j(Dn,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[x,g]of[["baseline",e],["current",t]])for(let w of g.omitted){if(l.length>=DR)break;l.push(_t({kind:"snapshot-omission",source:x,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${x} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...zv("baseline",e),...zv("current",t),...o.totalChanges===0&&a===null?[_t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(i.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(g=>x.has(g)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(g=>!x.has(g))}},v=x=>{let g=o.candidates.slice(0,x.detailedChangeCount),w=g.filter(We=>We.attributedTo.length===0&&!u.has(We.path)),C=o.totalChanges-g.length,O=o.totalUnattributed-w.length,T=d-x.detailedOmissionCount,pe=O+T,Q=[...w.map(We=>_t({kind:"unattributed-change",source:"implementation-scope",path:We.path,evidence:{after:We.after,before:We.before,changeKind:We.kind}},`Changed path is not covered by a declared artifact: ${We.path}`)),...l.slice(0,x.detailedOmissionCount),...f,...pe>0?[ng(x.overflowHash,{changes:C,unattributed:O,unresolved:pe})]:[]],G=zR(Q),at=x.includeGitAdvisory?p():void 0;return{schema:Su,contractHash:r,baselineProjectionRef:Eu(s),baselineProjectionHash:s,currentProjectionRef:Eu(c),currentProjectionHash:c,complete:G.length===0,declaredArtifacts:n,changes:g,unattributed:w,unresolvedScopes:G,noCodeReason:a,...at?{gitAdvisory:at}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},h=o.candidates.length,m=l.length,S=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let x=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:y});if(Bn({...x,scopeHash:y})<=_i)break;if(S){S=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let k=o.totalChanges>h||d>m?KR({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):y,E=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:k}),b={...E,scopeHash:j(Qv,E)};if(Bn(b)>_i)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function _u(e){let t=Cu(e.baseline),i=Cu(e.current),r=rg(e);return{authority:r,baseline:t,current:i,scope:ag(t,i,r)}}var YR=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function ht(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mt(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function Ai(e,t){if(typeof e!="string"||!Pu.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Gv(e,t,i){let r=Eu(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function Qo(e,t){let i=ht(e,"Native snapshot projection");if(mt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Xv)throw new Error("Native snapshot projection schema is invalid");let r=xi({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=Cu(r);if(j(Dn,i)!==j(Dn,n))throw new Error("Native snapshot projection is not canonical");let a=j(Dn,n);if(t!==void 0&&Ai(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Iu(e,t){let i=ht(e,`Declared artifact ${t}`);if(mt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:li(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Uv(e,t){if(e===null)return null;let i=ht(e,t);return mt(i,["hash","size"],[],t),{hash:Ai(i.hash,`${t} hash`),size:vr(i.size,`${t} size`)}}function Kv(e,t){let i=ht(e,`Implementation change ${t}`);if(mt(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Iu),n=Vn(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Uv(i.before,`Implementation change ${t} before`),o=Uv(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:li(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function XR(e,t){let i=ht(e,`Unresolved scope ${t}`);mt(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Zv(i.path,`Unresolved scope ${t} path`):li(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Ln(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>li(n,`${t} ${a}`)),r=[...new Set(i)].sort(ve);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function og(e){let t=ht(e,"Native implementation external drift");if(mt(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=Ln(t.paths,"Native external drift paths");return ig({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function Zo(e){let t=ht(e,"Native implementation scope"),i=[...YR].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(mt(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Su)throw new Error("Native implementation scope schema is invalid");let r=Ai(t.contractHash,"Implementation scope contractHash"),n=Ai(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Gv(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Ai(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Gv(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Iu);if(JSON.stringify(c)!==JSON.stringify(Vn(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Kv),u=[...l].sort((w,C)=>ve(w.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(C=>Fn(C,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Kv),p=t.externalDrift===void 0?void 0:og(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(XR),S=m.filter(w=>w.kind==="scope-detail-overflow");if(S.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=S[0]===void 0?null:UR(S[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let N=t.noCodeReason,k=[...h.map(w=>_t({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(y?.changes??0)===0&&N===null?[_t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(xu))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(E)!==JSON.stringify(k.sort(xu))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=ht(t.gitAdvisory,"Implementation scope Git advisory");if(mt(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Ln(w.changedPaths,"Git changed paths"),O=Ln(w.pathsPresentInSnapshotChanges,"Git present paths"),T=Ln(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),pe=[...O,...T].sort(ve);if(JSON.stringify(pe)!==JSON.stringify(C)||T.some(Q=>l.some(G=>G.path===Q)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:T}}let x={schema:Su,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:N,...b?{gitAdvisory:b}:{},...p?{externalDrift:p}:{}},g=Ai(t.scopeHash,"Implementation scope scopeHash");if(j(Qv,x)!==g)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:g}}function QR(e){let t=ht(e,"Native implementation scope authority");if(mt(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Iu);if(JSON.stringify(i)!==JSON.stringify(Vn(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=Ln(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:og(t.externalDrift),a=rg({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function qn(e){let t=ht(e,"Native implementation scope bundle");mt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=QR(t.authority),r=Qo(t.baseline),n=Qo(t.current),a=Zo(t.scope),o=ag(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function sg(e){let t=Zo(e.scope);return qn({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var ug=/^[a-f0-9]{64}$/u;var ZR="comet.native.acceptance-trace.v2",eA="comet.native.partial-allowance.v1",tA="comet.native.verification-evidence.v2";function It(e,t){if(!ug.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function dg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function fg(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Tu(e,t,i=2e3){let r=Fe(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Mn(e,t){let i=cg.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||cg.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function iA(e,t,i){let r=Mn(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ct(r),a=r.toLowerCase(),o=i?Mn(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function ju(e){let t=Mn(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function gr(e,t){return e<t?-1:e>t?1:0}function es(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ts(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function pg(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function lg(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function rA(e){let t=es(e,"Native acceptance trace");if(ts(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!ug.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=Mn(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=es(o,`Native acceptance trace entry ${s}`);if(ts(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>ju(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(gr))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Mn(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Tu(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>gr(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=It(t.traceHash,"Native acceptance trace hash");if(j(ZR,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function hg(e){let t=es(e,"Native partial allowance");if(ts(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(gr))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:fg(t.change),scopeHash:It(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Tu(t.reason,"Partial allowance reason"),confirmedSummary:Tu(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:dg(t.sourceRevision),confirmedAt:pg(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=It(t.allowanceHash,"Native partial allowance hash");if(j(eA,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function $u(e){let t=es(e,"Native verification evidence");if(ts(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=It(t.implementationScopeHash,"Native verification implementation scope hash"),r=rA(t.acceptanceTrace),n=It(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:It(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>ju(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(gr)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(gr);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>ju(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(gr)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:fg(t.change),sourceRevision:dg(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:It(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:lg(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:iA(t.reportRef,"Native verification report ref"),reportHash:It(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:lg(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:pg(t.createdAt,"Native verification timestamp")},d=It(t.envelopeHash,"Native verification envelope hash");if(j(tA,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function Ou(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var mg="repairStagnation",Ie={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},aA=/^[a-f0-9]{64}$/u;var oA=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),sA=["data","runId","sequence","timestamp","type"],vg=["disposition","overrideSummaryHash","signatureHash"],cA=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],gg=12;function Du(e,t){return e<t?-1:e>t?1:0}function wg(e,t,i){let r=Object.keys(e).sort(Du);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function is(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Wn(e,t){if(typeof e!="string"||!aA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function lA(e){if(!Array.isArray(e)||e.length>mr.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Du)}function yg(e){if(typeof e!="string"||e.length===0||e.length>Ie.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Hu(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Ie.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Ie.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Ie.maxTextCharacters&&(!n||e.length>Ie.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Ie.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Ie.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Hu(s,t+1,i,`${r}[${c}]`));return}let a=is(e,r),o=Object.keys(a);if(o.length>Ie.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Ie.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Ie.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Hu(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function uA(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function dA(e,t,i){let r=is(e,`Native repair trajectory event ${t+1}`);if(wg(r,sA,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(uA(r.timestamp),typeof r.type!="string"||!oA.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(yg(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Hu(r.data,0,n,"Native trajectory event data"),is(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Lu(e){let t=is(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Du),r=i.length===vg.length&&i.every((l,u)=>l===vg[u]);r||wg(t,cA,"Native repair trajectory projection");let n=Wn(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Wn(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Wn(t.contractHash,"Native repair trajectory contract hash"),s=lA(t.failedAcceptanceIds),c=bu(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function fA(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function pA(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??gg;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=ku({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<mr.warningAtConsecutiveFailures?"continue":a<mr.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function hA(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??gg;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Ng(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Ie.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=yg(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=dA(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Ie.maxTotalDataNodes||c>Ie.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Wn(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Wn(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,mg)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Lu(f[mg]);if(fA(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(i.length=0,o=0),p!==null&&(n=p),pA(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");hA(v,i,r);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>mr.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function bg(e){return Ng(e).history}function kg(e){let t=Ng(e).latestProjection;return t?{...t}:null}var wr={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:[]},Bu=K("comet-native-runtime:v3:scope-reopen"),mA=[{skillVersion:"3",skillHash:K("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:K("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:K("comet-native-runtime:v1")}];function Sg(e){return e.skillVersion===wr.definition.metadata.version&&e.skillHash===Bu||mA.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function Eg(e){return K(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var Ag=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],bA=new Set(Ag),_g=new Set([...Ag,"minimum_runtime_version","revision"]),kA=new Set([..._g,"operation"]),SA=512*1024,Fu=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),EA=new Set([...Fu,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),qu=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Wu(e,t){return NA.join(U(e,t),"transition.json")}function ns(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function zu(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function rs(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Mu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!EA.has(u)),a=[...Fu].find(u=>!Object.hasOwn(i,u)),o=Fu.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Ou(i.summary,"Native transition journal event summary"),Fe(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Ou(i.noCodeReason,"Native transition journal event no-code reason"),Fe(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Lu(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function CA(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return Mu({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Mu(e,t)}function Ju(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?CA(e.eventData,e.evidenceHash):Mu(e.eventData,e.evidenceHash),n=Kl(e.nextRun),a=e.previousRun===null?null:Kl(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Cg(e,t,i=!1){if(e.skill!==wr.definition.metadata.name||(i?!Sg(e):e.skillVersion!==wr.definition.metadata.version||e.skillHash!==Bu)||e.orchestration!==wr.definition.orchestration.mode||e.pendingRef!==Be.pendingRef||e.trajectoryRef!==Be.trajectoryRef||e.contextRef!==Be.contextRef||e.artifactsRef!==Be.artifactsRef||e.checkpointRef!==Be.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function xg(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Pg(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function Gu(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Cg(o,"next Run",r||a!==null),Pg(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Cg(a,"previous Run",!0),Pg(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!Vu(xg(a),xg(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function xA(e,t,i){return K(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Ig(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Rg(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Uu(e,t,i,r,n=!1){let a=i.eventData,o=Rg(e),s=Rg(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&Vu(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&Vu(e.spec_changes,t.spec_changes),l=Eg({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=xA(e.name,a.summary,t.spec_changes),l=K(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function PA(e,t){let i=ns(e);if(zu(i,kA),i.schema!==tr)throw new Error(`Expected Native transition schema ${tr}`);let r=rs(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${tr} minimum_runtime_version must be ${3}`);let n=rs(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Ju(i,t),o=ni(i.previousState),s=ni(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Uu(o,s,a,i.operation),Gu(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:tr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function RA(e,t){let i=ns(e);if(zu(i,bA),i.schema!==yn)throw new Error(`Expected Native transition schema ${yn}`);let r=Ju(i,t,!0),n=rr(i.previousState),a=rr(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Uu(n,a,r,Ig(n,a,r.eventData),!0),Gu(n,a,r,!0),{schema:yn,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function AA(e,t){let i=ns(e);if(zu(i,_g),i.schema!==ir)throw new Error(`Expected Native transition schema ${ir}`);if(rs(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${ir} minimum_runtime_version must be 2`);let n=rs(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Ju(i,t,!0),o=nr(i.previousState),s=nr(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Uu(o,s,a,Ig(o,s,a.eventData),!0),Gu(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:ir,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function _A(e,t){let i=ns(e);if(i.schema===tr)return{status:"current",journal:PA(i,t)};if(i.schema===yn)return{status:"migration-required",journal:RA(i,t)};if(i.schema===ir)return{status:"migration-required",journal:AA(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function IA(e,t){let i=Wu(e,t),r=le(e,i);await J(r,i);try{let n=await Et({root:r,file:i,maxBytes:SA,label:`Native transition journal ${t}`});return _A(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Tg(e,t){let i=await IA(e,t);if(!i)return null;if(i.status==="migration-required")throw new qu(t);return i.journal}var TA=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function jA(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function $A(e){return e?e.map(jA).join(" "):null}function OA(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function qe(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function HA(e){return e.map(t=>qe(t,[],null))}function DA(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[qe("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(qe("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(qe("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),qe("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(qe("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(qe("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),qe("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function ge(e,t){let i=t.commandArgs===void 0?OA(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?$A(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??HA(t.requiredInputs??[])}}function as(e){let i=(e.findings??[]).filter(d=>!fr(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||TA.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return ge(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[qe("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return ge(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[qe("summary",["--summary"],"<summary>")]});if(n)return ge(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[qe("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),ge(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[qe("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):ge(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return ge(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=DA(e.state);return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import zn from"path";var jg=8,LA={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function BA(e){let t=LA[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:fr(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function VA(e,t,i){if(!i.path)return null;let r;if(zn.isAbsolute(i.path)?r=zn.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=zn.resolve(fe(e,t.name),...i.path.split(/[\\/]/u)):r=zn.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!V(e.projectRoot,r))return null;let n=zn.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function FA(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Ku(e){return e.findings.map(t=>{let i=BA(t.code);return{code:t.code,message:t.message,severity:i.severity,path:VA(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:FA(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Yu(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,jg),truncated:t.length>jg}}import yr from"path";var di={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Nr=/^[a-f0-9]{64}$/u;function os(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ss(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function ui(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function $g(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Xu(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function qA(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||yr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=yr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Og(e,t){return yr.join(U(e,t),"checkpoints","progress.json")}function Jn(e,t){return yr.join(U(e,t),"checkpoint-journal.json")}function Hg(e,t,i){if(!Nr.test(i))throw new Error("Native checkpoint manifest hash is invalid");return yr.join(U(e,t),"checkpoints","manifests",`${i}.json`)}function MA(e){if(!Nr.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Qu(e,t,i){let r=await Et({root:e,file:t,maxBytes:di.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function WA(e,t){let i=os(e,`checkpoint manifest artifact ${t}`);ss(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=qA(ui(i.path,`checkpoint artifact ${t} path`,4096)),n=ct(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!Nr.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:Xu(i.size,`checkpoint artifact ${t} size`)}}function Zu(e,t){let i=os(e,"Native checkpoint manifest");if(ss(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>di.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(WA),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Xu(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>di.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Dg(e){return K(JSON.stringify(Zu(e,e.change)))}function Lg(e,t){let i=os(e,"Native progress checkpoint");if(ss(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=$g(i.previousRevision,"Native checkpoint previousRevision"),a=$g(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ui(i.manifestHash,"Native checkpoint manifestHash",64);if(!Nr.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=MA(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ui(i.inputHash,"Native checkpoint inputHash",64);if(!Nr.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ui(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Xu(i.artifactCount,"Native checkpoint artifactCount");if(u>di.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ui(i.summary,"Native checkpoint summary"),f=ui(i.nextAction,"Native checkpoint nextAction");if(Fe(d)!==d||Fe(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ui(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function zA(e,t){let i=os(e,"Native checkpoint journal");if(ss(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=ni(i.previousState),n=ni(i.nextState),a=Lg(i.checkpoint,t),o=Zu(i.manifest,t),s=ui(i.inputHash,"Native checkpoint journal inputHash",64),c=K(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Nr.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Dg(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function JA(e,t,i){let r=yr.resolve(e.projectRoot,...t.split("/"));if(!V(e.projectRoot,r)||V(e.nativeRoot,r)||V(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=rl(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await Et({root:e.projectRoot,file:r,maxBytes:di.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function GA(e,t){let i=Og(e,t),r=le(e,i);await J(r,i);try{return Lg(await Qu(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function UA(e,t,i){let r=Hg(e,t,i),n=le(e,r);await J(n,r);let a=await Qu(n,r,"Native checkpoint manifest"),o=Zu(a,t);if(Bg(e,o),Dg(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function ed(e,t){let i=Jn(e,t),r=le(e,i);await J(r,i);try{let n=zA(await Qu(r,i,"Native checkpoint journal"),t);return Bg(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Bg(e,t){for(let i of t.artifacts){let r=rl(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Vg(e){let t;try{t=await GA(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Og(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await UA(e.paths,e.name,t.manifestHash);let a=K(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await JA(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Hg(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}var Fg=240,qg=8,cs=50;function Mg(e){let t=Array.from(e);return t.length<=Fg?e:`${t.slice(0,Fg-1).join("")}…`}function KA(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function YA(e){let t=[...new Set(e.map(KA))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,qg),reasonCount:e.length,codesTruncated:t.length>qg};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,cs),reasonsTruncated:e.length>cs}}}async function Wg(e){let t=null;try{let s=await ed(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Jn(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Jn(e.paths,e.state.name)}}let i=await Vg({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=YA(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:di.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Mg(i.checkpoint.summary),nextAction:Mg(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:di.maxArtifacts}}import{promises as DI}from"node:fs";import Ew from"node:path";import zg from"node:path";var XA="comet.native.archive-preflight.v1",QA="comet.native.archive-preflight.v1",ZA="comet.native.archive-operation.v1",e_=/^[a-f0-9]{64}$/u,Jg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,t_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function ls(e,t){return e<t?-1:e>t?1:0}function i_(e,t){if(typeof e!="string"||!e_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Tt(e,t){return e===null?null:i_(e,t)}function r_(e,t){let i=zg.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||zg.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function n_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function a_(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function o_(e,t){if(!Jg.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Tt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Tt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Tt(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function s_(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Tt(e.contractHash,"Native archive contract hash"),acceptanceHash:Tt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Tt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Tt(e.reportHash,"Native archive report hash"),envelopeHash:Tt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Tt(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function c_(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!t_.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(ls);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function l_(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(ls)}function Gg(e){if(!Jg.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(o_).sort((l,u)=>ls(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:j(ZA,l)})),r=s_(e.evidence),n=a_(e.workspace),a=[...new Set([...c_(e.findingCodes??[]),...l_({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(ls),o=n_(e.revision),s=r_(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:XA,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:j(QA,c)}}import{createHash as u_}from"node:crypto";import Ug from"node:path";var d_="comet.native.conflict-radar.v1",Ce=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}),f_="comet.native.conflict-radar.v1",p_="comet.native.conflict-radar-signals.v1",h_=/^[a-f0-9]{64}$/u,Xg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,m_=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),v_=new Set(["capability","operation","baseHash"]),g_=new Set(["path","kind"]);function br(e,t){return e<t?-1:e>t?1:0}function td(e){return Buffer.byteLength(e,"utf8")}function id(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function rd(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(td(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function w_(e,t){let i=rd(e,t,Ce.maxArtifactPathBytes),r=Ug.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||Ug.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Qg(e,t){if(typeof e!="string"||!h_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function y_(e,t){let i=id(e,v_,t),r=rd(i.capability,`${t} capability`,Ce.maxCapabilityBytes);if(!Xg.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:Qg(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function N_(e,t){let i=id(e,g_,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:w_(i.path,`${t} path`),kind:i.kind}}function b_(e,t){let i=id(e,m_,`Conflict radar change ${t}`),r=rd(i.name,`Conflict radar change ${t} name`,Ce.maxNameBytes);if(!Xg.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>Ce.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>Ce.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>y_(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>br(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>N_(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>br(c.path,l.path)||br(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:Qg(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function k_(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Ce.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(b_).sort((n,a)=>br(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>Ce.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Ce.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function S_(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function E_(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function C_(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function x_(e,t){let i=[],r=u_("sha256").update(`${p_}
|
|
172
|
-
[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(_r(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Ce.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(S_(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=E_(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:C_(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function Kg(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function P_(e,t){return Kg(e.classification)-Kg(t.classification)||br(e.left,t.left)||br(e.right,t.right)}function Yg(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:d_,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function Zg(e){let t=k_(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(x_(t[s],t[c]));i.sort(P_);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(f_,{changes:t,relationships:r}),a=i.slice(0,Ce.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Yg(t,i,a,n);for(;a.length>0&&td(JSON.stringify(o))>Ce.maxSerializedBytes;)a=a.slice(0,-1),o=Yg(t,i,a,n);if(td(JSON.stringify(o))>Ce.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as oI}from"node:crypto";import{promises as nt}from"node:fs";import vt from"node:path";import ew from"node:path";var tw="comet.native.check-receipt.v1",R_="comet.native.check-receipt.v1",kr="scoped-text-safety",nd=1,xe=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),A_=/^[a-f0-9]{64}$/u,__=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,I_="comet.native.checker-policy.v1",T_="comet.native.check-input.v1",j_=2048,iw=j(I_,{policy:kr,version:nd,limits:xe,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),$_=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),rw=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],aw=["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"],O_=new Set(aw);function fi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pi(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function jt(e,t){if(typeof e!="string"||!A_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Te(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function ow(e,t){let i=Te(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function nw(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function H_(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>j_||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=ew.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||ew.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function D_(e){let t=fi(e,"Native check receipt checker");pi(t,["policy","version","hash","limits"],"Native check receipt checker");let i=fi(t.limits,"Native check receipt limits");if(pi(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==kr||t.version!==nd||t.hash!==iw||i.maxFiles!==xe.maxFiles||i.maxFileBytes!==xe.maxFileBytes||i.maxTotalBytes!==xe.maxTotalBytes||i.maxIssues!==xe.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:kr,version:nd,hash:iw,limits:{...xe}}}function L_(e){let t=fi(e,"Native check receipt contract");return pi(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:jt(t.expectedHash,"Native check expected contract hash"),beforeHash:jt(t.beforeHash,"Native check before contract hash"),afterHash:jt(t.afterHash,"Native check after contract hash")}}function B_(e){let t=fi(e,"Native check receipt implementation");return pi(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:jt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:jt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:jt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:jt(t.afterSnapshotHash,"Native check after snapshot hash")}}function V_(e,t){let i=fi(e,`Native check batch ${t}`);pi(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Te(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Te(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Te(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Te(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Te(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Te(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>xe.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>xe.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function F_(e){let t=fi(e,"Native check receipt counts");pi(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Te(t.filesSelected,"Native check filesSelected"),filesScanned:Te(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Te(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Te(t.bytesScanned,"Native check bytesScanned"),issueCount:Te(t.issueCount,"Native check issueCount"),recordedIssueCount:Te(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(V_):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>xe.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>xe.maxFiles||i.bytesScanned>xe.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function q_(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||rw.indexOf(e.kind)-rw.indexOf(t.kind)}function M_(e){if(!Array.isArray(e)||e.length>xe.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=fi(r,`Native check issue ${n}`);if(pi(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!$_.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:H_(a.path,`Native check issue ${n} path`),line:ow(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(q_);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function W_(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!O_.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=aw.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function z_(e){return j(T_,e)}function sw(e){let t=fi(e,"Native check receipt");if(pi(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==tw)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!__.test(t.change))throw new Error("Native check receipt change name is invalid");let i=ow(t.sourceRevision,"Native check source revision"),r=D_(t.checker),n=L_(t.contract),a=B_(t.implementation),o=z_({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(jt(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=nw(t.startedAt,"Native check receipt startedAt"),c=nw(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=F_(t.counts),u=M_(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=W_(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>xe.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>xe.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:tw,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=jt(t.receiptHash,"Native check receipt content hash");if(j(R_,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var od="comet.native.verification-receipt.v3",J_=od,G_="comet.native.declared-artifacts.v1",U_=/^[a-f0-9]{64}$/u,K_=/^acceptance-[a-f0-9]{64}$/u,Y_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,X_=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Q_=4096,Z_=256,eI=1024;function Sr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function hi(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function $t(e,t){if(typeof e!="string"||!U_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function rt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=Fe(e).trim();if(!i||i.length>Q_||i!==e.trim())throw new Error(`${t} is invalid`);return i}function ad(e,t){let i=rt(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function Gn(e,t,i=rt,r=!1,n=Z_){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function tI(e,t){if(typeof e!="string"||!K_.test(e))throw new Error(`${t} is invalid`);return e}function iI(e){let t=Sr(e,"Native verification receipt bindings");if(hi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!Y_.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:$t(t.contractHash,"Native verification receipt contract hash"),scopeHash:$t(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:$t(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:$t(t.artifactHash,"Native verification receipt artifact hash")}}function rI(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=X_.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function nI(e,t,i,r){let n=Sr(t,`Native ${e} evidence`);if(e==="automated-check"){if(hi(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=ad(n.startedAt,"Native automated-check start time"),o=ad(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Sr(n.worktree,"Native automated-check worktree");if(hi(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=Sr(n.afterFence,"Native automated-check after fence");if(hi(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:rt(n.executable,"Native automated-check executable"),args:Gn(n.args,"Native automated-check arguments",rt,!0),cwd:rt(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:rt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:$t(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:$t(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:$t(n.outputHash,"Native automated-check output hash"),outputSummary:rt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){hi(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=rI(n.checkReceiptRef);if($t(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Gn(n.subjects,"Native static inspection subjects",rt,r==="required-check"),rule:rt(n.rule,"Native static inspection rule"),resultSummary:rt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return hi(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Gn(n.steps,"Native manual evidence steps"),observations:Gn(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function aI(e){let t=Sr(e,"Native verification receipt");if(hi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=rt(t.actor,"Native verification receipt actor"),o=Gn(t.acceptanceIds,"Native receipt acceptance IDs",tI,r==="required-check",eI).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:od,kind:i,role:r,status:n,bindings:iI(t.bindings),acceptanceIds:o,actor:a,issuedAt:ad(t.issuedAt,"Native verification receipt issue time"),evidence:nI(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==kr||s.actor!==`native-runtime:${kr}`))throw new Error("Native required check policy identity is invalid");return s}function cw(e){let t=Sr(e,"Native verification receipt");if(hi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==od)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=aI(r),a=$t(t.receiptHash,"Native verification receipt hash");if(j(J_,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function sd(e){return j(G_,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var fw=/^[a-f0-9]{64}$/u,Er=_i,kF=3*Er;function cd(e,t){let i=vt.relative(e,t);return i===""||!vt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${vt.sep}`)}function sI(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function us(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function lw(e){let t=await nt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await nt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function cI(e,t){let i=vt.resolve(e),r=vt.resolve(t);if(!cd(i,r))throw new Error("Native evidence path is outside its change");let n=[await lw(i)],a=i;for(let o of vt.relative(i,r).split(vt.sep).filter(Boolean)){a=vt.join(a,o);let s=await lw(a);if(!cd(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function uw(e){for(let t of e){let i=await nt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!sI(t,i)||await nt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function lI(e,t,i={}){let r=await cI(t,vt.dirname(e));await i.afterParentChainCaptured?.();let n=await nt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await nt.realpath(e);if(!cd(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await nt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),nt.lstat(e),nt.realpath(e)]);if(await uw(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!us(s,n)||!us(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Er)throw new Error(`Native evidence document exceeds ${Er} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=Er+1-d,S=await o.read(f,0,Math.min(f.length,m),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>Er)throw new Error(`Native evidence document exceeds ${Er} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),nt.lstat(e),nt.realpath(e)]);if(await uw(r),!v.isFile()||v.isSymbolicLink()||h!==a||!us(s,p)||!us(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function pw(e,t){if(!fw.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function uI(e,t,i,r,n){if(!fw.test(i))throw new Error("Native report evidence hash is invalid");let a=await Ii({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||oI("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function Cr(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function dI(e,t,i,r,n){let a=pw(i,r);return n?vt.join(n,...a.split("/")):ei(U(e,t),a)}async function Ii(e){let t=dI(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??le(e.paths,t);return await J(i,t),lI(t,i,e.hooks)}function dw(e,t){return Qo(e,t)}function fI(e,t){let i=Zo(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function pI(e,t,i){let r=hg(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function hI(e,t,i){let r=$u(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function mI(e,t,i,r=!1,n){let a=await ds(e,t,i.implementationScopeRef,void 0,n);if(r&&await uI(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await hw(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Un(e,t,i,r,n){let a=Cr(i,"scopes"),o=fI(await Ii({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Cr(o.baselineProjectionRef,"snapshots"),c=Cr(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Ii({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>dw(d,s)),Ii({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>dw(d,c))]);return sg({baseline:l,current:u,scope:o})}async function ds(e,t,i,r,n){return(await Un(e,t,i,r,n)).scope}async function hw(e,t,i,r,n){let a=Cr(i,"allowances");return pI(await Ii({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function Kn(e,t,i,r,n){let a=Cr(i,"receipts"),o=cw(await Ii({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function xr(e,t,i,r,n){let a=Cr(i,"verifications"),o=hI(await Ii({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await mI(e,t,o,!1,n),o}var vI=4096;async function gI(e,t=Ce.maxChanges){try{let i=await Nn({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function mw(e,t){let i=await At(e,t),[r,n]=await Promise.all([i.implementation_scope?ds(e,t,i.implementation_scope):null,Pt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function fs(e,t,i={}){let n=(await gI(e,vI)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await mw(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await mw(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Zg([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{execFile as RI}from"node:child_process";import{promisify as AI}from"node:util";import{constants as ld,promises as Me}from"node:fs";import Pr from"node:path";var yI=/^[a-f0-9]{64}$/u,NI=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Yn=512*1024;function bI(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ps(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kI(e,t){let i=Pr.resolve(e),r=Pr.resolve(t);if(!V(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...Pr.relative(i,r).split(Pr.sep).filter(Boolean)]){o&&(a=Pr.join(a,o));let s=await Me.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Me.realpath(a);if(n.length>0&&!V(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function gw(e){for(let t of e){let i=await Me.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!bI(t,i)||await Me.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function SI(e){if(!yI.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function EI(e){let t=NI.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function CI(e,t,i){return ei(U(e,t),SI(i))}async function xI(e,t,i){let r=await kI(i,Pr.dirname(e)),n=await Me.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Yn)throw new Error(`Native check receipt exceeds ${Yn} bytes`);let[a,o]=await Promise.all([Me.realpath(t),Me.realpath(e)]);if(!V(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":ld.O_RDONLY|ld.O_NOFOLLOW|ld.O_NONBLOCK,c=await Me.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Me.lstat(e),Me.realpath(e)]);if(await gw(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ps(n,l)||!ps(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=Yn+1-p,N=await c.read(v,0,Math.min(v.length,y),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,p>Yn)throw new Error(`Native check receipt exceeds ${Yn} bytes`);f.push(Buffer.from(v.subarray(0,N.bytesRead)))}let[h,m,S]=await Promise.all([c.stat(),Me.lstat(e),Me.realpath(e)]);if(await gw(r),!m.isFile()||m.isSymbolicLink()||S!==o||!V(a,S)||!ps(l,h)||!ps(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function ww(e,t,i){let r=EI(i),n=U(e,t),a=CI(e,t,r),o=le(e,a);await J(o,a);let s=sw(await xI(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var Xn=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var mq=64*1024;var vq=3600*1e3;var gq=AI(RI);var _I=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function yw(e,t){let i=[];for(let r of _I){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function Nw(e){if(e.receipt.kind!=="static-inspection")return null;let t=await ww(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var mi=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function II(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function TI(e){let t=II(e.bundle.baseline),i=await Gl(e.paths,t,{origin:"explicit",now:e.now});return _u({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function kw(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Un(e.paths,e.state.name,e.state.implementation_scope),i=await pr({changeDir:fe(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await TI({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function Sw(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await kw(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function jI(e){let t=await ne({root:fe(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Gh(t.text)}}function $I(e){let{receipt:t,implementationScope:i}=e,r=[],n=Au({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function OI(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:sd(e.implementationScope.scope.declaredArtifacts)}}async function bw(e){let t=await Kn(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=yw(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new mi([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await Nw({paths:e.paths,state:e.state,receipt:t});if(n){let a=$I({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function HI(e){let t=OI({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await bw({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof mi)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await bw({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof mi)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new mi(i)}function ud(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function dd(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:ud(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([kw(e),xr(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:ud(e.state.verification_result,"stale"),envelope:null};let r=await jI({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await HI({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:ud(e.state.verification_result,"invalid"),envelope:null}}}function LI(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function Cw(e){try{return await DI.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function BI(e,t){try{return(await ne({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function VI(e,t,i){let r=qo(e,i.capability);if(!V(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=Ew.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await BI(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ne({root:fe(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function FI(e,t){return Cw(Wu(e,t))}async function fd(e){let t=e.now??new Date,i=await At(e.paths,e.name),r=await Pt(e.paths,e.name),n=await Ee(e.paths.projectRoot),a=LI(i.name,t),o=Ew.resolve(e.paths.nativeRoot,...a.split("/"));if(!V(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(v=>VI(e.paths,i.name,v))),dd({paths:e.paths,state:i,now:t}),fs(e.paths,i.name),Fo(e.paths,i.name),Qm(e.paths,i.name),FI(e.paths,i.name),Cw(o)]);return Gg({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}async function qI(e,t){let i=U(e,t.name),r=await dr(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await jo(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Pi(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function MI(e,t){let i=await qI(e,t);return{committed:i,latest:kg(i),history:bg(i)}}async function xw(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await MI(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var Ot=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function zI(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function JI(e){return(await Vv(e))?.change??null}function GI(e,t,i=!1,r){return as({state:e,archiveReady:t,evidenceRetreat:i}).command}async function UI(e,t){let i=fe(e,t.name),r=[...(await ou(i,t.brief)).findings,...(await av(e,t)).findings,...await Fv(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Po(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Cm(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await pr({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Tg(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await su(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function pd(e,t,i){let r=await JI(e)===t,n=await Sl(e,t),a=await Pn(e,t),o;try{let w=await nu(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=Ku({paths:e,state:o,findings:[w]}),O=as({state:o,findings:C});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:Yu(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...i?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await Wg({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await xw(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await pr({changeDir:fe(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let pe=await xr(e,o.name,o.verification_evidence);for(let Q of pe.acceptanceTrace.entries)C.set(Q.acceptanceId,Q.status==="failed"?"failed":Q.status==="missing"?"missing":"satisfied")}let O=Wh({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),T=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...T?{nextPageCommand:zI(T),nextPageArgs:T}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await fs(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await Pt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let C=await Rn({paths:e,identity:w});C.state==="drifted"&&C.code&&f.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await Ho({paths:e,identity:w});f.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let w=await Sw({paths:e,state:o});v=w.freshness!=="fresh",p.push(...w.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await fd({paths:e,name:o.name}),m.push(...h.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let S=[...await UI(e,o),...s.findings,...d,...f,...p,...l,...m].filter((w,C,O)=>O.findIndex(T=>T.code===w.code&&T.path===w.path)===C),y=Ku({paths:e,state:o,findings:S}),N=y.filter(w=>!fr(w.code)),k=o.phase==="archive"&&h?.ready===!0&&N.length===0,E=v||o.phase==="archive"&&(h?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=y.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),x=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",g=y.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:b||x?null:GI(o,k,E,i?.clarificationMode),archiveReady:k,inspection:s.inspection,findingSummary:Yu(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:as({state:o,findings:y,archiveReady:k,evidenceRetreat:E,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:cs,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...g?{error:g.message}:{}}}async function Pw(e){let t;try{t=await Hl({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await WI.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Ot.maxChanges))throw new Error(`Native status exceeds ${Ot.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}import eT from"node:path";function Ti(e,t,i){return e.language==="zh-CN"?i:t}function KI(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:Ti(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:Ti(e,"Reply A or B","回复 A 或 B"),agentInstruction:Ti(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 i(Ti(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(Ti(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:r})=>r==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"由于独立验收服务暂时不可用,目前只能完成自动检查。你可以选择接受当前检查结果,或者等验收服务恢复后再重试。",suggestedReply: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 i(Ti(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 md(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function hs(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Rw(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function YI(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function XI(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function QI(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 Qn(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:md({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[hs("summary","--summary"),Rw(e.name,e.flag)]}}function hd(e){return[Qn({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Qn({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Aw(e,t){let i=XI(t)&&e.coordination_mode===void 0,r={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:KI(e,i)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...r,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"?{...r,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[hs("summary","--summary")],commandAlternatives:[Qn({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...hd({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"?{...r,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:md({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"?{...r,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[hs("summary","--summary")],commandAlternatives:[Qn({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...hd({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...r,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[hs("summary","--summary")],commandAlternatives:hd({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...r,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{...r,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?md({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{...r,disposition:i?"await-user":"continue",action:"confirm-shape",commandArgs:QI({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[YI("coordination-mode","--coordination-mode",Uh)]:[],Rw("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...r,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{...r,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...r,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{...r,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...r,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{...r,userCommunication:!a&&o?{...r.userCommunication,agentInstruction:`${r.userCommunication.agentInstruction} ${Ti(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:r.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?{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[Qn({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}function ZI(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function _w(e){let t=e.acceptance.reduce((i,r)=>({...i,[r.result]:i[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:ZI(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}function tT(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function iT(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function rT(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:oT(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:sT(r,i)}))]:[]]}function nT(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function Iw(e,t){let i=be(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:eT.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}function aT(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function ms(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function oT(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:ms(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function sT(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:ms(e.summary,t)??""}}async function vd(e){let t=await Bv(e),i=_w(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await vu({paths:e.paths,state:t.state}),a=await On(e.paths,e.name),o=a?{...Iw(e.paths,t.state),projectRoot:"."}:Iw(e.paths,t.state),s=Aw(t.state,n),c=o.bindingState==="mismatch"?{...s,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...s.runnerAction,kind:"none"}}:s,l=a?aT(e.paths,a):[],u=a?(()=>{let p=a.children.filter(({status:N})=>N==="pending"||N==="ready").length,v=a.children.filter(({status:N})=>N==="active"||N==="verified").length,h=a.children.filter(({status:N})=>N==="integrated"||N==="archived").length,m=a.children.filter(({status:N})=>N==="blocked"||N==="needs-reverify").length,S=a.children.filter(({status:N})=>N==="active"||N==="blocked"||N==="needs-reverify").slice(0,16).map(N=>({name:N.name,summary:N.summary,projectRoot:N.task?.projectRoot??N.projectRoot?"<worktree>":null,reason:ms(N.blocker,l)})),y=a.children.flatMap(({blocker:N})=>{let k=ms(N,l);return k?[k]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:a.children.length,waiting:p,working:v,integrated:h,blocked:m,active:S,agents:{working:a.children.filter(({task:N})=>N!==null).length,completed:h},risks:y,nextAction:a.finalVerification.status==="passed"?"final-delivery":a.finalVerification.status==="pending"&&h===a.children.length?"parent-verification":p>0?"dispatch-ready-child":m>0?"resolve-blocker":"continue-supervisor"}})():null,d=e.details?(()=>{let p=a?.stateVersion??0,v=rT(t.state,a,l),h=iT(e.cursor,t.state.state_version,p),m=v.slice(h,h+32),S=h+m.length<v.length?tT(t.state.state_version,p,h+m.length):null;return{items:m,nextCursor:S,supervisorStateVersion:p}})():null,f=a?{schema:a.schema,parent:a.parent,integration:{branch:a.integration.branch,targetBranch:a.integration.targetBranch},finalVerification:{status:a.finalVerification.status,summary:a.finalVerification.summary},summary:u}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:nT(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:a?[]:i.blockers,workspace:o,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((p,v)=>({...p,[v.status]:(p[v.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},continuation:c,...e.details?{details:{stateVersion:t.state.state_version,...a?{supervisorStateVersion:d.supervisorStateVersion}:{},items:d.items,nextCursor:d.nextCursor,nextPageArgs:d.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",d.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}var lT=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function vs(e,t){let i=vi.normalize(gd(e)),r=vi.normalize(gd(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function gd(e){let t=vi.resolve(e);try{return cT.native(t)}catch{return t}}function uT(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function Tw(e){let t=[];for(let i of await Pw(e))t.push({name:i,kind:await Nu(e,i)?"portable":"legacy"});return t}async function Hw(e){let t=vi.resolve(e),i=Dt(e),r=i.length>0?i:[t];r.some(o=>vs(o,t))||r.push(t);let n=[],a=new Set;for(let o of r.map(s=>vi.resolve(s)).sort()){let s=vs(o,t)?t:o,c=gd(s),l=process.platform==="win32"?c.toLowerCase():c;if(a.has(l))continue;a.add(l);let u=await Ee(s);if(!u)continue;let d=await kt(s,u.native.artifact_root);n.push({projectRoot:s,config:u,paths:d,changes:await Tw(d)})}if(n.length===0){let o=await Ee(e);if(!o)throw new Error(".comet/config.yaml was not found in any registered worktree");let s=await kt(e,o.native.artifact_root);n.push({projectRoot:vi.resolve(e),config:o,paths:s,changes:await Tw(s)})}return n}function jw(e,t){return e.workspace.bindingState==="aligned"?0:vs(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function Dw(e,t){let i=new Map;for(let n of t)for(let a of n.changes)i.set(a.name,[...i.get(a.name)??[],{source:n,kind:a.kind}]);let r=[];for(let[n,a]of[...i.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:c,kind:l})=>{if(l==="portable")try{let u=await vd({paths:c.paths,name:n});return{source:c,name:n,kind:l,workspace:u.workspace,portableStatus:u,inspectionError:null}}catch(u){return{source:c,name:n,kind:l,workspace:await Pn(c.paths,n),portableStatus:null,inspectionError:u instanceof Error?u.message:String(u)}}return{source:c,name:n,kind:l,workspace:await Pn(c.paths,n),portableStatus:null,inspectionError:null}}));o.sort((c,l)=>jw(c,e)-jw(l,e)||c.source.projectRoot.localeCompare(l.source.projectRoot));let s=o.filter(c=>c.workspace.bindingState==="aligned");s.length>1?r.push(...s):r.push(s[0]??o[0])}if(r.length>Ot.maxChanges)throw new Error(`Native status discovery exceeds ${Ot.maxChanges} visible changes`);return r.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function $w(e,t){let i=t.toString(36),r=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${i}.${r}`}function dT(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=lT.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let r=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:i});if(t[3]!==r)throw new Error("Native workspace status cursor integrity failed");return i}function Ow(e,t){let i=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:i?uT(i):null,nextPageArgs:i}}async function fT(e,t,i){let r=null;try{r=await ev(e.source.paths,e.name)}catch{}return r?.state?{schema:"comet.native.status.v2",name:e.name,phase:r.state.phase,status:"blocked",migrationRequired:!0,legacySchema:r.schema,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:r.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:pd(e.source.paths,e.name,{details:t,...i?{acceptanceCursor:i}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function Lw(e,t,i,r){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(i)throw new Error("Portable Native status includes the complete acceptance list");return!t&&e.portableStatus?e.portableStatus:vd({paths:e.source.paths,name:e.name,details:t,...r?{cursor:r}:{}})}return fT(e,t,i)}async function Bw(e){let t=await Hw(e.projectRoot),i=(await Dw(e.projectRoot,t)).filter(r=>r.name===e.name);if(i.length===0){let r=t.find(n=>vs(n.projectRoot,e.projectRoot))??t[0];return pd(r.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:r.config.native.clarification_mode,maxVerifyFailures:r.config.native.max_verify_failures})}if(i.length>1)throw new Error(`Native change ${e.name} has multiple aligned workspace bindings: ${i.map(r=>r.source.projectRoot).join(", ")}`);return Lw(i[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function Vw(e){let t=await Hw(e.projectRoot),i=await Dw(e.projectRoot,t),r=j("comet.native.workspace-status-candidates.v1",i.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=dT({candidatesHash:r,total:i.length,cursor:e.cursor}),a=await Promise.all(i.slice(n,n+Ot.maxItems).map(u=>Lw(u,!1))),o=[],s=i.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],f=n+d.length,p=f<i.length?$w(r,f):null,v={schema:s,total:i.length,offset:n,items:d,nextCursor:p,...Ow(vi.resolve(e.projectRoot),p),limits:{...Ot}};if(Buffer.byteLength(JSON.stringify(v),"utf8")>Ot.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<i.length?$w(r,c):null;return{schema:s,total:i.length,offset:n,items:o,nextCursor:l,...Ow(vi.resolve(e.projectRoot),l),limits:{...Ot}}}import Zn from"path";import{realpathSync as _T}from"fs";var Ht={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Fw(e){return e?e.command?`${Ht.next} ${e.command}`:e.ask_user?`${Ht.next} ${e.ask_user}`:null:null}function qw(e,t){let i=[e.summary],r=Fw(e.next);return r&&i.push(r),e.user_message&&i.push("",Ht.relay,e.user_message),t!==void 0&&i.push("",Ht.details,JSON.stringify(t,null,2)),`${i.join(`
|
|
169
|
+
${Tr(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function WR(e){if(Vn(e)<=_i)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=Kv("sha256");a.update(`${HR}
|
|
170
|
+
`),e.omissionOverflow&&ci(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(r+=1),n+=1,ci(a,"omission",f)},s=f=>{r+=1,n+=1,ci(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let p=i[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(f,1),p}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Vn(u)>_i;){if(i.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(i.length/4));for(let v=0;v<p;v+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-p))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function Cu(e){let t=xi(e),i=t.entries.map((n,a)=>VR(n,`Snapshot entry ${a}`));if(i.sort(qR),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>FR(n,`Snapshot omission ${a}`));return r.sort(MR),WR({schema:Yv,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Fn(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:li(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>ve(i.path,r.path)||ve(i.kind,r.kind))}function qn(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Mv(e){return e?{hash:e.hash,size:e.size}:null}function Ru(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:ve(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:Mv(c),after:Mv(l)})}}function Zv(e,t){return{...e,attributedTo:t.filter(i=>qn(i,e.path))}}function Au(e){let t=Fn(e.declaredArtifacts),i=[];return Ru(e.baseline,e.current,r=>{i.push(Zv(r,t))}),i}function _t(e,t){return{id:`scope:${j($R,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function zR(e,t){let i=t.omitted.map(r=>_t({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(_t({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(_t({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function Wv(e,t){return zR(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function xu(e,t){return ve(e.kind,t.kind)||ve(e.source,t.source)||BR(e.path,t.path)||ve(e.id,t.id)}function JR(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(xu)}function eg(e){return[...new Set(e.map((t,i)=>li(t,`Git path ${i}`)))].sort(ve)}function zv(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function GR(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function tg(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=eg(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:zv(e.baseCommit,"Native external drift base commit"),targetBranch:GR(e.targetBranch,"Native external drift target branch"),targetCommit:zv(e.targetCommit,"Native external drift target commit"),paths:t}}function ig(e){if(typeof e.contractHash!="string"||!Pu.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Fn(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:eg(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:tg(e.externalDrift)}}}function UR(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return Ru(e,t,p=>{let v=i.some(h=>qn(h,p.path));if(d+=1,c.push(p.path),!v&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<DR){let h=Zv(p,i),m=Vn(h);l+m<=_i?(a.push(h),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function rg(e,t){return _t({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function KR(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let i={changes:wr(Number(t[1]),"Scope overflow change count"),unresolved:wr(Number(t[2]),"Scope overflow unresolved count"),unattributed:wr(Number(t[3]),"Scope overflow unattributed count")},r=Ai(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(rg(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function YR(e){let t=Kv("sha256");t.update(`${OR}
|
|
171
|
+
`);let i=0;Ru(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){ci(t,"change",n);let a=0;for(let o of e.declaredArtifacts)qn(o,n.path)&&(a+=1,ci(t,"change-attribution",o));ci(t,"change-end",{attributionCount:a}),a===0&&ci(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&ci(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function ng(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=UR(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let x=new Set(i.externalDrift.paths),g=new Set(o.changePaths),w=i.externalDrift.paths.filter(C=>!g.has(C)||n.some(O=>qn(O,C)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(x.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=j(Ln,e),c=j(Ln,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[x,g]of[["baseline",e],["current",t]])for(let w of g.omitted){if(l.length>=LR)break;l.push(_t({kind:"snapshot-omission",source:x,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${x} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...Wv("baseline",e),...Wv("current",t),...o.totalChanges===0&&a===null?[_t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(i.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(g=>x.has(g)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(g=>!x.has(g))}},v=x=>{let g=o.candidates.slice(0,x.detailedChangeCount),w=g.filter(We=>We.attributedTo.length===0&&!u.has(We.path)),C=o.totalChanges-g.length,O=o.totalUnattributed-w.length,T=d-x.detailedOmissionCount,he=O+T,Q=[...w.map(We=>_t({kind:"unattributed-change",source:"implementation-scope",path:We.path,evidence:{after:We.after,before:We.before,changeKind:We.kind}},`Changed path is not covered by a declared artifact: ${We.path}`)),...l.slice(0,x.detailedOmissionCount),...f,...he>0?[rg(x.overflowHash,{changes:C,unattributed:O,unresolved:he})]:[]],G=JR(Q),at=x.includeGitAdvisory?p():void 0;return{schema:Su,contractHash:r,baselineProjectionRef:Eu(s),baselineProjectionHash:s,currentProjectionRef:Eu(c),currentProjectionHash:c,complete:G.length===0,declaredArtifacts:n,changes:g,unattributed:w,unresolvedScopes:G,noCodeReason:a,...at?{gitAdvisory:at}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},h=o.candidates.length,m=l.length,S=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let x=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:y});if(Vn({...x,scopeHash:y})<=_i)break;if(S){S=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let k=o.totalChanges>h||d>m?YR({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):y,E=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:k}),b={...E,scopeHash:j(Xv,E)};if(Vn(b)>_i)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function _u(e){let t=Cu(e.baseline),i=Cu(e.current),r=ig(e);return{authority:r,baseline:t,current:i,scope:ng(t,i,r)}}var XR=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function ht(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mt(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function Ai(e,t){if(typeof e!="string"||!Pu.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Jv(e,t,i){let r=Eu(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function ts(e,t){let i=ht(e,"Native snapshot projection");if(mt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Yv)throw new Error("Native snapshot projection schema is invalid");let r=xi({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=Cu(r);if(j(Ln,i)!==j(Ln,n))throw new Error("Native snapshot projection is not canonical");let a=j(Ln,n);if(t!==void 0&&Ai(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Iu(e,t){let i=ht(e,`Declared artifact ${t}`);if(mt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:li(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Gv(e,t){if(e===null)return null;let i=ht(e,t);return mt(i,["hash","size"],[],t),{hash:Ai(i.hash,`${t} hash`),size:wr(i.size,`${t} size`)}}function Uv(e,t){let i=ht(e,`Implementation change ${t}`);if(mt(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Iu),n=Fn(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Gv(i.before,`Implementation change ${t} before`),o=Gv(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:li(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function QR(e,t){let i=ht(e,`Unresolved scope ${t}`);mt(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Qv(i.path,`Unresolved scope ${t} path`):li(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Bn(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>li(n,`${t} ${a}`)),r=[...new Set(i)].sort(ve);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function ag(e){let t=ht(e,"Native implementation external drift");if(mt(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=Bn(t.paths,"Native external drift paths");return tg({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function is(e){let t=ht(e,"Native implementation scope"),i=[...XR].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(mt(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Su)throw new Error("Native implementation scope schema is invalid");let r=Ai(t.contractHash,"Implementation scope contractHash"),n=Ai(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Jv(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Ai(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Jv(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Iu);if(JSON.stringify(c)!==JSON.stringify(Fn(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Uv),u=[...l].sort((w,C)=>ve(w.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(C=>qn(C,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Uv),p=t.externalDrift===void 0?void 0:ag(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(QR),S=m.filter(w=>w.kind==="scope-detail-overflow");if(S.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=S[0]===void 0?null:KR(S[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let N=t.noCodeReason,k=[...h.map(w=>_t({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(y?.changes??0)===0&&N===null?[_t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(xu))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(E)!==JSON.stringify(k.sort(xu))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=ht(t.gitAdvisory,"Implementation scope Git advisory");if(mt(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Bn(w.changedPaths,"Git changed paths"),O=Bn(w.pathsPresentInSnapshotChanges,"Git present paths"),T=Bn(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),he=[...O,...T].sort(ve);if(JSON.stringify(he)!==JSON.stringify(C)||T.some(Q=>l.some(G=>G.path===Q)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:T}}let x={schema:Su,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:N,...b?{gitAdvisory:b}:{},...p?{externalDrift:p}:{}},g=Ai(t.scopeHash,"Implementation scope scopeHash");if(j(Xv,x)!==g)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:g}}function ZR(e){let t=ht(e,"Native implementation scope authority");if(mt(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Iu);if(JSON.stringify(i)!==JSON.stringify(Fn(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=Bn(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:ag(t.externalDrift),a=ig({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Mn(e){let t=ht(e,"Native implementation scope bundle");mt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=ZR(t.authority),r=ts(t.baseline),n=ts(t.current),a=is(t.scope),o=ng(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function og(e){let t=is(e.scope);return Mn({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var lg=/^[a-f0-9]{64}$/u;var eA="comet.native.acceptance-trace.v2",tA="comet.native.partial-allowance.v1",iA="comet.native.verification-evidence.v2";function It(e,t){if(!lg.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ug(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function dg(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Tu(e,t,i=2e3){let r=Fe(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Wn(e,t){let i=sg.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||sg.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function rA(e,t,i){let r=Wn(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ct(r),a=r.toLowerCase(),o=i?Wn(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function ju(e){let t=Wn(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function yr(e,t){return e<t?-1:e>t?1:0}function rs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ns(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function fg(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function cg(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function nA(e){let t=rs(e,"Native acceptance trace");if(ns(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!lg.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=Wn(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=rs(o,`Native acceptance trace entry ${s}`);if(ns(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>ju(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(yr))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Wn(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Tu(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>yr(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=It(t.traceHash,"Native acceptance trace hash");if(j(eA,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function pg(e){let t=rs(e,"Native partial allowance");if(ns(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(yr))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:dg(t.change),scopeHash:It(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Tu(t.reason,"Partial allowance reason"),confirmedSummary:Tu(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:ug(t.sourceRevision),confirmedAt:fg(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=It(t.allowanceHash,"Native partial allowance hash");if(j(tA,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function $u(e){let t=rs(e,"Native verification evidence");if(ns(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=It(t.implementationScopeHash,"Native verification implementation scope hash"),r=nA(t.acceptanceTrace),n=It(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:It(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>ju(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(yr)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(yr);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>ju(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(yr)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:dg(t.change),sourceRevision:ug(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:It(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:cg(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:rA(t.reportRef,"Native verification report ref"),reportHash:It(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:cg(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:fg(t.createdAt,"Native verification timestamp")},d=It(t.envelopeHash,"Native verification envelope hash");if(j(iA,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function Ou(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var hg="repairStagnation",Ie={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},oA=/^[a-f0-9]{64}$/u;var sA=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),cA=["data","runId","sequence","timestamp","type"],mg=["disposition","overrideSummaryHash","signatureHash"],lA=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],vg=12;function Du(e,t){return e<t?-1:e>t?1:0}function gg(e,t,i){let r=Object.keys(e).sort(Du);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function as(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function zn(e,t){if(typeof e!="string"||!oA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function uA(e){if(!Array.isArray(e)||e.length>gr.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Du)}function wg(e){if(typeof e!="string"||e.length===0||e.length>Ie.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Hu(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Ie.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Ie.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Ie.maxTextCharacters&&(!n||e.length>Ie.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Ie.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Ie.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Hu(s,t+1,i,`${r}[${c}]`));return}let a=as(e,r),o=Object.keys(a);if(o.length>Ie.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Ie.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Ie.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Hu(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function dA(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function fA(e,t,i){let r=as(e,`Native repair trajectory event ${t+1}`);if(gg(r,cA,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(dA(r.timestamp),typeof r.type!="string"||!sA.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(wg(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Hu(r.data,0,n,"Native trajectory event data"),as(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Lu(e){let t=as(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Du),r=i.length===mg.length&&i.every((l,u)=>l===mg[u]);r||gg(t,lA,"Native repair trajectory projection");let n=zn(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:zn(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=zn(t.contractHash,"Native repair trajectory contract hash"),s=uA(t.failedAcceptanceIds),c=bu(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function pA(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function hA(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??vg;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=ku({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<gr.warningAtConsecutiveFailures?"continue":a<gr.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function mA(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??vg;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function yg(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Ie.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=wg(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=fA(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Ie.maxTotalDataNodes||c>Ie.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?zn(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?zn(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,hg)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Lu(f[hg]);if(pA(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(i.length=0,o=0),p!==null&&(n=p),hA(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");mA(v,i,r);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>gr.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function Ng(e){return yg(e).history}function bg(e){let t=yg(e).latestProjection;return t?{...t}:null}var Nr={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:[]},Bu=K("comet-native-runtime:v3:scope-reopen"),vA=[{skillVersion:"3",skillHash:K("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:K("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:K("comet-native-runtime:v1")}];function kg(e){return e.skillVersion===Nr.definition.metadata.version&&e.skillHash===Bu||vA.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function Sg(e){return K(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var Rg=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],kA=new Set(Rg),Ag=new Set([...Rg,"minimum_runtime_version","revision"]),SA=new Set([...Ag,"operation"]),EA=512*1024,Fu=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),CA=new Set([...Fu,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),qu=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Wu(e,t){return bA.join(U(e,t),"transition.json")}function ss(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function zu(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function os(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Mu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!CA.has(u)),a=[...Fu].find(u=>!Object.hasOwn(i,u)),o=Fu.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Ou(i.summary,"Native transition journal event summary"),Fe(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Ou(i.noCodeReason,"Native transition journal event no-code reason"),Fe(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Lu(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function xA(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return Mu({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Mu(e,t)}function Ju(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?xA(e.eventData,e.evidenceHash):Mu(e.eventData,e.evidenceHash),n=Kl(e.nextRun),a=e.previousRun===null?null:Kl(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Eg(e,t,i=!1){if(e.skill!==Nr.definition.metadata.name||(i?!kg(e):e.skillVersion!==Nr.definition.metadata.version||e.skillHash!==Bu)||e.orchestration!==Nr.definition.orchestration.mode||e.pendingRef!==Be.pendingRef||e.trajectoryRef!==Be.trajectoryRef||e.contextRef!==Be.contextRef||e.artifactsRef!==Be.artifactsRef||e.checkpointRef!==Be.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Cg(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function xg(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function Gu(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Eg(o,"next Run",r||a!==null),xg(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Eg(a,"previous Run",!0),xg(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!Vu(Cg(a),Cg(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function PA(e,t,i){return K(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function _g(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Pg(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Uu(e,t,i,r,n=!1){let a=i.eventData,o=Pg(e),s=Pg(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&Vu(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&Vu(e.spec_changes,t.spec_changes),l=Sg({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=PA(e.name,a.summary,t.spec_changes),l=K(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function RA(e,t){let i=ss(e);if(zu(i,SA),i.schema!==rr)throw new Error(`Expected Native transition schema ${rr}`);let r=os(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${rr} minimum_runtime_version must be ${3}`);let n=os(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Ju(i,t),o=ni(i.previousState),s=ni(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Uu(o,s,a,i.operation),Gu(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:rr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function AA(e,t){let i=ss(e);if(zu(i,kA),i.schema!==Nn)throw new Error(`Expected Native transition schema ${Nn}`);let r=Ju(i,t,!0),n=ar(i.previousState),a=ar(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Uu(n,a,r,_g(n,a,r.eventData),!0),Gu(n,a,r,!0),{schema:Nn,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function _A(e,t){let i=ss(e);if(zu(i,Ag),i.schema!==nr)throw new Error(`Expected Native transition schema ${nr}`);if(os(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${nr} minimum_runtime_version must be 2`);let n=os(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Ju(i,t,!0),o=or(i.previousState),s=or(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Uu(o,s,a,_g(o,s,a.eventData),!0),Gu(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:nr,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function IA(e,t){let i=ss(e);if(i.schema===rr)return{status:"current",journal:RA(i,t)};if(i.schema===Nn)return{status:"migration-required",journal:AA(i,t)};if(i.schema===nr)return{status:"migration-required",journal:_A(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function TA(e,t){let i=Wu(e,t),r=ue(e,i);await J(r,i);try{let n=await Et({root:r,file:i,maxBytes:EA,label:`Native transition journal ${t}`});return IA(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ig(e,t){let i=await TA(e,t);if(!i)return null;if(i.status==="migration-required")throw new qu(t);return i.journal}var jA=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function $A(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function OA(e){return e?e.map($A).join(" "):null}function HA(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function qe(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function DA(e){return e.map(t=>qe(t,[],null))}function LA(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[qe("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(qe("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(qe("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),qe("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(qe("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(qe("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),qe("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function ge(e,t){let i=t.commandArgs===void 0?HA(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?OA(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??DA(t.requiredInputs??[])}}function cs(e){let i=(e.findings??[]).filter(d=>!hr(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||jA.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return ge(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[qe("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return ge(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[qe("summary",["--summary"],"<summary>")]});if(n)return ge(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[qe("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),ge(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[qe("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):ge(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return ge(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=LA(e.state);return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Jn from"path";var Tg=8,BA={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function VA(e){let t=BA[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:hr(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function FA(e,t,i){if(!i.path)return null;let r;if(Jn.isAbsolute(i.path)?r=Jn.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Jn.resolve(pe(e,t.name),...i.path.split(/[\\/]/u)):r=Jn.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!V(e.projectRoot,r))return null;let n=Jn.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function qA(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Ku(e){return e.findings.map(t=>{let i=VA(t.code);return{code:t.code,message:t.message,severity:i.severity,path:FA(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:qA(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Yu(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,Tg),truncated:t.length>Tg}}import br from"path";var di={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},kr=/^[a-f0-9]{64}$/u;function ls(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function us(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function ui(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function jg(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Xu(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function MA(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||br.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=br.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function $g(e,t){return br.join(U(e,t),"checkpoints","progress.json")}function Gn(e,t){return br.join(U(e,t),"checkpoint-journal.json")}function Og(e,t,i){if(!kr.test(i))throw new Error("Native checkpoint manifest hash is invalid");return br.join(U(e,t),"checkpoints","manifests",`${i}.json`)}function WA(e){if(!kr.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Qu(e,t,i){let r=await Et({root:e,file:t,maxBytes:di.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function zA(e,t){let i=ls(e,`checkpoint manifest artifact ${t}`);us(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=MA(ui(i.path,`checkpoint artifact ${t} path`,4096)),n=ct(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!kr.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:Xu(i.size,`checkpoint artifact ${t} size`)}}function Zu(e,t){let i=ls(e,"Native checkpoint manifest");if(us(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>di.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(zA),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Xu(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>di.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Hg(e){return K(JSON.stringify(Zu(e,e.change)))}function Dg(e,t){let i=ls(e,"Native progress checkpoint");if(us(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=jg(i.previousRevision,"Native checkpoint previousRevision"),a=jg(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ui(i.manifestHash,"Native checkpoint manifestHash",64);if(!kr.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=WA(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ui(i.inputHash,"Native checkpoint inputHash",64);if(!kr.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ui(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Xu(i.artifactCount,"Native checkpoint artifactCount");if(u>di.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ui(i.summary,"Native checkpoint summary"),f=ui(i.nextAction,"Native checkpoint nextAction");if(Fe(d)!==d||Fe(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ui(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function JA(e,t){let i=ls(e,"Native checkpoint journal");if(us(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=ni(i.previousState),n=ni(i.nextState),a=Dg(i.checkpoint,t),o=Zu(i.manifest,t),s=ui(i.inputHash,"Native checkpoint journal inputHash",64),c=K(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!kr.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Hg(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function GA(e,t,i){let r=br.resolve(e.projectRoot,...t.split("/"));if(!V(e.projectRoot,r)||V(e.nativeRoot,r)||V(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=al(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await Et({root:e.projectRoot,file:r,maxBytes:di.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function UA(e,t){let i=$g(e,t),r=ue(e,i);await J(r,i);try{return Dg(await Qu(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function KA(e,t,i){let r=Og(e,t,i),n=ue(e,r);await J(n,r);let a=await Qu(n,r,"Native checkpoint manifest"),o=Zu(a,t);if(Lg(e,o),Hg(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function ed(e,t){let i=Gn(e,t),r=ue(e,i);await J(r,i);try{let n=JA(await Qu(r,i,"Native checkpoint journal"),t);return Lg(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Lg(e,t){for(let i of t.artifacts){let r=al(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Bg(e){let t;try{t=await UA(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:$g(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await KA(e.paths,e.name,t.manifestHash);let a=K(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await GA(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Og(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}var Vg=240,Fg=8,ds=50;function qg(e){let t=Array.from(e);return t.length<=Vg?e:`${t.slice(0,Vg-1).join("")}…`}function YA(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function XA(e){let t=[...new Set(e.map(YA))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Fg),reasonCount:e.length,codesTruncated:t.length>Fg};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,ds),reasonsTruncated:e.length>ds}}}async function Mg(e){let t=null;try{let s=await ed(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Gn(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Gn(e.paths,e.state.name)}}let i=await Bg({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=XA(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:di.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:qg(i.checkpoint.summary),nextAction:qg(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:di.maxArtifacts}}import{promises as LI}from"node:fs";import Sw from"node:path";import Wg from"node:path";var QA="comet.native.archive-preflight.v1",ZA="comet.native.archive-preflight.v1",e_="comet.native.archive-operation.v1",t_=/^[a-f0-9]{64}$/u,zg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,i_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function fs(e,t){return e<t?-1:e>t?1:0}function r_(e,t){if(typeof e!="string"||!t_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Tt(e,t){return e===null?null:r_(e,t)}function n_(e,t){let i=Wg.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Wg.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function a_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function o_(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function s_(e,t){if(!zg.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Tt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Tt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Tt(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function c_(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Tt(e.contractHash,"Native archive contract hash"),acceptanceHash:Tt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Tt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Tt(e.reportHash,"Native archive report hash"),envelopeHash:Tt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Tt(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function l_(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!i_.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(fs);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function u_(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(fs)}function Jg(e){if(!zg.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(s_).sort((l,u)=>fs(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:j(e_,l)})),r=c_(e.evidence),n=o_(e.workspace),a=[...new Set([...l_(e.findingCodes??[]),...u_({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(fs),o=a_(e.revision),s=n_(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:QA,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:j(ZA,c)}}import{createHash as d_}from"node:crypto";import Gg from"node:path";var f_="comet.native.conflict-radar.v1",Ce=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}),p_="comet.native.conflict-radar.v1",h_="comet.native.conflict-radar-signals.v1",m_=/^[a-f0-9]{64}$/u,Yg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,v_=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),g_=new Set(["capability","operation","baseHash"]),w_=new Set(["path","kind"]);function Sr(e,t){return e<t?-1:e>t?1:0}function td(e){return Buffer.byteLength(e,"utf8")}function id(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function rd(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(td(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function y_(e,t){let i=rd(e,t,Ce.maxArtifactPathBytes),r=Gg.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||Gg.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Xg(e,t){if(typeof e!="string"||!m_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function N_(e,t){let i=id(e,g_,t),r=rd(i.capability,`${t} capability`,Ce.maxCapabilityBytes);if(!Yg.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:Xg(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function b_(e,t){let i=id(e,w_,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:y_(i.path,`${t} path`),kind:i.kind}}function k_(e,t){let i=id(e,v_,`Conflict radar change ${t}`),r=rd(i.name,`Conflict radar change ${t} name`,Ce.maxNameBytes);if(!Yg.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>Ce.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>Ce.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>N_(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>Sr(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>b_(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>Sr(c.path,l.path)||Sr(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:Xg(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function S_(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Ce.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(k_).sort((n,a)=>Sr(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>Ce.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Ce.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function E_(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function C_(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function x_(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function P_(e,t){let i=[],r=d_("sha256").update(`${h_}
|
|
172
|
+
[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(Tr(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Ce.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(E_(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=C_(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:x_(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function Ug(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function R_(e,t){return Ug(e.classification)-Ug(t.classification)||Sr(e.left,t.left)||Sr(e.right,t.right)}function Kg(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:f_,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function Qg(e){let t=S_(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(P_(t[s],t[c]));i.sort(R_);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(p_,{changes:t,relationships:r}),a=i.slice(0,Ce.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Kg(t,i,a,n);for(;a.length>0&&td(JSON.stringify(o))>Ce.maxSerializedBytes;)a=a.slice(0,-1),o=Kg(t,i,a,n);if(td(JSON.stringify(o))>Ce.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as sI}from"node:crypto";import{promises as nt}from"node:fs";import vt from"node:path";import Zg from"node:path";var ew="comet.native.check-receipt.v1",A_="comet.native.check-receipt.v1",Er="scoped-text-safety",nd=1,xe=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),__=/^[a-f0-9]{64}$/u,I_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,T_="comet.native.checker-policy.v1",j_="comet.native.check-input.v1",$_=2048,tw=j(T_,{policy:Er,version:nd,limits:xe,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),O_=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),iw=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],nw=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],H_=new Set(nw);function fi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pi(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function jt(e,t){if(typeof e!="string"||!__.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Te(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function aw(e,t){let i=Te(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function rw(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function D_(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>$_||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=Zg.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Zg.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function L_(e){let t=fi(e,"Native check receipt checker");pi(t,["policy","version","hash","limits"],"Native check receipt checker");let i=fi(t.limits,"Native check receipt limits");if(pi(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Er||t.version!==nd||t.hash!==tw||i.maxFiles!==xe.maxFiles||i.maxFileBytes!==xe.maxFileBytes||i.maxTotalBytes!==xe.maxTotalBytes||i.maxIssues!==xe.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Er,version:nd,hash:tw,limits:{...xe}}}function B_(e){let t=fi(e,"Native check receipt contract");return pi(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:jt(t.expectedHash,"Native check expected contract hash"),beforeHash:jt(t.beforeHash,"Native check before contract hash"),afterHash:jt(t.afterHash,"Native check after contract hash")}}function V_(e){let t=fi(e,"Native check receipt implementation");return pi(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:jt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:jt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:jt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:jt(t.afterSnapshotHash,"Native check after snapshot hash")}}function F_(e,t){let i=fi(e,`Native check batch ${t}`);pi(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Te(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Te(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Te(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Te(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Te(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Te(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>xe.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>xe.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function q_(e){let t=fi(e,"Native check receipt counts");pi(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Te(t.filesSelected,"Native check filesSelected"),filesScanned:Te(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Te(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Te(t.bytesScanned,"Native check bytesScanned"),issueCount:Te(t.issueCount,"Native check issueCount"),recordedIssueCount:Te(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(F_):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>xe.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>xe.maxFiles||i.bytesScanned>xe.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function M_(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||iw.indexOf(e.kind)-iw.indexOf(t.kind)}function W_(e){if(!Array.isArray(e)||e.length>xe.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=fi(r,`Native check issue ${n}`);if(pi(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!O_.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:D_(a.path,`Native check issue ${n} path`),line:aw(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(M_);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function z_(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!H_.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=nw.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function J_(e){return j(j_,e)}function ow(e){let t=fi(e,"Native check receipt");if(pi(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==ew)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!I_.test(t.change))throw new Error("Native check receipt change name is invalid");let i=aw(t.sourceRevision,"Native check source revision"),r=L_(t.checker),n=B_(t.contract),a=V_(t.implementation),o=J_({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(jt(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=rw(t.startedAt,"Native check receipt startedAt"),c=rw(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=q_(t.counts),u=W_(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=z_(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>xe.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>xe.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:ew,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=jt(t.receiptHash,"Native check receipt content hash");if(j(A_,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var od="comet.native.verification-receipt.v3",G_=od,U_="comet.native.declared-artifacts.v1",K_=/^[a-f0-9]{64}$/u,Y_=/^acceptance-[a-f0-9]{64}$/u,X_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Q_=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Z_=4096,eI=256,tI=1024;function Cr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function hi(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function $t(e,t){if(typeof e!="string"||!K_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function rt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=Fe(e).trim();if(!i||i.length>Z_||i!==e.trim())throw new Error(`${t} is invalid`);return i}function ad(e,t){let i=rt(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function Un(e,t,i=rt,r=!1,n=eI){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function iI(e,t){if(typeof e!="string"||!Y_.test(e))throw new Error(`${t} is invalid`);return e}function rI(e){let t=Cr(e,"Native verification receipt bindings");if(hi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!X_.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:$t(t.contractHash,"Native verification receipt contract hash"),scopeHash:$t(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:$t(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:$t(t.artifactHash,"Native verification receipt artifact hash")}}function nI(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=Q_.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function aI(e,t,i,r){let n=Cr(t,`Native ${e} evidence`);if(e==="automated-check"){if(hi(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=ad(n.startedAt,"Native automated-check start time"),o=ad(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Cr(n.worktree,"Native automated-check worktree");if(hi(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=Cr(n.afterFence,"Native automated-check after fence");if(hi(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:rt(n.executable,"Native automated-check executable"),args:Un(n.args,"Native automated-check arguments",rt,!0),cwd:rt(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:rt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:$t(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:$t(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:$t(n.outputHash,"Native automated-check output hash"),outputSummary:rt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){hi(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=nI(n.checkReceiptRef);if($t(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Un(n.subjects,"Native static inspection subjects",rt,r==="required-check"),rule:rt(n.rule,"Native static inspection rule"),resultSummary:rt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return hi(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Un(n.steps,"Native manual evidence steps"),observations:Un(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function oI(e){let t=Cr(e,"Native verification receipt");if(hi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=rt(t.actor,"Native verification receipt actor"),o=Un(t.acceptanceIds,"Native receipt acceptance IDs",iI,r==="required-check",tI).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:od,kind:i,role:r,status:n,bindings:rI(t.bindings),acceptanceIds:o,actor:a,issuedAt:ad(t.issuedAt,"Native verification receipt issue time"),evidence:aI(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Er||s.actor!==`native-runtime:${Er}`))throw new Error("Native required check policy identity is invalid");return s}function sw(e){let t=Cr(e,"Native verification receipt");if(hi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==od)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=oI(r),a=$t(t.receiptHash,"Native verification receipt hash");if(j(G_,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function sd(e){return j(U_,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var dw=/^[a-f0-9]{64}$/u,xr=_i,A1=3*xr;function cd(e,t){let i=vt.relative(e,t);return i===""||!vt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${vt.sep}`)}function cI(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ps(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function cw(e){let t=await nt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await nt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function lI(e,t){let i=vt.resolve(e),r=vt.resolve(t);if(!cd(i,r))throw new Error("Native evidence path is outside its change");let n=[await cw(i)],a=i;for(let o of vt.relative(i,r).split(vt.sep).filter(Boolean)){a=vt.join(a,o);let s=await cw(a);if(!cd(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function lw(e){for(let t of e){let i=await nt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!cI(t,i)||await nt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function uI(e,t,i={}){let r=await lI(t,vt.dirname(e));await i.afterParentChainCaptured?.();let n=await nt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await nt.realpath(e);if(!cd(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await nt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),nt.lstat(e),nt.realpath(e)]);if(await lw(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!ps(s,n)||!ps(s,c))throw new Error("Native evidence document changed while opening");if(s.size>xr)throw new Error(`Native evidence document exceeds ${xr} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=xr+1-d,S=await o.read(f,0,Math.min(f.length,m),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>xr)throw new Error(`Native evidence document exceeds ${xr} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),nt.lstat(e),nt.realpath(e)]);if(await lw(r),!v.isFile()||v.isSymbolicLink()||h!==a||!ps(s,p)||!ps(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function fw(e,t){if(!dw.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function dI(e,t,i,r,n){if(!dw.test(i))throw new Error("Native report evidence hash is invalid");let a=await Ii({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||sI("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function Pr(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function fI(e,t,i,r,n){let a=fw(i,r);return n?vt.join(n,...a.split("/")):ei(U(e,t),a)}async function Ii(e){let t=fI(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??ue(e.paths,t);return await J(i,t),uI(t,i,e.hooks)}function uw(e,t){return ts(e,t)}function pI(e,t){let i=is(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function hI(e,t,i){let r=pg(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function mI(e,t,i){let r=$u(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function vI(e,t,i,r=!1,n){let a=await hs(e,t,i.implementationScopeRef,void 0,n);if(r&&await dI(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await pw(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Kn(e,t,i,r,n){let a=Pr(i,"scopes"),o=pI(await Ii({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Pr(o.baselineProjectionRef,"snapshots"),c=Pr(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Ii({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>uw(d,s)),Ii({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>uw(d,c))]);return og({baseline:l,current:u,scope:o})}async function hs(e,t,i,r,n){return(await Kn(e,t,i,r,n)).scope}async function pw(e,t,i,r,n){let a=Pr(i,"allowances");return hI(await Ii({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function Yn(e,t,i,r,n){let a=Pr(i,"receipts"),o=sw(await Ii({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Rr(e,t,i,r,n){let a=Pr(i,"verifications"),o=mI(await Ii({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await vI(e,t,o,!1,n),o}var gI=4096;async function wI(e,t=Ce.maxChanges){try{let i=await bn({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function hw(e,t){let i=await At(e,t),[r,n]=await Promise.all([i.implementation_scope?hs(e,t,i.implementation_scope):null,Pt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function ms(e,t,i={}){let n=(await wI(e,gI)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await hw(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await hw(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Qg([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{execFile as AI}from"node:child_process";import{promisify as _I}from"node:util";import{constants as ld,promises as Me}from"node:fs";import Ar from"node:path";var NI=/^[a-f0-9]{64}$/u,bI=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Xn=512*1024;function kI(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function vs(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function SI(e,t){let i=Ar.resolve(e),r=Ar.resolve(t);if(!V(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...Ar.relative(i,r).split(Ar.sep).filter(Boolean)]){o&&(a=Ar.join(a,o));let s=await Me.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Me.realpath(a);if(n.length>0&&!V(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function vw(e){for(let t of e){let i=await Me.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!kI(t,i)||await Me.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function EI(e){if(!NI.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function CI(e){let t=bI.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function xI(e,t,i){return ei(U(e,t),EI(i))}async function PI(e,t,i){let r=await SI(i,Ar.dirname(e)),n=await Me.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Xn)throw new Error(`Native check receipt exceeds ${Xn} bytes`);let[a,o]=await Promise.all([Me.realpath(t),Me.realpath(e)]);if(!V(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":ld.O_RDONLY|ld.O_NOFOLLOW|ld.O_NONBLOCK,c=await Me.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Me.lstat(e),Me.realpath(e)]);if(await vw(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!vs(n,l)||!vs(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=Xn+1-p,N=await c.read(v,0,Math.min(v.length,y),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,p>Xn)throw new Error(`Native check receipt exceeds ${Xn} bytes`);f.push(Buffer.from(v.subarray(0,N.bytesRead)))}let[h,m,S]=await Promise.all([c.stat(),Me.lstat(e),Me.realpath(e)]);if(await vw(r),!m.isFile()||m.isSymbolicLink()||S!==o||!V(a,S)||!vs(l,h)||!vs(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function gw(e,t,i){let r=CI(i),n=U(e,t),a=xI(e,t,r),o=ue(e,a);await J(o,a);let s=ow(await PI(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var Qn=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var kq=64*1024;var Sq=3600*1e3;var Eq=_I(AI);var II=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function ww(e,t){let i=[];for(let r of II){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function yw(e){if(e.receipt.kind!=="static-inspection")return null;let t=await gw(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var mi=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function TI(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function jI(e){let t=TI(e.bundle.baseline),i=await Gl(e.paths,t,{origin:"explicit",now:e.now});return _u({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function bw(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Kn(e.paths,e.state.name,e.state.implementation_scope),i=await mr({changeDir:pe(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await jI({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function kw(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await bw(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function $I(e){let t=await ne({root:pe(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Jh(t.text)}}function OI(e){let{receipt:t,implementationScope:i}=e,r=[],n=Au({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function HI(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:sd(e.implementationScope.scope.declaredArtifacts)}}async function Nw(e){let t=await Yn(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=ww(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new mi([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await yw({paths:e.paths,state:e.state,receipt:t});if(n){let a=OI({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function DI(e){let t=HI({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await Nw({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof mi)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await Nw({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof mi)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new mi(i)}function ud(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function dd(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:ud(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([bw(e),Rr(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:ud(e.state.verification_result,"stale"),envelope:null};let r=await $I({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await DI({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:ud(e.state.verification_result,"invalid"),envelope:null}}}function BI(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function Ew(e){try{return await LI.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function VI(e,t){try{return(await ne({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function FI(e,t,i){let r=zo(e,i.capability);if(!V(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=Sw.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await VI(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ne({root:pe(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function qI(e,t){return Ew(Wu(e,t))}async function fd(e){let t=e.now??new Date,i=await At(e.paths,e.name),r=await Pt(e.paths,e.name),n=await Ee(e.paths.projectRoot),a=BI(i.name,t),o=Sw.resolve(e.paths.nativeRoot,...a.split("/"));if(!V(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(v=>FI(e.paths,i.name,v))),dd({paths:e.paths,state:i,now:t}),ms(e.paths,i.name),Wo(e.paths,i.name),Xm(e.paths,i.name),qI(e.paths,i.name),Ew(o)]);return Jg({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}async function MI(e,t){let i=U(e,t.name),r=await pr(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Ho(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Pi(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function WI(e,t){let i=await MI(e,t);return{committed:i,latest:bg(i),history:Ng(i)}}async function Cw(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await WI(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var Ot=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function JI(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function GI(e){return(await Bv(e))?.change??null}function UI(e,t,i=!1,r){return cs({state:e,archiveReady:t,evidenceRetreat:i}).command}async function KI(e,t){let i=pe(e,t.name),r=[...(await ou(i,t.brief)).findings,...(await nv(e,t)).findings,...await Vv(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await _o(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Em(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await mr({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Ig(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await su(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function pd(e,t,i){let r=await GI(e)===t,n=await Sl(e,t),a=await Rn(e,t),o;try{let w=await nu(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=Ku({paths:e,state:o,findings:[w]}),O=cs({state:o,findings:C});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:Yu(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...i?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await Mg({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await Cw(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await mr({changeDir:pe(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let he=await Rr(e,o.name,o.verification_evidence);for(let Q of he.acceptanceTrace.entries)C.set(Q.acceptanceId,Q.status==="failed"?"failed":Q.status==="missing"?"missing":"satisfied")}let O=Mh({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),T=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...T?{nextPageCommand:JI(T),nextPageArgs:T}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await ms(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await Pt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let C=await An({paths:e,identity:w});C.state==="drifted"&&C.code&&f.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await Bo({paths:e,identity:w});f.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let w=await kw({paths:e,state:o});v=w.freshness!=="fresh",p.push(...w.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await fd({paths:e,name:o.name}),m.push(...h.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let S=[...await KI(e,o),...s.findings,...d,...f,...p,...l,...m].filter((w,C,O)=>O.findIndex(T=>T.code===w.code&&T.path===w.path)===C),y=Ku({paths:e,state:o,findings:S}),N=y.filter(w=>!hr(w.code)),k=o.phase==="archive"&&h?.ready===!0&&N.length===0,E=v||o.phase==="archive"&&(h?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=y.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),x=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",g=y.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:b||x?null:UI(o,k,E,i?.clarificationMode),archiveReady:k,inspection:s.inspection,findingSummary:Yu(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:cs({state:o,findings:y,archiveReady:k,evidenceRetreat:E,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:ds,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...g?{error:g.message}:{}}}async function xw(e){let t;try{t=await Hl({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await zI.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Ot.maxChanges))throw new Error(`Native status exceeds ${Ot.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}import tT from"node:path";function Ti(e,t,i){return e.language==="zh-CN"?i:t}function YI(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:Ti(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:Ti(e,"Reply A or B","回复 A 或 B"),agentInstruction:Ti(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 i(Ti(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(Ti(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return i(Ti(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 Pw(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Zn(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Rw(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function XI(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function QI(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function ZI(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 ji(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Pw({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Zn("summary","--summary"),Rw(e.name,e.flag)]}}function hd(e){return[ji({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),ji({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Aw(e,t){let i=QI(t)&&e.coordination_mode===void 0,r={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:YI(e,i)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...r,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"?{...r,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Zn("summary","--summary")],commandAlternatives:[ji({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...hd({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"?{...r,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Zn("summary","--summary")],commandAlternatives:[ji({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),ji({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"?{...r,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Zn("summary","--summary")],commandAlternatives:[ji({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...hd({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...r,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Zn("summary","--summary")],commandAlternatives:hd({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...r,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{...r,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?Pw({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{...r,disposition:i?"await-user":"continue",action:"confirm-shape",commandArgs:ZI({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[XI("coordination-mode","--coordination-mode",Gh)]:[],Rw("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...r,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{...r,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...r,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{...r,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...r,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{...r,userCommunication:!a&&o?{...r.userCommunication,agentInstruction:`${r.userCommunication.agentInstruction} ${Ti(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:r.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?{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[ji({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}function eT(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function _w(e){let t=e.acceptance.reduce((i,r)=>({...i,[r.result]:i[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:eT(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}function iT(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function rT(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function nT(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:sT(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:cT(r,i)}))]:[]]}function aT(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function Iw(e,t){let i=be(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:tT.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}function oT(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function gs(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function sT(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:gs(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function cT(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:gs(e.summary,t)??""}}async function md(e){let t=await Lv(e),i=_w(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await vu({paths:e.paths,state:t.state}),a=await Hn(e.paths,e.name),o=a?{...Iw(e.paths,t.state),projectRoot:"."}:Iw(e.paths,t.state),s=Aw(t.state,n),c=o.bindingState==="mismatch"?{...s,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...s.runnerAction,kind:"none"}}:s,l=a?oT(e.paths,a):[],u=a?(()=>{let p=a.children.filter(({status:N})=>N==="pending"||N==="ready").length,v=a.children.filter(({status:N})=>N==="active"||N==="verified").length,h=a.children.filter(({status:N})=>N==="integrated"||N==="archived").length,m=a.children.filter(({status:N})=>N==="blocked"||N==="needs-reverify").length,S=a.children.filter(({status:N})=>N==="active"||N==="blocked"||N==="needs-reverify").slice(0,16).map(N=>({name:N.name,summary:N.summary,projectRoot:N.task?.projectRoot??N.projectRoot?"<worktree>":null,reason:gs(N.blocker,l)})),y=a.children.flatMap(({blocker:N})=>{let k=gs(N,l);return k?[k]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:a.children.length,waiting:p,working:v,integrated:h,blocked:m,active:S,agents:{working:a.children.filter(({task:N})=>N!==null).length,completed:h},risks:y,nextAction:a.finalVerification.status==="passed"?"final-delivery":a.finalVerification.status==="pending"&&h===a.children.length?"parent-verification":p>0?"dispatch-ready-child":m>0?"resolve-blocker":"continue-supervisor"}})():null,d=e.details?(()=>{let p=a?.stateVersion??0,v=nT(t.state,a,l),h=rT(e.cursor,t.state.state_version,p),m=v.slice(h,h+32),S=h+m.length<v.length?iT(t.state.state_version,p,h+m.length):null;return{items:m,nextCursor:S,supervisorStateVersion:p}})():null,f=a?{schema:a.schema,parent:a.parent,integration:{branch:a.integration.branch,targetBranch:a.integration.targetBranch},finalVerification:{status:a.finalVerification.status,summary:a.finalVerification.summary},summary:u}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:aT(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:a?[]:i.blockers,workspace:o,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((p,v)=>({...p,[v.status]:(p[v.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},continuation:c,...e.details?{details:{stateVersion:t.state.state_version,...a?{supervisorStateVersion:d.supervisorStateVersion}:{},items:d.items,nextCursor:d.nextCursor,nextPageArgs:d.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",d.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}var uT=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function ws(e,t){let i=vi.normalize(vd(e)),r=vi.normalize(vd(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function vd(e){let t=vi.resolve(e);try{return lT.native(t)}catch{return t}}function dT(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function Tw(e){let t=[];for(let i of await xw(e))t.push({name:i,kind:await Nu(e,i)?"portable":"legacy"});return t}async function Hw(e){let t=vi.resolve(e),i=Dt(e),r=i.length>0?i:[t];r.some(o=>ws(o,t))||r.push(t);let n=[],a=new Set;for(let o of r.map(s=>vi.resolve(s)).sort()){let s=ws(o,t)?t:o,c=vd(s),l=process.platform==="win32"?c.toLowerCase():c;if(a.has(l))continue;a.add(l);let u=await Ee(s);if(!u)continue;let d=await kt(s,u.native.artifact_root);n.push({projectRoot:s,config:u,paths:d,changes:await Tw(d)})}if(n.length===0){let o=await Ee(e);if(!o)throw new Error(".comet/config.yaml was not found in any registered worktree");let s=await kt(e,o.native.artifact_root);n.push({projectRoot:vi.resolve(e),config:o,paths:s,changes:await Tw(s)})}return n}function jw(e,t){return e.workspace.bindingState==="aligned"?0:ws(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function Dw(e,t){let i=new Map;for(let n of t)for(let a of n.changes)i.set(a.name,[...i.get(a.name)??[],{source:n,kind:a.kind}]);let r=[];for(let[n,a]of[...i.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:c,kind:l})=>{if(l==="portable")try{let u=await md({paths:c.paths,name:n});return{source:c,name:n,kind:l,workspace:u.workspace,portableStatus:u,inspectionError:null}}catch(u){return{source:c,name:n,kind:l,workspace:await Rn(c.paths,n),portableStatus:null,inspectionError:u instanceof Error?u.message:String(u)}}return{source:c,name:n,kind:l,workspace:await Rn(c.paths,n),portableStatus:null,inspectionError:null}}));o.sort((c,l)=>jw(c,e)-jw(l,e)||c.source.projectRoot.localeCompare(l.source.projectRoot));let s=o.filter(c=>c.workspace.bindingState==="aligned");s.length>1?r.push(...s):r.push(s[0]??o[0])}if(r.length>Ot.maxChanges)throw new Error(`Native status discovery exceeds ${Ot.maxChanges} visible changes`);return r.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function $w(e,t){let i=t.toString(36),r=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${i}.${r}`}function fT(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=uT.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let r=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:i});if(t[3]!==r)throw new Error("Native workspace status cursor integrity failed");return i}function Ow(e,t){let i=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:i?dT(i):null,nextPageArgs:i}}async function pT(e,t,i){let r=null;try{r=await Zm(e.source.paths,e.name)}catch{}return r?.state?{schema:"comet.native.status.v2",name:e.name,phase:r.state.phase,status:"blocked",migrationRequired:!0,legacySchema:r.schema,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:r.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:pd(e.source.paths,e.name,{details:t,...i?{acceptanceCursor:i}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function Lw(e,t,i,r){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(i)throw new Error("Portable Native status includes the complete acceptance list");return!t&&e.portableStatus?e.portableStatus:md({paths:e.source.paths,name:e.name,details:t,...r?{cursor:r}:{}})}return pT(e,t,i)}async function Bw(e){let t=await Hw(e.projectRoot),i=(await Dw(e.projectRoot,t)).filter(r=>r.name===e.name);if(i.length===0){let r=t.find(n=>ws(n.projectRoot,e.projectRoot))??t[0];return pd(r.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:r.config.native.clarification_mode,maxVerifyFailures:r.config.native.max_verify_failures})}if(i.length>1)throw new Error(`Native change ${e.name} has multiple aligned workspace bindings: ${i.map(r=>r.source.projectRoot).join(", ")}`);return Lw(i[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function Vw(e){let t=await Hw(e.projectRoot),i=await Dw(e.projectRoot,t),r=j("comet.native.workspace-status-candidates.v1",i.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=fT({candidatesHash:r,total:i.length,cursor:e.cursor}),a=await Promise.all(i.slice(n,n+Ot.maxItems).map(u=>Lw(u,!1))),o=[],s=i.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],f=n+d.length,p=f<i.length?$w(r,f):null,v={schema:s,total:i.length,offset:n,items:d,nextCursor:p,...Ow(vi.resolve(e.projectRoot),p),limits:{...Ot}};if(Buffer.byteLength(JSON.stringify(v),"utf8")>Ot.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<i.length?$w(r,c):null;return{schema:s,total:i.length,offset:n,items:o,nextCursor:l,...Ow(vi.resolve(e.projectRoot),l),limits:{...Ot}}}import ea from"path";import{realpathSync as IT}from"fs";var Ht={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Fw(e){return e?e.command?`${Ht.next} ${e.command}`:e.ask_user?`${Ht.next} ${e.ask_user}`:null:null}function qw(e,t){let i=[e.summary],r=Fw(e.next);return r&&i.push(r),e.user_message&&i.push("",Ht.relay,e.user_message),t!==void 0&&i.push("",Ht.details,JSON.stringify(t,null,2)),`${i.join(`
|
|
173
173
|
`)}
|
|
174
174
|
`}function Mw(e,t,i){let r=[e.summary],n=Fw(e.next);return n&&r.push(n),e.user_message&&r.push("",Ht.relay,e.user_message),r.push("",`${Ht.detail} ${t}`),i!==void 0&&r.push("",Ht.details,JSON.stringify(i,null,2)),r.join(`
|
|
175
|
-
`)}var
|
|
176
|
-
`)}}let i=t.continuation;if(Jw(i))return
|
|
177
|
-
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
|
|
178
|
-
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
|
|
175
|
+
`)}var vW={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var PW=16*1024*1024,RW=256*1024,AW=16*1024;var OW=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var b2=16*1024*1024,ys=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Ns=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function B(e,t,i){return e==="zh-CN"?i:t}var gd={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Ww(e,t){return typeof e=="string"&&gd[e]?B(t,gd[e].en,gd[e].zh):typeof e=="string"?e:""}function wd(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 gT(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let i of e){if(!i||typeof i!="object")return null;let r=i.result;if(r!=="passed"&&r!=="failed"&&r!=="blocked"&&r!=="pending")return null;t[r]+=1}return t}function zw(e,t){let i=[];e.failed>0&&i.push(B(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&i.push(B(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&i.push(B(t,`${e.pending} pending`,`${e.pending} 项待验`));let r=B(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return i.length>0?`${r} (${i.join(", ")})`:r}function Jw(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let i=t.userCommunication;return!!(i&&typeof i=="object"&&typeof i.required=="boolean"&&(i.message===null||typeof i.message=="string")&&typeof i.agentInstruction=="string")}function yd(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function wT(e,t,i){return e==="done"?B(i,"complete","已完成"):e==="await-user"?B(i,"waiting for a user decision","等待用户决定"):e==="blocked"?B(i,"paused: needs attention","已暂停,需要处理"):t?B(i,"waiting for a user decision","等待用户决定"):B(i,"ready to continue","可继续推进")}function yT(e,t,i){let r=yd(e),n=[];i&&n.push(i);let a=B(r,`Change ${e.change}`,`需求 ${e.change}`),o=Ww(e.phase,r),s=wT(e.disposition,e.userCommunication.required,r);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(zw(t,r));let c=e.userCommunication,l=Gw(e,r);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Gw(e,t){let i=e.userCommunication;if(e.disposition==="await-user"&&i.required)return{ask_user:B(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:B(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:B(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function NT(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function bT(e,t){let i=typeof e.name=="string"?e.name:"(unnamed)",r=Ww(e.phase,t),n=e.status==="await-user"?B(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?B(t,"paused","已暂停"):e.status==="done"?B(t,"complete","已完成"):B(t,"in progress","进行中"),a=wd(e.acceptance)?`${B(t,", ",",")}${zw(e.acceptance,t)}`:"";return` ${i} · ${r||String(e.phase??"?")} · ${n}${a}`}function kT(e){for(let t of e){let i=t.continuation;if(i?.userCommunication&&typeof i.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(i.userCommunication.agentInstruction))return"zh-CN"}return"en"}function ST(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 ET(e){if(e.healthy){let r=e.repaired?B("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):B("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=CT(e.continuation);return n?{summary:r,next:n}:{summary:r}}let i=Array.isArray(e.findings)?e.findings.length:0;return{summary:B("en",i>0?`Diagnostics found ${i} problem${i===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",i>0?`诊断发现 ${i} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:B("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function CT(e){return Jw(e)?Gw(e,yd(e)):void 0}function Uw(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(ST(t))return ET(t);if(NT(t)){let r=kT(t.items);return{summary:[t.total===t.items.length?B(r,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):B(r,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>bT(a,r))].join(`
|
|
176
|
+
`)}}let i=t.continuation;if(Jw(i))return yT(i,xT(t),PT(t,yd(i)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let r=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:B(r,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function xT(e){if(wd(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t;if(wd(i.acceptance))return i.acceptance;if(Array.isArray(i.acceptance))return gT(i.acceptance)}return null}function PT(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return B(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let i=e.migration;return i&&typeof i=="object"&&i.completed===!0?B(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Kw(e){let i=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:B("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof i.change=="string"?{next:{command:`comet native status ${i.change} --json`}}:{}};case"baseline-incomplete":return{summary:B("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:B("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:B("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:B("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:B("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:B("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:B("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:B("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var Yw=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],bd=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:Yw,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>]
|
|
177
|
+
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]
|
|
178
|
+
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 Nd(e,t){return`${e}:
|
|
179
179
|
${t.map(i=>` ${i}`).join(`
|
|
180
|
-
`)}`}function
|
|
181
|
-
${i.output}`),i.examples&&r.push("",
|
|
180
|
+
`)}`}function RT(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return bd[i]||t.length>1&&bd[t[0]]?.subcommands?i:t[0]}function AT(e=[]){let t=RT(e),i=bd[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Nd("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...Yw];return n&&n.length>0&&r.push("",Nd("Options",n)),r.push("",`Output:
|
|
181
|
+
${i.output}`),i.examples&&r.push("",Nd("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
|
|
182
182
|
`)}
|
|
183
|
-
`}}var AT
|
|
184
|
-
`}function ty(e,t,i){return{command:e,exitCode:0,data:t,text:i??ey(t)}}function
|
|
183
|
+
`}}var _T=AT().usage;var F2=10*1024*1024,gt=class extends Error{};function ta(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new gt(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function bs(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new gt(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new gt(`${t} requires a value`);return e.splice(r,2),n}function Qw(e){if(e.length>0)throw new gt(`Unexpected argument: ${e[0]}`)}function kd(e,t){let i=ea.normalize(Xw(e)),r=ea.normalize(Xw(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Xw(e){let t=ea.resolve(e);try{return IT.native(t)}catch{return t}}function TT(e){let t=ea.resolve(e),i=be(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=be(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!kd(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||kd(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:kd(process.cwd(),i.currentWorktreeRoot)?ea.resolve(process.cwd()):i.currentWorktreeRoot}async function Zw(e){return e?TT(e):bl(process.cwd())}function ey(e){return JSON.stringify(e,null,2)+`
|
|
184
|
+
`}function ty(e,t,i){return{command:e,exitCode:0,data:t,text:i??ey(t)}}function jT(e,t){if(t instanceof gt)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof ys)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 Ns)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Fo)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof _n)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof Uo)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof qo)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof mi)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Qn)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function iy(e,t){let i=jT(e,t),r=i.error;if(!r)return i;let n=Kw({code:r.code,message:r.message,data:i.data});return n?{...i,envelope:n}:i}function ry(e,t,i=!1){let r=e.envelope??Uw(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...r===void 0?{}:{summary:r.summary,...r.next===void 0?{}:{next:r.next},...r.user_message===void 0?{}:{user_message:r.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
185
185
|
`}:e.error?{exitCode:e.exitCode,stderr:r?Mw(r,e.error.message,i?e.data:void 0):e.error.message}:r?{exitCode:e.exitCode,stdout:qw(r,i?e.data:void 0)}:i&&e.text!==void 0&&e.data!==void 0&&e.text!==ey(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
186
186
|
${Ht.details}
|
|
187
187
|
${JSON.stringify(e.data,null,2)}
|
|
188
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}async function ny(e,t){let i=
|
|
188
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}async function ny(e,t){let i=ta(e,"--details"),r=bs(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(i&&!n)throw new gt("status --details requires a change name");if(r&&n&&!i)throw new gt("--cursor for a named status requires --details");Qw(e);let a=n?await Bw({projectRoot:t,name:n,details:i,...r?{detailsCursor:r}:{}}):await Vw({projectRoot:t,...r?{cursor:r}:{}});return ty("status",a)}async function ay(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{ta(n,"--json"),ta(n,"--verbose"),c=bs(n,"--project-root");let d=[...n,...a],f=await Zw(c);l=await t(d,f)}catch(d){l=iy(e,d)}let u=ry(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
189
189
|
`)?"":`
|
|
190
190
|
`)),u.exitCode}process.exitCode=await ay("status",ny);
|