@rpamis/comet 0.4.4 → 0.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -1
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +97 -94
- package/assets/skills/comet/scripts/comet-guard.mjs +131 -131
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +91 -91
- package/assets/skills/comet/scripts/comet-hook-router.mjs +202 -193
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +82 -82
- package/assets/skills/comet/scripts/comet-runtime.mjs +287 -285
- package/assets/skills/comet/scripts/comet-state.mjs +199 -198
- package/assets/skills/comet-archive/SKILL.md +9 -5
- package/assets/skills/comet-native/reference/artifacts.md +44 -0
- package/assets/skills/comet-native/reference/clarification.md +1 -1
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +199 -192
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +173 -166
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +150 -143
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +103 -99
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +209 -205
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +180 -173
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +106 -102
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +182 -175
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +124 -117
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +99 -95
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +143 -136
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +120 -113
- package/assets/skills-zh/comet-archive/SKILL.md +9 -5
- package/assets/skills-zh/comet-native/reference/artifacts.md +44 -0
- package/assets/skills-zh/comet-native/reference/clarification.md +1 -1
- package/dist/app/cli/index.js +1 -0
- package/dist/app/cli/index.js.map +1 -1
- package/dist/app/commands/doctor.d.ts.map +1 -1
- package/dist/app/commands/doctor.js +17 -10
- package/dist/app/commands/doctor.js.map +1 -1
- package/dist/app/commands/i18n.d.ts +1 -1
- package/dist/app/commands/i18n.d.ts.map +1 -1
- package/dist/app/commands/i18n.js +4 -0
- package/dist/app/commands/i18n.js.map +1 -1
- package/dist/app/commands/project-knowledge.d.ts +2 -0
- package/dist/app/commands/project-knowledge.d.ts.map +1 -1
- package/dist/app/commands/project-knowledge.js +64 -7
- package/dist/app/commands/project-knowledge.js.map +1 -1
- package/dist/app/commands/uninstall.d.ts +1 -0
- package/dist/app/commands/uninstall.d.ts.map +1 -1
- package/dist/app/commands/uninstall.js +65 -10
- package/dist/app/commands/uninstall.js.map +1 -1
- package/dist/domains/agent-learning/coordinator.d.ts +8 -1
- package/dist/domains/agent-learning/coordinator.d.ts.map +1 -1
- package/dist/domains/agent-learning/coordinator.js +58 -0
- package/dist/domains/agent-learning/coordinator.js.map +1 -1
- package/dist/domains/agent-learning/experience-journal.d.ts +21 -1
- package/dist/domains/agent-learning/experience-journal.d.ts.map +1 -1
- package/dist/domains/agent-learning/experience-journal.js +190 -11
- package/dist/domains/agent-learning/experience-journal.js.map +1 -1
- package/dist/domains/bundle/bundle-platform.d.ts.map +1 -1
- package/dist/domains/bundle/bundle-platform.js +6 -1
- package/dist/domains/bundle/bundle-platform.js.map +1 -1
- package/dist/domains/comet-classic/classic-archive.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-archive.js +5 -1
- package/dist/domains/comet-classic/classic-archive.js.map +1 -1
- package/dist/domains/comet-classic/classic-design-readiness.d.ts +1 -1
- package/dist/domains/comet-classic/classic-progress.d.ts +60 -2
- package/dist/domains/comet-classic/classic-progress.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-progress.js +199 -22
- package/dist/domains/comet-classic/classic-progress.js.map +1 -1
- package/dist/domains/comet-classic/classic-recovery.d.ts +20 -1
- package/dist/domains/comet-classic/classic-recovery.d.ts.map +1 -1
- package/dist/domains/comet-native/native-artifact-language.d.ts +7 -0
- package/dist/domains/comet-native/native-artifact-language.d.ts.map +1 -1
- package/dist/domains/comet-native/native-artifact-language.js +61 -1
- package/dist/domains/comet-native/native-artifact-language.js.map +1 -1
- package/dist/domains/comet-native/native-artifacts.d.ts +2 -0
- package/dist/domains/comet-native/native-artifacts.d.ts.map +1 -1
- package/dist/domains/comet-native/native-artifacts.js +116 -19
- package/dist/domains/comet-native/native-artifacts.js.map +1 -1
- package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
- package/dist/domains/comet-native/native-hook-guard.js +3 -2
- package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
- package/dist/domains/comet-native/native-portable-requirements.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-requirements.js +12 -5
- package/dist/domains/comet-native/native-portable-requirements.js.map +1 -1
- package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-state.js +4 -2
- package/dist/domains/comet-native/native-portable-state.js.map +1 -1
- package/dist/domains/comet-native/native-portable-types.d.ts +1 -1
- package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
- package/dist/domains/comet-plugin/integration.d.ts +1 -0
- package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
- package/dist/domains/comet-plugin/integration.js +20 -10
- package/dist/domains/comet-plugin/integration.js.map +1 -1
- package/dist/domains/comet-plugin/plugin-runtime.d.ts +8 -2
- package/dist/domains/comet-plugin/plugin-runtime.d.ts.map +1 -1
- package/dist/domains/comet-plugin/plugin-runtime.js +18 -4
- package/dist/domains/comet-plugin/plugin-runtime.js.map +1 -1
- package/dist/domains/dashboard/project-directory.d.ts +4 -0
- package/dist/domains/dashboard/project-directory.d.ts.map +1 -1
- package/dist/domains/dashboard/project-directory.js +30 -2
- package/dist/domains/dashboard/project-directory.js.map +1 -1
- package/dist/domains/dashboard/server.d.ts.map +1 -1
- package/dist/domains/dashboard/server.js +28 -3
- package/dist/domains/dashboard/server.js.map +1 -1
- package/dist/domains/dashboard/web/assets/{abnfDiagram-VCTEODGH-CFEU4PQU.js → abnfDiagram-VCTEODGH-m9_t3fwH.js} +1 -1
- package/dist/domains/dashboard/web/assets/{arc-BeYYJor9.js → arc-CDiwRrMg.js} +1 -1
- package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-ypJOsR2Y.js +1 -0
- package/dist/domains/dashboard/web/assets/{architectureDiagram-5GKGNRK7-CqTy4fyH.js → architectureDiagram-5GKGNRK7-Xwj-hlQB.js} +1 -1
- package/dist/domains/dashboard/web/assets/{blockDiagram-I7D4REHJ-SR_5S4SA.js → blockDiagram-I7D4REHJ-Cme6qNK_.js} +1 -1
- package/dist/domains/dashboard/web/assets/{c4Diagram-7LVT6UL2-DzphG2XS.js → c4Diagram-7LVT6UL2-Cxs1dU7y.js} +1 -1
- package/dist/domains/dashboard/web/assets/channel-BFTjR7Ng.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-4HAMMTFA-BpthUtIs.js → chunk-4HAMMTFA-DBQykIWE.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-75Z2AOVW-CxAdhPhG.js → chunk-75Z2AOVW-Dh-E6TAx.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-DU6HZSFF-5peVNfxp.js → chunk-DU6HZSFF-W3lPaoVP.js} +2 -2
- package/dist/domains/dashboard/web/assets/{chunk-F27PBJKO-CwG4xi2V.js → chunk-F27PBJKO-dzf1fpYi.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-GMAD6QVW-BuFFY783.js → chunk-GMAD6QVW-CeuSGVHV.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-GVQU2GXP-OyUFmjE-.js → chunk-GVQU2GXP-BrGrIBgk.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-IMKFNOWR-DmTme45C.js → chunk-IMKFNOWR-DXiTC1Xo.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-L3NEJ4N5-D6BHbKty.js → chunk-L3NEJ4N5-DnyD3Ocj.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-OSK3NFVY-CCz1v1Nv.js → chunk-OSK3NFVY-6vxhPm51.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-P2QGCYS3-C1_7kDYS.js → chunk-P2QGCYS3-DChNsVqO.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-POPQ4Y6H-buFKlAdG.js → chunk-POPQ4Y6H-RBgha6dE.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-PWAF6VOD-B_K6Jrsv.js → chunk-PWAF6VOD-CayoKmnh.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-SHT3W25Y-CRRLsXmS.js → chunk-SHT3W25Y-sOkLJZoB.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-SVP7TREG-Q5zCQTul.js → chunk-SVP7TREG-j0QRwmsq.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-TICWLB2K-Zc5XaO5Z.js → chunk-TICWLB2K-D7Re_d_T.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-BAIB2h_r.js → chunk-XXDRQBXY-BFV70fKF.js} +1 -1
- package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-gDSLbV2K.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-gDSLbV2K.js +1 -0
- package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-C7jkFYhm.js → cose-bilkent-JH36ORCC-k7gqx2Br.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefin-OW5HDTMX-4yS-l7kx.js → cynefin-OW5HDTMX-CWI6FZT8.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefinDiagram-5FMLGOSQ-DAkfQ8jW.js → cynefinDiagram-5FMLGOSQ-D-O3RrOu.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dagre-GXQ25YYZ-D3b16ruz.js → dagre-GXQ25YYZ-BR1jxWfn.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-S7CK7UJ4-BXZHtdNz.js → diagram-S7CK7UJ4-B6gXFYBj.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-UQ7AKVKN-B4nIzofw.js → diagram-UQ7AKVKN-BBW6aRk8.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-VSXAHHWV-B6d7KNj1.js → diagram-VSXAHHWV-BC0CZeyH.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-VX7I27RA-CHr0Rg8a.js → diagram-VX7I27RA-BmwBIkwS.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-Z3DM3KII-BO2IxR9N.js → diagram-Z3DM3KII-DTZgX9SF.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dist-0wyW4qbm.js → dist-brXLwleg.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ebnfDiagram-PWID7BFC-CHRK8Hyg.js → ebnfDiagram-PWID7BFC-CsMXo0C6.js} +1 -1
- package/dist/domains/dashboard/web/assets/{erDiagram-RLTQ6QDP-_HFHzZlc.js → erDiagram-RLTQ6QDP-DQ9ewX94.js} +1 -1
- package/dist/domains/dashboard/web/assets/{es-kjndkyYX.js → es-CgcAhzLf.js} +1 -1
- package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-Ll12Q19y.js +1 -0
- package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-Bf2-9XUn.js +1 -0
- package/dist/domains/dashboard/web/assets/{ganttDiagram-EL5Y4UJY-CxhSw1PI.js → ganttDiagram-EL5Y4UJY-DIFkXe6G.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraph-4MIJSDKK-Cbw-3Dnk.js → gitGraph-4MIJSDKK-BHY8ZnpE.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraphDiagram-WWUBYQGX-Cx93hwtL.js → gitGraphDiagram-WWUBYQGX-cBn9dMzs.js} +1 -1
- package/dist/domains/dashboard/web/assets/{index-CQb8j5OE.js → index-C_6nf1Fw.js} +2 -2
- package/dist/domains/dashboard/web/assets/{info-A6RAGUB7--d4EMiIK.js → info-A6RAGUB7-DtUaS9jN.js} +1 -1
- package/dist/domains/dashboard/web/assets/{infoDiagram-27XIBGKW-DMkRRNGB.js → infoDiagram-27XIBGKW-CIl0e_EN.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ishikawaDiagram-5VMMS53U-CjKh_jHT.js → ishikawaDiagram-5VMMS53U-DAdtPZ_c.js} +1 -1
- package/dist/domains/dashboard/web/assets/{journeyDiagram-3NMN7TZE-CG735M_M.js → journeyDiagram-3NMN7TZE-CBokRgde.js} +1 -1
- package/dist/domains/dashboard/web/assets/{kanban-definition-UXKFOSKX-CgXFmhFM.js → kanban-definition-UXKFOSKX-DrqCYJ-7.js} +1 -1
- package/dist/domains/dashboard/web/assets/katex-D29apahB.js +257 -0
- package/dist/domains/dashboard/web/assets/{line-Bhf8l3gG.js → line-BDlVqlh4.js} +1 -1
- package/dist/domains/dashboard/web/assets/{linear-YWT9mnmu.js → linear-DTAzui9x.js} +1 -1
- package/dist/domains/dashboard/web/assets/{mermaid-parser.core-COzQ1kq0.js → mermaid-parser.core-CFw-xbYY.js} +3 -3
- package/dist/domains/dashboard/web/assets/{mermaid.core-Cc1lMpx-.js → mermaid.core-Ck7fB8UD.js} +4 -4
- package/dist/domains/dashboard/web/assets/{mindmap-definition-YA3MSWOX-B_VOgUSO.js → mindmap-definition-YA3MSWOX-C7kb9KL9.js} +1 -1
- package/dist/domains/dashboard/web/assets/{packet-AYTQ26CC-CXbJLNC9.js → packet-AYTQ26CC-P8Mtt0tp.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pegDiagram-XKGWAZYB-BuS0hioo.js → pegDiagram-XKGWAZYB-DUDD9qv5.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pie-WAS4IAKB-BEaGwdWZ.js → pie-WAS4IAKB-dEmLxiDR.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pieDiagram-E7YTZNPT-DDzYv-_9.js → pieDiagram-E7YTZNPT-BUssAcqk.js} +1 -1
- package/dist/domains/dashboard/web/assets/{quadrantDiagram-AXDQQJYC-DExT--Ut.js → quadrantDiagram-AXDQQJYC-BzaAWdQL.js} +1 -1
- package/dist/domains/dashboard/web/assets/{radar-RG4KPBEZ-C1JtzGr8.js → radar-RG4KPBEZ-mqtvaz9w.js} +1 -1
- package/dist/domains/dashboard/web/assets/{railroad-74A4TZTK-CMpkXATR.js → railroad-74A4TZTK-7tTnGpoz.js} +1 -1
- package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CpJvyBJM.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-BJ5g77l6.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-BslCK-Gr.js +1 -0
- package/dist/domains/dashboard/web/assets/{railroadDiagram-O6MQD6OU-BCE65sLR.js → railroadDiagram-O6MQD6OU-DM1AKXm0.js} +1 -1
- package/dist/domains/dashboard/web/assets/{requirementDiagram-BXWQKSXE-CmyX3vGG.js → requirementDiagram-BXWQKSXE--H5KiPSc.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sankeyDiagram-P5KCCOFB-BFKrX2dv.js → sankeyDiagram-P5KCCOFB-JweUq_u2.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sequenceDiagram-WJ2MYXX4-DqodS9W-.js → sequenceDiagram-WJ2MYXX4-pxb1iTGb.js} +1 -1
- package/dist/domains/dashboard/web/assets/{src-BVUP3QzK.js → src-joFOxopw.js} +1 -1
- package/dist/domains/dashboard/web/assets/{stateDiagram-D77RDMKH-nHai_EZh.js → stateDiagram-D77RDMKH-CDu5crd8.js} +1 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-wV5AqWaM.js +1 -0
- package/dist/domains/dashboard/web/assets/{swimlanes-42K2YHIH-BODBARYN.js → swimlanes-42K2YHIH-ioSqowJ4.js} +1 -1
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-DOPLn-V5.js +8 -0
- package/dist/domains/dashboard/web/assets/{timeline-definition-24CTP7MA-RVnG8rgK.js → timeline-definition-24CTP7MA-2YXSYkS3.js} +1 -1
- package/dist/domains/dashboard/web/assets/{treeView-Q6P3EWNA-B6lrg3KQ.js → treeView-Q6P3EWNA-DEGims38.js} +1 -1
- package/dist/domains/dashboard/web/assets/{treemap-WGGIJYW6-CJfMKVf4.js → treemap-WGGIJYW6-CJvBhTlR.js} +1 -1
- package/dist/domains/dashboard/web/assets/{vennDiagram-4TSXK5OY-CZMWJiN7.js → vennDiagram-4TSXK5OY-CHdNWhBK.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardley-WFR3VGLG-BoUsbNlx.js → wardley-WFR3VGLG-CVO9PCjo.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardleyDiagram-VM6X3IG4-BwBCykVb.js → wardleyDiagram-VM6X3IG4-RToPmij6.js} +1 -1
- package/dist/domains/dashboard/web/assets/{xychartDiagram-S5SC5T6Z-vutnbx57.js → xychartDiagram-S5SC5T6Z-DaWHnpHE.js} +1 -1
- package/dist/domains/dashboard/web/index.html +1 -1
- package/dist/domains/project-knowledge/host-review.d.ts +15 -2
- package/dist/domains/project-knowledge/host-review.d.ts.map +1 -1
- package/dist/domains/project-knowledge/host-review.js +65 -25
- package/dist/domains/project-knowledge/host-review.js.map +1 -1
- package/dist/domains/project-knowledge/index.d.ts +1 -0
- package/dist/domains/project-knowledge/index.d.ts.map +1 -1
- package/dist/domains/project-knowledge/index.js +1 -0
- package/dist/domains/project-knowledge/index.js.map +1 -1
- package/dist/domains/project-knowledge/learning.d.ts +2 -1
- package/dist/domains/project-knowledge/learning.d.ts.map +1 -1
- package/dist/domains/project-knowledge/learning.js +6 -0
- package/dist/domains/project-knowledge/learning.js.map +1 -1
- package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
- package/dist/domains/project-knowledge/plugin.js +3 -1
- package/dist/domains/project-knowledge/plugin.js.map +1 -1
- package/dist/domains/skill/dsh-adapter.d.ts +5 -1
- package/dist/domains/skill/dsh-adapter.d.ts.map +1 -1
- package/dist/domains/skill/dsh-adapter.js +222 -87
- package/dist/domains/skill/dsh-adapter.js.map +1 -1
- package/dist/domains/skill/platform-inspect.d.ts +1 -0
- package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
- package/dist/domains/skill/platform-inspect.js +8 -4
- package/dist/domains/skill/platform-inspect.js.map +1 -1
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +7 -7
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/platform/fs/file-system.d.ts +2 -0
- package/dist/platform/fs/file-system.d.ts.map +1 -1
- package/dist/platform/fs/file-system.js +11 -0
- package/dist/platform/fs/file-system.js.map +1 -1
- package/dist/platform/install/dsh-profiles.d.ts +3 -0
- package/dist/platform/install/dsh-profiles.d.ts.map +1 -0
- package/dist/platform/install/dsh-profiles.js +40 -0
- package/dist/platform/install/dsh-profiles.js.map +1 -0
- package/dist/platform/install/platforms.d.ts.map +1 -1
- package/dist/platform/install/platforms.js +1 -0
- package/dist/platform/install/platforms.js.map +1 -1
- package/dist/platform/install/project-registry.d.ts +7 -1
- package/dist/platform/install/project-registry.d.ts.map +1 -1
- package/dist/platform/install/project-registry.js +49 -5
- package/dist/platform/install/project-registry.js.map +1 -1
- package/dist/platform/paths/project-worktree-root.d.ts +3 -0
- package/dist/platform/paths/project-worktree-root.d.ts.map +1 -0
- package/dist/platform/paths/project-worktree-root.js +14 -0
- package/dist/platform/paths/project-worktree-root.js.map +1 -0
- package/dist/platform/process/hook-adapter.d.ts.map +1 -1
- package/dist/platform/process/hook-adapter.js +13 -0
- package/dist/platform/process/hook-adapter.js.map +1 -1
- package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +11 -3
- package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +11 -3
- package/eval/local/tests/scaffold/test_task_resolution.py +6 -2
- package/package.json +14 -8
- package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-YphM8Wtg.js +0 -1
- package/dist/domains/dashboard/web/assets/channel-BkwcGbYR.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-DzpQhyL3.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-DzpQhyL3.js +0 -1
- package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-CG-cVTEg.js +0 -1
- package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-C3RaJz-z.js +0 -1
- package/dist/domains/dashboard/web/assets/katex-CXMH3UgJ.js +0 -257
- package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-BM35gYWg.js +0 -1
- package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-CN60GGp0.js +0 -1
- package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-DRUSW4g7.js +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-BL6vE1m9.js +0 -1
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-XHK_nuTj.js +0 -8
|
@@ -1,78 +1,78 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
${
|
|
6
|
-
`)}};
|
|
7
|
-
`)
|
|
4
|
+
var KE=Object.create;var Nu=Object.defineProperty;var YE=Object.getOwnPropertyDescriptor;var XE=Object.getOwnPropertyNames;var QE=Object.getPrototypeOf,ZE=Object.prototype.hasOwnProperty;var os=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var I=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},ex=(e,t)=>{for(var r in t)Nu(e,r,{get:t[r],enumerable:!0})},tx=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of XE(t))!ZE.call(e,n)&&n!==r&&Nu(e,n,{get:()=>t[n],enumerable:!(i=YE(t,n))||i.enumerable});return e};var ir=(e,t,r)=>(r=e!=null?KE(QE(e)):{},tx(t||!e||!e.__esModule?Nu(r,"default",{value:e,enumerable:!0}):r,e));import{AsyncLocalStorage as rx}from"node:async_hooks";import{performance as ss}from"node:perf_hooks";function cs(e=0){ix+=1,nx+=e;let t=ax.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function Zn(e){let t=ss.now();try{return e()}finally{cs(ss.now()-t)}}async function bu(e){let t=ss.now();try{return await e()}finally{cs(ss.now()-t)}}var ix,nx,ax,Ji=I(()=>{"use strict";ix=0,nx=0,ax=new rx});import{existsSync as ox}from"node:fs";import ea from"node:path";function Am(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function cx(e){let t=(Am(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function lx(e,t,r){let n=ea.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Am(t,"PATH")??"").split(ea.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=ea.win32.extname(e)?[e]:cx(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?ea.join(s,c):ea.resolve(r,c)))}function ls(e,t,r){return lx(e,t,r).find(i=>ox(i))??e}function ku(e){if(e.some(t=>sx.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var sx,EL,ta=I(()=>{"use strict";sx=/[&|<>()^%"!\r\n]/u,EL=["$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("; ")});import{execFile as ux,execFileSync as RL}from"node:child_process";import Im from"node:path";async function Er(e,t,r={}){let i=r.timeoutMs??dx,n=r.maxBufferBytes??px;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(n)||n<1)throw new Error("External command limits must be positive integers");let a=Im.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?ls(e,o,a):e,c=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);c&&ku(t);let l=()=>new Promise((u,d)=>{let p=!1,f=ux(s,[...t],{cwd:a,env:o,encoding:"utf8",maxBuffer:n,windowsHide:!0,shell:c},(g,b,k)=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),g?d(new ra(e,t,k.trim(),{cause:g,timedOut:fx(g)})):u(b))}),m=g=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),f.kill("SIGKILL"),f.stdin?.destroy(),f.stdout?.destroy(),f.stderr?.destroy(),f.unref(),d(new ra(e,t,"",{timedOut:g})))},h=()=>m(!1),v=setTimeout(()=>m(!0),i);r.signal?.addEventListener("abort",h,{once:!0}),r.signal?.aborted&&h(),f.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(Im.win32.basename(e))?bu(l):l()}function fx(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}var dx,px,ra,Ui=I(()=>{"use strict";Ji();ta();dx=6e4,px=8*1024*1024;ra=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});import{createHash as wx}from"crypto";function wt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function yx(e,t){t.has(e)&&wt("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||wt("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&wt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&wt("symbol properties are not supported"),`[${e.map(i=>Su(i,t)).join(",")}]`}finally{t.delete(e)}}function Nx(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&wt("only plain objects are supported"),t.has(e)&&wt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&wt("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&wt("accessor properties are not supported"),`${JSON.stringify(o)}:${Su(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Su(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)||wt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?yx(e,t):Nx(e,t);case"bigint":case"function":case"symbol":case"undefined":return wt(`${typeof e} values are not supported`)}return wt("unsupported value type")}function oa(e){return Su(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 wx("sha256").update(`${e}
|
|
5
|
+
${oa(t)}`).digest("hex")}var de=I(()=>{"use strict"});var z=R(Ee=>{"use strict";var Eu=Symbol.for("yaml.alias"),Hm=Symbol.for("yaml.document"),ds=Symbol.for("yaml.map"),Dm=Symbol.for("yaml.pair"),xu=Symbol.for("yaml.scalar"),ps=Symbol.for("yaml.seq"),ar=Symbol.for("yaml.node.type"),bx=e=>!!e&&typeof e=="object"&&e[ar]===Eu,kx=e=>!!e&&typeof e=="object"&&e[ar]===Hm,Sx=e=>!!e&&typeof e=="object"&&e[ar]===ds,Ex=e=>!!e&&typeof e=="object"&&e[ar]===Dm,Bm=e=>!!e&&typeof e=="object"&&e[ar]===xu,xx=e=>!!e&&typeof e=="object"&&e[ar]===ps;function Fm(e){if(e&&typeof e=="object")switch(e[ar]){case ds:case ps:return!0}return!1}function Cx(e){if(e&&typeof e=="object")switch(e[ar]){case Eu:case ds:case xu:case ps:return!0}return!1}var Rx=e=>(Bm(e)||Fm(e))&&!!e.anchor;Ee.ALIAS=Eu;Ee.DOC=Hm;Ee.MAP=ds;Ee.NODE_TYPE=ar;Ee.PAIR=Dm;Ee.SCALAR=xu;Ee.SEQ=ps;Ee.hasAnchor=Rx;Ee.isAlias=bx;Ee.isCollection=Fm;Ee.isDocument=kx;Ee.isMap=Sx;Ee.isNode=Cx;Ee.isPair=Ex;Ee.isScalar=Bm;Ee.isSeq=xx});var sa=R(Cu=>{"use strict";var ye=z(),qe=Symbol("break visit"),Lm=Symbol("skip children"),Ht=Symbol("remove node");function fs(e,t){let r=qm(t);ye.isDocument(e)?Ki(null,e.contents,r,Object.freeze([e]))===Ht&&(e.contents=null):Ki(null,e,r,Object.freeze([]))}fs.BREAK=qe;fs.SKIP=Lm;fs.REMOVE=Ht;function Ki(e,t,r,i){let n=Mm(e,t,r,i);if(ye.isNode(n)||ye.isPair(n))return Vm(e,i,n),Ki(e,n,r,i);if(typeof n!="symbol"){if(ye.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Ki(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===qe)return qe;o===Ht&&(t.items.splice(a,1),a-=1)}}}else if(ye.isPair(t)){i=Object.freeze(i.concat(t));let a=Ki("key",t.key,r,i);if(a===qe)return qe;a===Ht&&(t.key=null);let o=Ki("value",t.value,r,i);if(o===qe)return qe;o===Ht&&(t.value=null)}}return n}async function hs(e,t){let r=qm(t);ye.isDocument(e)?await Yi(null,e.contents,r,Object.freeze([e]))===Ht&&(e.contents=null):await Yi(null,e,r,Object.freeze([]))}hs.BREAK=qe;hs.SKIP=Lm;hs.REMOVE=Ht;async function Yi(e,t,r,i){let n=await Mm(e,t,r,i);if(ye.isNode(n)||ye.isPair(n))return Vm(e,i,n),Yi(e,n,r,i);if(typeof n!="symbol"){if(ye.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Yi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===qe)return qe;o===Ht&&(t.items.splice(a,1),a-=1)}}}else if(ye.isPair(t)){i=Object.freeze(i.concat(t));let a=await Yi("key",t.key,r,i);if(a===qe)return qe;a===Ht&&(t.key=null);let o=await Yi("value",t.value,r,i);if(o===qe)return qe;o===Ht&&(t.value=null)}}return n}function qm(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 Mm(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(ye.isMap(t))return r.Map?.(e,t,i);if(ye.isSeq(t))return r.Seq?.(e,t,i);if(ye.isPair(t))return r.Pair?.(e,t,i);if(ye.isScalar(t))return r.Scalar?.(e,t,i);if(ye.isAlias(t))return r.Alias?.(e,t,i)}function Vm(e,t,r){let i=t[t.length-1];if(ye.isCollection(i))i.items[e]=r;else if(ye.isPair(i))e==="key"?i.key=r:i.value=r;else if(ye.isDocument(i))i.contents=r;else{let n=ye.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Cu.visit=fs;Cu.visitAsync=hs});var Ru=R(zm=>{"use strict";var Wm=z(),Px=sa(),_x={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ax=e=>e.replace(/[!,[\]{}]/g,t=>_x[t]),ca=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+Ax(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Wm.isNode(t.contents)){let a={};Px.visit(t.contents,(o,s)=>{Wm.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
|
|
6
|
+
`)}};ca.defaultYaml={explicit:!1,version:"1.2"};ca.defaultTags={"!!":"tag:yaml.org,2002:"};zm.Directives=ca});var ms=R(la=>{"use strict";var Gm=z(),Ix=sa();function Tx(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Jm(e){let t=new Set;return Ix.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Um(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function jx(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Jm(e));let o=Um(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Gm.isScalar(o.node)||Gm.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}la.anchorIsValid=Tx;la.anchorNames=Jm;la.createNodeAnchors=jx;la.findNewAnchor=Um});var Pu=R(Km=>{"use strict";function ua(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=ua(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=ua(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=ua(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=ua(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Km.applyReviver=ua});var Rr=R(Xm=>{"use strict";var $x=z();function Ym(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Ym(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!$x.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}Xm.toJS=Ym});var vs=R(Zm=>{"use strict";var Ox=Pu(),Qm=z(),Hx=Rr(),_u=class{constructor(t){Object.defineProperty(this,Qm.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!Qm.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=Hx.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Ox.applyReviver(a,{"":s},"",s):s}};Zm.NodeBase=_u});var da=R(ev=>{"use strict";var Dx=ms(),Bx=sa(),Xi=z(),Fx=vs(),Lx=Rr(),Au=class extends Fx.NodeBase{constructor(t){super(Xi.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Bx.visit(t,{Node:(a,o)=>{(Xi.isAlias(o)||Xi.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Lx.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=gs(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(Dx.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 gs(e,t,r){if(Xi.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Xi.isCollection(t)){let i=0;for(let n of t.items){let a=gs(e,n,r);a>i&&(i=a)}return i}else if(Xi.isPair(t)){let i=gs(e,t.key,r),n=gs(e,t.value,r);return Math.max(i,n)}return 1}ev.Alias=Au});var pe=R(Iu=>{"use strict";var qx=z(),Mx=vs(),Vx=Rr(),Wx=e=>!e||typeof e!="function"&&typeof e!="object",Pr=class extends Mx.NodeBase{constructor(t){super(qx.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Vx.toJS(this.value,t,r)}toString(){return String(this.value)}};Pr.BLOCK_FOLDED="BLOCK_FOLDED";Pr.BLOCK_LITERAL="BLOCK_LITERAL";Pr.PLAIN="PLAIN";Pr.QUOTE_DOUBLE="QUOTE_DOUBLE";Pr.QUOTE_SINGLE="QUOTE_SINGLE";Iu.Scalar=Pr;Iu.isScalarValue=Wx});var pa=R(rv=>{"use strict";var zx=da(),fi=z(),tv=pe(),Gx="tag:yaml.org,2002:";function Jx(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function Ux(e,t,r){if(fi.isDocument(e)&&(e=e.contents),fi.isNode(e))return e;if(fi.isPair(e)){let d=r.schema[fi.MAP].createNode?.(r.schema,null,r);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:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new zx.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Gx+t.slice(2));let l=Jx(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new tv.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[fi.MAP]:Symbol.iterator in Object(e)?o[fi.SEQ]:o[fi.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new tv.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}rv.createNode=Ux});var ys=R(ws=>{"use strict";var Kx=pa(),Dt=z(),Yx=vs();function Tu(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return Kx.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var iv=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ju=class extends Yx.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>Dt.isNode(i)||Dt.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(iv(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(Dt.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Tu(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Dt.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&Dt.isScalar(a)?a.value:a:Dt.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Dt.isPair(r))return!1;let i=r.value;return i==null||t&&Dt.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Dt.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Dt.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Tu(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};ws.Collection=ju;ws.collectionFromPath=Tu;ws.isEmptyPath=iv});var fa=R(Ns=>{"use strict";var Xx=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function $u(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Qx=(e,t,r)=>e.endsWith(`
|
|
7
|
+
`)?$u(r,t):r.includes(`
|
|
8
8
|
`)?`
|
|
9
|
-
|
|
10
|
-
`)r===
|
|
9
|
+
`+$u(r,t):(e.endsWith(" ")?"":" ")+r;Ns.indentComment=$u;Ns.lineComment=Qx;Ns.stringifyComment=Xx});var av=R(ha=>{"use strict";var Zx="flow",Ou="block",bs="quoted";function eC(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let p,f,m=!1,h=-1,v=-1,g=-1;r===Ou&&(h=nv(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(r===bs&&k==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(k===`
|
|
10
|
+
`)r===Ou&&(h=nv(e,h,t.length)),d=h+t.length+c,p=void 0;else{if(k===" "&&f&&f!==" "&&f!==`
|
|
11
11
|
`&&f!==" "){let N=e[h+1];N&&N!==" "&&N!==`
|
|
12
|
-
`&&N!==" "&&(p=h)}if(h>=d)if(p)l.push(p),d=p+c,p=void 0;else if(r===
|
|
13
|
-
${t}${e.slice(0,x)}`:(r===
|
|
14
|
-
${t}${e.slice(N+1,x)}`)}return b}function
|
|
15
|
-
`);i=t,n=t+1,a=e[n]}return i}
|
|
16
|
-
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function
|
|
12
|
+
`&&N!==" "&&(p=h)}if(h>=d)if(p)l.push(p),d=p+c,p=void 0;else if(r===bs){for(;f===" "||f===" ";)f=k,k=e[h+=1],m=!0;let N=h>g+1?h-2:v-1;if(u[N])return e;l.push(N),u[N]=!0,d=N+c,p=void 0}else m=!0}f=k}if(m&&s&&s(),l.length===0)return e;o&&o();let b=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let N=l[k],x=l[k+1]||e.length;N===0?b=`
|
|
13
|
+
${t}${e.slice(0,x)}`:(r===bs&&u[N]&&(b+=`${e[N]}\\`),b+=`
|
|
14
|
+
${t}${e.slice(N+1,x)}`)}return b}function nv(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
15
|
+
`);i=t,n=t+1,a=e[n]}return i}ha.FOLD_BLOCK=Ou;ha.FOLD_FLOW=Zx;ha.FOLD_QUOTED=bs;ha.foldFlowLines=eC});var va=R(ov=>{"use strict";var yt=pe(),_r=av(),Ss=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Es=e=>/^(%|---|\.\.\.)/m.test(e);function tC(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
16
|
+
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function ma(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Es(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.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+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
|
|
17
17
|
|
|
18
18
|
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
|
|
19
|
-
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:_r.foldFlowLines(o,a,_r.FOLD_QUOTED,
|
|
20
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
21
|
-
${r}`)+"'";return t.implicitKey?i:_r.foldFlowLines(i,r,_r.FOLD_FLOW,
|
|
19
|
+
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:_r.foldFlowLines(o,a,_r.FOLD_QUOTED,Ss(t,!1))}function Hu(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
20
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return ma(e,t);let r=t.indent||(Es(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
21
|
+
${r}`)+"'";return t.implicitKey?i:_r.foldFlowLines(i,r,_r.FOLD_FLOW,Ss(t,!1))}function Qi(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=ma;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Hu:a&&!n?i=ma:i=r?Hu:ma}return i(e,t)}var Du;try{Du=new RegExp(`(^|(?<!
|
|
22
22
|
))
|
|
23
23
|
+(?!
|
|
24
|
-
|$)`,"g")}catch{
|
|
24
|
+
|$)`,"g")}catch{Du=/\n+(?!\n|$)/g}function ks({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Qi(r,i);let l=i.indent||(i.forceBlockIndent||Es(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===yt.Scalar.BLOCK_FOLDED?!1:t===yt.Scalar.BLOCK_LITERAL?!0:!tC(r,c,l.length);if(!r)return u?`|
|
|
25
25
|
`:`>
|
|
26
26
|
`;let d,p;for(p=r.length;p>0;--p){let x=r[p-1];if(x!==`
|
|
27
27
|
`&&x!==" "&&x!==" ")break}let f=r.substring(p),m=f.indexOf(`
|
|
28
28
|
`);m===-1?d="-":r===f||m!==f.length-1?(d="+",a&&a()):d="",f&&(r=r.slice(0,-f.length),f[f.length-1]===`
|
|
29
|
-
`&&(f=f.slice(0,-1)),f=f.replace(
|
|
29
|
+
`&&(f=f.slice(0,-1)),f=f.replace(Du,`$&${l}`));let h=!1,v,g=-1;for(v=0;v<r.length;++v){let x=r[v];if(x===" ")h=!0;else if(x===`
|
|
30
30
|
`)g=v;else break}let b=r.substring(0,g<v?g+1:v);b&&(r=r.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let N=(h?l?"2":"1":"")+d;if(e&&(N+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let x=r.replace(/\n+/g,`
|
|
31
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),w=!1,S=
|
|
31
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),w=!1,S=Ss(i,!0);o!=="folded"&&t!==yt.Scalar.BLOCK_FOLDED&&(S.onOverflow=()=>{w=!0});let E=_r.foldFlowLines(`${b}${x}${f}`,l,_r.FOLD_BLOCK,S);if(!w)return`>${N}
|
|
32
32
|
${l}${E}`}return r=r.replace(/\n+/g,`$&${l}`),`|${N}
|
|
33
|
-
${l}${b}${r}${f}`}function
|
|
34
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
35
|
-
`)?
|
|
36
|
-
`))return
|
|
37
|
-
${c}`);if(o){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:f,tags:m}=t.doc.schema;if(m.some(p)||f?.some(p))return
|
|
38
|
-
${t.indent}${s}`:s}
|
|
39
|
-
${s}:`):(v=`${v}:`,p&&(v+=
|
|
33
|
+
${l}${b}${r}${f}`}function rC(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
34
|
+
`)||u&&/[[\]{},]/.test(a))return Qi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
35
|
+
`)?Qi(a,t):ks(e,t,r,i);if(!s&&!u&&n!==yt.Scalar.PLAIN&&a.includes(`
|
|
36
|
+
`))return ks(e,t,r,i);if(Es(a)){if(c==="")return t.forceBlockIndent=!0,ks(e,t,r,i);if(s&&c===l)return Qi(a,t)}let d=a.replace(/\n+/g,`$&
|
|
37
|
+
${c}`);if(o){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:f,tags:m}=t.doc.schema;if(m.some(p)||f?.some(p))return Qi(a,t)}return s?d:_r.foldFlowLines(d,c,_r.FOLD_FLOW,Ss(t,!1))}function iC(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==yt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=yt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case yt.Scalar.BLOCK_FOLDED:case yt.Scalar.BLOCK_LITERAL:return n||a?Qi(o.value,t):ks(o,t,r,i);case yt.Scalar.QUOTE_DOUBLE:return ma(o.value,t);case yt.Scalar.QUOTE_SINGLE:return Hu(o.value,t);case yt.Scalar.PLAIN:return rC(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,p=n&&u||d;if(l=c(p),l===null)throw new Error(`Unsupported default string type ${p}`)}return l}ov.stringifyString=iC});var ga=R(Bu=>{"use strict";var nC=ms(),Ar=z(),aC=fa(),oC=va();function sC(e,t){let r=Object.assign({blockQuote:!0,commentString:aC.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function cC(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(Ar.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function lC(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Ar.isScalar(e)||Ar.isCollection(e))&&e.anchor;a&&nC.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function uC(e,t,r,i){if(Ar.isPair(e))return e.toString(t,r,i);if(Ar.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=Ar.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=cC(t.doc.schema.tags,a));let o=lC(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):Ar.isScalar(a)?oC.stringifyString(a,t,r,i):a.toString(t,r,i);return o?Ar.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
38
|
+
${t.indent}${s}`:s}Bu.createStringifyContext=sC;Bu.stringify=uC});var uv=R(lv=>{"use strict";var or=z(),sv=pe(),cv=ga(),wa=fa();function dC({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,p=or.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(or.isCollection(e)||!or.isNode(e)&&typeof e=="object"){let S="With simple keys, collection cannot be used as a key value";throw new Error(S)}}let f=!d&&(!e||p&&t==null&&!r.inFlow||or.isCollection(e)||(or.isScalar(e)?e.type===sv.Scalar.BLOCK_FOLDED||e.type===sv.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!f&&(d||!a),indent:s+c});let m=!1,h=!1,v=cv.stringify(e,r,()=>m=!0,()=>h=!0);if(!f&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");f=!0}if(r.inFlow){if(a||t==null)return m&&i&&i(),v===""?"?":f?`? ${v}`:v}else if(a&&!d||t==null&&f)return v=`? ${v}`,p&&!m?v+=wa.lineComment(v,r.indent,l(p)):h&&n&&n(),v;m&&(p=null),f?(p&&(v+=wa.lineComment(v,r.indent,l(p))),v=`? ${v}
|
|
39
|
+
${s}:`):(v=`${v}:`,p&&(v+=wa.lineComment(v,r.indent,l(p))));let g,b,k;or.isNode(t)?(g=!!t.spaceBefore,b=t.commentBefore,k=t.comment):(g=!1,b=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!f&&!p&&or.isScalar(t)&&(r.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!f&&or.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let N=!1,x=cv.stringify(t,r,()=>N=!0,()=>h=!0),w=" ";if(p||g||b){if(w=g?`
|
|
40
40
|
`:"",b){let S=l(b);w+=`
|
|
41
|
-
${
|
|
41
|
+
${wa.indentComment(S,r.indent)}`}x===""&&!r.inFlow?w===`
|
|
42
42
|
`&&k&&(w=`
|
|
43
43
|
|
|
44
44
|
`):w+=`
|
|
45
45
|
${r.indent}`}else if(!f&&or.isCollection(t)){let S=x[0],E=x.indexOf(`
|
|
46
46
|
`),y=E!==-1,C=r.inFlow??t.flow??t.items.length===0;if(y||!C){let O=!1;if(y&&(S==="&"||S==="!")){let T=x.indexOf(" ");S==="&"&&T!==-1&&T<E&&x[T+1]==="!"&&(T=x.indexOf(" ",T+1)),(T===-1||E<T)&&(O=!0)}O||(w=`
|
|
47
47
|
${r.indent}`)}}else(x===""||x[0]===`
|
|
48
|
-
`)&&(w="");return v+=w+x,r.inFlow?N&&i&&i():k&&!N?v+=
|
|
48
|
+
`)&&(w="");return v+=w+x,r.inFlow?N&&i&&i():k&&!N?v+=wa.lineComment(v,r.indent,l(k)):h&&n&&n(),v}lv.stringifyPair=dC});var Lu=R(Fu=>{"use strict";var dv=os("process");function pC(e,...t){e==="debug"&&console.log(...t)}function fC(e,t){(e==="debug"||e==="warn")&&(typeof dv.emitWarning=="function"?dv.emitWarning(t):console.warn(t))}Fu.debug=pC;Fu.warn=fC});var _s=R(Ps=>{"use strict";var Rs=z(),pv=pe(),xs="<<",Cs={identify:e=>e===xs||typeof e=="symbol"&&e.description===xs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new pv.Scalar(Symbol(xs)),{addToJSMap:fv}),stringify:()=>xs},hC=(e,t)=>(Cs.identify(t)||Rs.isScalar(t)&&(!t.type||t.type===pv.Scalar.PLAIN)&&Cs.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Cs.tag&&r.default);function fv(e,t,r){let i=hv(e,r);if(Rs.isSeq(i))for(let n of i.items)qu(e,t,n);else if(Array.isArray(i))for(let n of i)qu(e,t,n);else qu(e,t,i)}function qu(e,t,r){let i=hv(e,r);if(!Rs.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function hv(e,t){return e&&Rs.isAlias(t)?t.resolve(e.doc,e):t}Ps.addMergeToJSMap=fv;Ps.isMergeKey=hC;Ps.merge=Cs});var Vu=R(gv=>{"use strict";var mC=Lu(),mv=_s(),vC=ga(),vv=z(),Mu=Rr();function gC(e,t,{key:r,value:i}){if(vv.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(mv.isMergeKey(e,r))mv.addMergeToJSMap(e,t,i);else{let n=Mu.toJS(r,"",e);if(t instanceof Map)t.set(n,Mu.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=wC(r,n,e),o=Mu.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function wC(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(vv.isNode(e)&&r?.doc){let i=vC.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),mC.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}gv.addPairToJSMap=gC});var Ir=R(Wu=>{"use strict";var wv=pa(),yC=uv(),NC=Vu(),As=z();function bC(e,t,r){let i=wv.createNode(e,void 0,r),n=wv.createNode(t,void 0,r);return new Is(i,n)}var Is=class e{constructor(t,r=null){Object.defineProperty(this,As.NODE_TYPE,{value:As.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return As.isNode(r)&&(r=r.clone(t)),As.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return NC.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?yC.stringifyPair(this,t,r,i):JSON.stringify(this)}};Wu.Pair=Is;Wu.createPair=bC});var zu=R(Nv=>{"use strict";var hi=z(),yv=ga(),Ts=fa();function kC(e,t,r){return(t.inFlow??e.flow?EC:SC)(e,t,r)}function SC({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,p=[];for(let m=0;m<t.length;++m){let h=t[m],v=null;if(hi.isNode(h))!d&&h.spaceBefore&&p.push(""),js(r,p,h.commentBefore,d),h.comment&&(v=h.comment);else if(hi.isPair(h)){let b=hi.isNode(h.key)?h.key:null;b&&(!d&&b.spaceBefore&&p.push(""),js(r,p,b.commentBefore,d))}d=!1;let g=yv.stringify(h,u,()=>v=null,()=>d=!0);v&&(g+=Ts.lineComment(g,a,l(v))),d&&v&&(d=!1),p.push(i+g)}let f;if(p.length===0)f=n.start+n.end;else{f=p[0];for(let m=1;m<p.length;++m){let h=p[m];f+=h?`
|
|
49
49
|
${c}${h}`:`
|
|
50
50
|
`}}return e?(f+=`
|
|
51
|
-
`+
|
|
52
|
-
`)),m<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((b,k)=>b+k.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=
|
|
51
|
+
`+Ts.indentComment(l(e),c),s&&s()):d&&o&&o(),f}function EC({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(hi.isNode(h))h.spaceBefore&&d.push(""),js(t,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(hi.isPair(h)){let b=hi.isNode(h.key)?h.key:null;b&&(b.spaceBefore&&d.push(""),js(t,d,b.commentBefore,!1),b.comment&&(l=!0));let k=hi.isNode(h.value)?h.value:null;k?(k.comment&&(v=k.comment),k.commentBefore&&(l=!0)):h.value==null&&b?.comment&&(v=b.comment)}v&&(l=!0);let g=yv.stringify(h,c,()=>v=null);l||(l=d.length>u||g.includes(`
|
|
52
|
+
`)),m<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((b,k)=>b+k.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=Ts.lineComment(g,i,s(v))),d.push(g),u=d.length}let{start:p,end:f}=r;if(d.length===0)return p+f;if(!l){let m=d.reduce((h,v)=>h+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=p;for(let h of d)m+=h?`
|
|
53
53
|
${a}${n}${h}`:`
|
|
54
54
|
`;return`${m}
|
|
55
|
-
${n}${f}`}else return`${p}${o}${d.join(" ")}${o}${f}`}function
|
|
56
|
-
`:" ")}return
|
|
55
|
+
${n}${f}`}else return`${p}${o}${d.join(" ")}${o}${f}`}function js({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=Ts.indentComment(t(i),e);r.push(a.trimStart())}}Nv.stringifyCollection=kC});var jr=R(Ju=>{"use strict";var xC=zu(),CC=Vu(),RC=ys(),Tr=z(),$s=Ir(),PC=pe();function ya(e,t){let r=Tr.isScalar(t)?t.value:t;for(let i of e)if(Tr.isPair(i)&&(i.key===t||i.key===r||Tr.isScalar(i.key)&&i.key.value===r))return i}var Gu=class extends RC.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Tr.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push($s.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;Tr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new $s.Pair(t,t?.value):i=new $s.Pair(t.key,t.value);let n=ya(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Tr.isScalar(n.value)&&PC.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=ya(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=ya(this.items,t)?.value;return(!r&&Tr.isScalar(n)?n.value:n)??void 0}has(t){return!!ya(this.items,t)}set(t,r){this.add(new $s.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)CC.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Tr.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})),xC.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Ju.YAMLMap=Gu;Ju.findPair=ya});var Zi=R(kv=>{"use strict";var _C=z(),bv=jr(),AC={collection:"map",default:!0,nodeClass:bv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return _C.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>bv.YAMLMap.from(e,t,r)};kv.map=AC});var $r=R(Sv=>{"use strict";var IC=pa(),TC=zu(),jC=ys(),Hs=z(),$C=pe(),OC=Rr(),Uu=class extends jC.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Hs.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Os(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=Os(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Hs.isScalar(n)?n.value:n}has(t){let r=Os(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=Os(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Hs.isScalar(n)&&$C.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(OC.toJS(a,String(n++),r));return i}toString(t,r,i){return t?TC.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(IC.createNode(s,void 0,i))}}return a}};function Os(e){let t=Hs.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Sv.YAMLSeq=Uu});var en=R(xv=>{"use strict";var HC=z(),Ev=$r(),DC={collection:"seq",default:!0,nodeClass:Ev.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return HC.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Ev.YAMLSeq.from(e,t,r)};xv.seq=DC});var Na=R(Cv=>{"use strict";var BC=va(),FC={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),BC.stringifyString(e,t,r,i)}};Cv.string=FC});var Ds=R(_v=>{"use strict";var Rv=pe(),Pv={identify:e=>e==null,createNode:()=>new Rv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Rv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Pv.test.test(e)?e:t.options.nullStr};_v.nullTag=Pv});var Ku=R(Iv=>{"use strict";var LC=pe(),Av={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new LC.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Av.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Iv.boolTag=Av});var tn=R(Tv=>{"use strict";function qC({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Tv.stringifyNumber=qC});var Xu=R(Bs=>{"use strict";var MC=pe(),Yu=tn(),VC={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:Yu.stringifyNumber},WC={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():Yu.stringifyNumber(e)}},zC={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 MC.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Yu.stringifyNumber};Bs.float=zC;Bs.floatExp=WC;Bs.floatNaN=VC});var Zu=R(Ls=>{"use strict";var jv=tn(),Fs=e=>typeof e=="bigint"||Number.isInteger(e),Qu=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function $v(e,t,r){let{value:i}=e;return Fs(i)&&i>=0?r+i.toString(t):jv.stringifyNumber(e)}var GC={identify:e=>Fs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Qu(e,2,8,r),stringify:e=>$v(e,8,"0o")},JC={identify:Fs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Qu(e,0,10,r),stringify:jv.stringifyNumber},UC={identify:e=>Fs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Qu(e,2,16,r),stringify:e=>$v(e,16,"0x")};Ls.int=JC;Ls.intHex=UC;Ls.intOct=GC});var Hv=R(Ov=>{"use strict";var KC=Zi(),YC=Ds(),XC=en(),QC=Na(),ZC=Ku(),ed=Xu(),td=Zu(),eR=[KC.map,XC.seq,QC.string,YC.nullTag,ZC.boolTag,td.intOct,td.int,td.intHex,ed.floatNaN,ed.floatExp,ed.float];Ov.schema=eR});var Fv=R(Bv=>{"use strict";var tR=pe(),rR=Zi(),iR=en();function Dv(e){return typeof e=="bigint"||Number.isInteger(e)}var qs=({value:e})=>JSON.stringify(e),nR=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:qs},{identify:e=>e==null,createNode:()=>new tR.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:qs},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:qs},{identify:Dv,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Dv(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:qs}],aR={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},oR=[rR.map,iR.seq].concat(nR,aR);Bv.schema=oR});var id=R(Lv=>{"use strict";var ba=os("buffer"),rd=pe(),sR=va(),cR={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ba.Buffer=="function")return ba.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof ba.Buffer=="function")s=o instanceof ba.Buffer?o.toString("base64"):ba.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=rd.Scalar.BLOCK_LITERAL),t!==rd.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,p=0;d<l;++d,p+=c)u[d]=s.substr(p,c);s=u.join(t===rd.Scalar.BLOCK_LITERAL?`
|
|
56
|
+
`:" ")}return sR.stringifyString({comment:e,type:t,value:s},i,n,a)}};Lv.binary=cR});var Ws=R(Vs=>{"use strict";var Ms=z(),nd=Ir(),lR=pe(),uR=$r();function qv(e,t){if(Ms.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Ms.isPair(i)){if(Ms.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new nd.Pair(new lR.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
|
|
57
57
|
${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
|
|
58
|
-
${a.comment}`:i.comment}i=n}e.items[r]=Ls.isPair(i)?i:new td.Pair(i)}}else t("Expected a sequence for this tag");return e}function Bv(e,t,r){let{replacer:i}=r,n=new ZC.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(td.createPair(s,c,r))}return n}var eR={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Dv,createNode:Bv};qs.createPairs=Bv;qs.pairs=eR;qs.resolvePairs=Dv});var nd=R(id=>{"use strict";var Fv=z(),rd=Rr(),ba=jr(),tR=$r(),Lv=Ms(),mi=class e extends tR.YAMLSeq{constructor(){super(),this.add=ba.YAMLMap.prototype.add.bind(this),this.delete=ba.YAMLMap.prototype.delete.bind(this),this.get=ba.YAMLMap.prototype.get.bind(this),this.has=ba.YAMLMap.prototype.has.bind(this),this.set=ba.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Fv.isPair(n)?(a=rd.toJS(n.key,"",r),o=rd.toJS(n.value,a,r)):a=rd.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Lv.createPairs(t,r,i),a=new this;return a.items=n.items,a}};mi.tag="tag:yaml.org,2002:omap";var rR={collection:"seq",identify:e=>e instanceof Map,nodeClass:mi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Lv.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Fv.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new mi,r)},createNode:(e,t,r)=>mi.from(e,t,r)};id.YAMLOMap=mi;id.omap=rR});var zv=R(ad=>{"use strict";var qv=pe();function Mv({value:e,source:t},r){return t&&(e?Vv:Wv).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Vv={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 qv.Scalar(!0),stringify:Mv},Wv={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 qv.Scalar(!1),stringify:Mv};ad.falseTag=Wv;ad.trueTag=Vv});var Gv=R(Vs=>{"use strict";var iR=pe(),od=en(),nR={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:od.stringifyNumber},aR={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():od.stringifyNumber(e)}},oR={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 iR.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:od.stringifyNumber};Vs.float=oR;Vs.floatExp=aR;Vs.floatNaN=nR});var Uv=R(Sa=>{"use strict";var Jv=en(),ka=e=>typeof e=="bigint"||Number.isInteger(e);function Ws(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function sd(e,t,r){let{value:i}=e;if(ka(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Jv.stringifyNumber(e)}var sR={identify:ka,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Ws(e,2,2,r),stringify:e=>sd(e,2,"0b")},cR={identify:ka,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Ws(e,1,8,r),stringify:e=>sd(e,8,"0")},lR={identify:ka,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Ws(e,0,10,r),stringify:Jv.stringifyNumber},uR={identify:ka,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Ws(e,2,16,r),stringify:e=>sd(e,16,"0x")};Sa.int=lR;Sa.intBin=sR;Sa.intHex=uR;Sa.intOct=cR});var ld=R(cd=>{"use strict";var Js=z(),zs=Ir(),Gs=jr(),vi=class e extends Gs.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Js.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new zs.Pair(t.key,null):r=new zs.Pair(t,null),Gs.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Gs.findPair(this.items,t);return!r&&Js.isPair(i)?Js.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Gs.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new zs.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(zs.createPair(o,null,i));return a}};vi.tag="tag:yaml.org,2002:set";var dR={collection:"map",identify:e=>e instanceof Set,nodeClass:vi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>vi.from(e,t,r),resolve(e,t){if(Js.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new vi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};cd.YAMLSet=vi;cd.set=dR});var dd=R(Us=>{"use strict";var pR=en();function ud(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function Kv(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return pR.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var fR={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>ud(e,r),stringify:Kv},hR={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=>ud(e,!1),stringify:Kv},Yv={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(Yv.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=ud(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$/,"")??""};Us.floatTime=hR;Us.intTime=fR;Us.timestamp=Yv});var Zv=R(Qv=>{"use strict";var mR=Qi(),vR=Os(),gR=Zi(),wR=ya(),yR=ed(),Xv=zv(),pd=Gv(),Ks=Uv(),NR=Rs(),bR=nd(),kR=Ms(),SR=ld(),fd=dd(),ER=[mR.map,gR.seq,wR.string,vR.nullTag,Xv.trueTag,Xv.falseTag,Ks.intBin,Ks.intOct,Ks.int,Ks.intHex,pd.floatNaN,pd.floatExp,pd.float,yR.binary,NR.merge,bR.omap,kR.pairs,SR.set,fd.intTime,fd.floatTime,fd.timestamp];Qv.schema=ER});var lg=R(vd=>{"use strict";var ig=Qi(),xR=Os(),ng=Zi(),CR=ya(),RR=Gu(),hd=Uu(),md=Yu(),PR=Tv(),_R=Ov(),ag=ed(),Ea=Rs(),og=nd(),sg=Ms(),eg=Zv(),cg=ld(),Ys=dd(),tg=new Map([["core",PR.schema],["failsafe",[ig.map,ng.seq,CR.string]],["json",_R.schema],["yaml11",eg.schema],["yaml-1.1",eg.schema]]),rg={binary:ag.binary,bool:RR.boolTag,float:hd.float,floatExp:hd.floatExp,floatNaN:hd.floatNaN,floatTime:Ys.floatTime,int:md.int,intHex:md.intHex,intOct:md.intOct,intTime:Ys.intTime,map:ig.map,merge:Ea.merge,null:xR.nullTag,omap:og.omap,pairs:sg.pairs,seq:ng.seq,set:cg.set,timestamp:Ys.timestamp},AR={"tag:yaml.org,2002:binary":ag.binary,"tag:yaml.org,2002:merge":Ea.merge,"tag:yaml.org,2002:omap":og.omap,"tag:yaml.org,2002:pairs":sg.pairs,"tag:yaml.org,2002:set":cg.set,"tag:yaml.org,2002:timestamp":Ys.timestamp};function IR(e,t,r){let i=tg.get(t);if(i&&!e)return r&&!i.includes(Ea.merge)?i.concat(Ea.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(tg.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(Ea.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?rg[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(rg).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},[])}vd.coreKnownTags=AR;vd.getTags=IR});var yd=R(ug=>{"use strict";var gd=z(),TR=Qi(),jR=Zi(),$R=ya(),Xs=lg(),OR=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,wd=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Xs.getTags(t,"compat"):t?Xs.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Xs.coreKnownTags:{},this.tags=Xs.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,gd.MAP,{value:TR.map}),Object.defineProperty(this,gd.SCALAR,{value:$R.string}),Object.defineProperty(this,gd.SEQ,{value:jR.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?OR:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};ug.Schema=wd});var pg=R(dg=>{"use strict";var HR=z(),Nd=va(),xa=pa();function DR(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Nd.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(xa.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(HR.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(xa.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Nd.stringify(e.contents,n,()=>s=null,c);s&&(l+=xa.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Nd.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
59
|
-
`)?(r.push("..."),r.push(
|
|
58
|
+
${a.comment}`:i.comment}i=n}e.items[r]=Ms.isPair(i)?i:new nd.Pair(i)}}else t("Expected a sequence for this tag");return e}function Mv(e,t,r){let{replacer:i}=r,n=new uR.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(nd.createPair(s,c,r))}return n}var dR={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:qv,createNode:Mv};Vs.createPairs=Mv;Vs.pairs=dR;Vs.resolvePairs=qv});var sd=R(od=>{"use strict";var Vv=z(),ad=Rr(),ka=jr(),pR=$r(),Wv=Ws(),mi=class e extends pR.YAMLSeq{constructor(){super(),this.add=ka.YAMLMap.prototype.add.bind(this),this.delete=ka.YAMLMap.prototype.delete.bind(this),this.get=ka.YAMLMap.prototype.get.bind(this),this.has=ka.YAMLMap.prototype.has.bind(this),this.set=ka.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Vv.isPair(n)?(a=ad.toJS(n.key,"",r),o=ad.toJS(n.value,a,r)):a=ad.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Wv.createPairs(t,r,i),a=new this;return a.items=n.items,a}};mi.tag="tag:yaml.org,2002:omap";var fR={collection:"seq",identify:e=>e instanceof Map,nodeClass:mi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Wv.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Vv.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new mi,r)},createNode:(e,t,r)=>mi.from(e,t,r)};od.YAMLOMap=mi;od.omap=fR});var Kv=R(cd=>{"use strict";var zv=pe();function Gv({value:e,source:t},r){return t&&(e?Jv:Uv).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Jv={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 zv.Scalar(!0),stringify:Gv},Uv={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 zv.Scalar(!1),stringify:Gv};cd.falseTag=Uv;cd.trueTag=Jv});var Yv=R(zs=>{"use strict";var hR=pe(),ld=tn(),mR={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:ld.stringifyNumber},vR={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():ld.stringifyNumber(e)}},gR={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 hR.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:ld.stringifyNumber};zs.float=gR;zs.floatExp=vR;zs.floatNaN=mR});var Qv=R(Ea=>{"use strict";var Xv=tn(),Sa=e=>typeof e=="bigint"||Number.isInteger(e);function Gs(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function ud(e,t,r){let{value:i}=e;if(Sa(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Xv.stringifyNumber(e)}var wR={identify:Sa,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Gs(e,2,2,r),stringify:e=>ud(e,2,"0b")},yR={identify:Sa,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Gs(e,1,8,r),stringify:e=>ud(e,8,"0")},NR={identify:Sa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Gs(e,0,10,r),stringify:Xv.stringifyNumber},bR={identify:Sa,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Gs(e,2,16,r),stringify:e=>ud(e,16,"0x")};Ea.int=NR;Ea.intBin=wR;Ea.intHex=bR;Ea.intOct=yR});var pd=R(dd=>{"use strict";var Ks=z(),Js=Ir(),Us=jr(),vi=class e extends Us.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Ks.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Js.Pair(t.key,null):r=new Js.Pair(t,null),Us.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Us.findPair(this.items,t);return!r&&Ks.isPair(i)?Ks.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Us.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Js.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Js.createPair(o,null,i));return a}};vi.tag="tag:yaml.org,2002:set";var kR={collection:"map",identify:e=>e instanceof Set,nodeClass:vi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>vi.from(e,t,r),resolve(e,t){if(Ks.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new vi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};dd.YAMLSet=vi;dd.set=kR});var hd=R(Ys=>{"use strict";var SR=tn();function fd(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function Zv(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return SR.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var ER={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>fd(e,r),stringify:Zv},xR={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=>fd(e,!1),stringify:Zv},eg={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(eg.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=fd(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$/,"")??""};Ys.floatTime=xR;Ys.intTime=ER;Ys.timestamp=eg});var ig=R(rg=>{"use strict";var CR=Zi(),RR=Ds(),PR=en(),_R=Na(),AR=id(),tg=Kv(),md=Yv(),Xs=Qv(),IR=_s(),TR=sd(),jR=Ws(),$R=pd(),vd=hd(),OR=[CR.map,PR.seq,_R.string,RR.nullTag,tg.trueTag,tg.falseTag,Xs.intBin,Xs.intOct,Xs.int,Xs.intHex,md.floatNaN,md.floatExp,md.float,AR.binary,IR.merge,TR.omap,jR.pairs,$R.set,vd.intTime,vd.floatTime,vd.timestamp];rg.schema=OR});var fg=R(yd=>{"use strict";var sg=Zi(),HR=Ds(),cg=en(),DR=Na(),BR=Ku(),gd=Xu(),wd=Zu(),FR=Hv(),LR=Fv(),lg=id(),xa=_s(),ug=sd(),dg=Ws(),ng=ig(),pg=pd(),Qs=hd(),ag=new Map([["core",FR.schema],["failsafe",[sg.map,cg.seq,DR.string]],["json",LR.schema],["yaml11",ng.schema],["yaml-1.1",ng.schema]]),og={binary:lg.binary,bool:BR.boolTag,float:gd.float,floatExp:gd.floatExp,floatNaN:gd.floatNaN,floatTime:Qs.floatTime,int:wd.int,intHex:wd.intHex,intOct:wd.intOct,intTime:Qs.intTime,map:sg.map,merge:xa.merge,null:HR.nullTag,omap:ug.omap,pairs:dg.pairs,seq:cg.seq,set:pg.set,timestamp:Qs.timestamp},qR={"tag:yaml.org,2002:binary":lg.binary,"tag:yaml.org,2002:merge":xa.merge,"tag:yaml.org,2002:omap":ug.omap,"tag:yaml.org,2002:pairs":dg.pairs,"tag:yaml.org,2002:set":pg.set,"tag:yaml.org,2002:timestamp":Qs.timestamp};function MR(e,t,r){let i=ag.get(t);if(i&&!e)return r&&!i.includes(xa.merge)?i.concat(xa.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(ag.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(xa.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?og[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(og).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},[])}yd.coreKnownTags=qR;yd.getTags=MR});var kd=R(hg=>{"use strict";var Nd=z(),VR=Zi(),WR=en(),zR=Na(),Zs=fg(),GR=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,bd=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Zs.getTags(t,"compat"):t?Zs.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Zs.coreKnownTags:{},this.tags=Zs.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Nd.MAP,{value:VR.map}),Object.defineProperty(this,Nd.SCALAR,{value:zR.string}),Object.defineProperty(this,Nd.SEQ,{value:WR.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?GR:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};hg.Schema=bd});var vg=R(mg=>{"use strict";var JR=z(),Sd=ga(),Ca=fa();function UR(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Sd.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Ca.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(JR.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Ca.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Sd.stringify(e.contents,n,()=>s=null,c);s&&(l+=Ca.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Sd.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
59
|
+
`)?(r.push("..."),r.push(Ca.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(Ca.indentComment(a(c),"")))}return r.join(`
|
|
60
60
|
`)+`
|
|
61
|
-
`}
|
|
61
|
+
`}mg.stringifyDocument=UR});var Ra=R(gg=>{"use strict";var KR=da(),rn=ys(),it=z(),YR=Ir(),XR=Rr(),QR=kd(),ZR=vg(),Ed=ms(),eP=Pu(),tP=pa(),xd=Ru(),Cd=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,it.NODE_TYPE,{value:it.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new xd.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[it.NODE_TYPE]:{value:it.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=it.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){nn(this.contents)&&this.contents.add(t)}addIn(t,r){nn(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=Ed.anchorNames(this);t.anchor=!r||i.has(r)?Ed.findNewAnchor(r||"a",i):r}return new KR.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let v=b=>typeof b=="number"||b instanceof String||b instanceof Number,g=r.filter(v).map(String);g.length>0&&(r=r.concat(g)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=i??{},{onAnchor:d,setAnchors:p,sourceObjects:f}=Ed.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:f},h=tP.createNode(t,u,m);return s&&it.isCollection(h)&&(h.flow=!0),p(),h}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new YR.Pair(n,a)}delete(t){return nn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return rn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):nn(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return it.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return rn.isEmptyPath(t)?!r&&it.isScalar(this.contents)?this.contents.value:this.contents:it.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return it.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return rn.isEmptyPath(t)?this.contents!==void 0:it.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=rn.collectionFromPath(this.schema,[t],r):nn(this.contents)&&this.contents.set(t,r)}setIn(t,r){rn.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=rn.collectionFromPath(this.schema,Array.from(t),r):nn(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new xd.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new xd.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new QR.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=XR.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?eP.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return ZR.stringifyDocument(this,t)}};function nn(e){if(it.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}gg.Document=Cd});var Aa=R(_a=>{"use strict";var Pa=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Rd=class extends Pa{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Pd=class extends Pa{constructor(t,r,i){super("YAMLWarning",t,r,i)}},rP=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
62
62
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
|
|
63
63
|
|
|
64
64
|
${o}
|
|
65
65
|
${l}
|
|
66
|
-
`}};
|
|
67
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(
|
|
68
|
-
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||
|
|
69
|
-
`+k.comment:b.comment=k.comment);let N=new
|
|
70
|
-
`+w.comment:l.comment=w.comment),d=w.end;continue}!o&&r.options.strict&&
|
|
71
|
-
`+S:E.comment=S,w.comment=w.comment.substring(S.length+1)}}if(!o&&!N&&!w.found){let S=x?e(r,x,w,n):t(r,w.end,N,null,w,n);l.items.push(S),d=S.range[2],
|
|
72
|
-
`+y.comment:E.comment=y.comment);let O=new
|
|
73
|
-
`+v.comment:l.comment=v.comment),l.range=[i.offset,h,v.offset]}else l.range=[i.offset,h,h];return l}
|
|
66
|
+
`}};_a.YAMLError=Pa;_a.YAMLParseError=Rd;_a.YAMLWarning=Pd;_a.prettifyError=rP});var Ia=R(wg=>{"use strict";function iP(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",p="",f=!1,m=!1,h=null,v=null,g=null,b=null,k=null,N=null,x=null;for(let E of e)switch(m&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&a(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&E.type!=="comment"&&E.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),E.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&E.source.includes(" ")&&(h=E),u=!0;break;case"comment":{u||a(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let y=E.source.substring(1)||" ";d?d+=p+y:d=y,p="",l=!1;break}case"newline":l?d?d+=E.source:(!N||r!=="seq-item-ind")&&(c=!0):p+=E.source,l=!0,f=!0,(v||g)&&(b=E),u=!0;break;case"anchor":v&&a(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&a(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=E,x??(x=E.offset),l=!1,u=!1,m=!0;break;case"tag":{g&&a(E,"MULTIPLE_TAGS","A node can have at most one tag"),g=E,x??(x=E.offset),l=!1,u=!1,m=!0;break}case r:(v||g)&&a(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),N&&a(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${t??"collection"}`),N=E,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(E,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=E,l=!1,u=!1;break}default:a(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),l=!1,u=!1}let w=e[e.length-1],S=w?w.offset+w.source.length:n;return m&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:N,spaceBefore:c,comment:d,hasNewline:f,anchor:v,tag:g,newlineAfterProp:b,end:S,start:x??S}}wg.resolveProps=iP});var ec=R(yg=>{"use strict";function _d(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
67
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(_d(t.key)||_d(t.value))return!0}return!1;default:return!0}}yg.containsNewline=_d});var Ad=R(Ng=>{"use strict";var nP=ec();function aP(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&nP.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ng.flowIndentCheck=aP});var Id=R(kg=>{"use strict";var bg=z();function oP(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||bg.isScalar(a)&&bg.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}kg.mapIncludes=oP});var Pg=R(Rg=>{"use strict";var Sg=Ir(),sP=jr(),Eg=Ia(),cP=ec(),xg=Ad(),lP=Id(),Cg="All mapping items must start at the same column";function uP({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??sP.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let u of i.items){let{start:d,key:p,sep:f,value:m}=u,h=Eg.resolveProps(d,{indicator:"explicit-key-ind",next:p??f?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!h.found;if(v){if(p&&(p.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==i.indent&&n(c,"BAD_INDENT",Cg)),!h.anchor&&!h.tag&&!f){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
68
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||cP.containsNewline(p))&&n(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(c,"BAD_INDENT",Cg);r.atKey=!0;let g=h.end,b=p?e(r,p,h,n):t(r,g,d,null,h,n);r.schema.compat&&xg.flowIndentCheck(i.indent,p,n),r.atKey=!1,lP.mapIncludes(r,s.items,b)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let k=Eg.resolveProps(f??[],{indicator:"map-value-ind",next:m,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!p||p.type==="block-scalar"});if(c=k.end,k.found){v&&(m?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<k.found.offset-1024&&n(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let N=m?e(r,m,k,n):t(r,c,f,null,k,n);r.schema.compat&&xg.flowIndentCheck(i.indent,m,n),c=N.range[2];let x=new Sg.Pair(b,N);r.options.keepSourceTokens&&(x.srcToken=u),s.items.push(x)}else{v&&n(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(b.comment?b.comment+=`
|
|
69
|
+
`+k.comment:b.comment=k.comment);let N=new Sg.Pair(b);r.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Rg.resolveBlockMap=uP});var Ag=R(_g=>{"use strict";var dP=$r(),pP=Ia(),fP=Ad();function hP({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??dP.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:d}of i.items){let p=pP.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d?.type==="block-seq"?n(p.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=p.end,p.comment&&(s.comment=p.comment);continue}let f=d?e(r,d,p,n):t(r,p.end,u,null,p,n);r.schema.compat&&fP.flowIndentCheck(i.indent,d,n),c=f.range[2],s.items.push(f)}return s.range=[i.offset,c,l??c],s}_g.resolveBlockSeq=hP});var an=R(Ig=>{"use strict";function mP(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Ig.resolveEnd=mP});var Og=R($g=>{"use strict";var vP=z(),gP=Ir(),Tg=jr(),wP=$r(),yP=an(),jg=Ia(),NP=ec(),bP=Id(),Td="Block collections are not allowed within flow collections",jd=e=>e&&(e.type==="block-map"||e.type==="block-seq");function kP({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Tg.YAMLMap:wP.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let v=0;v<i.items.length;++v){let g=i.items[v],{start:b,key:k,sep:N,value:x}=g,w=jg.resolveProps(b,{flow:s,indicator:"explicit-key-ind",next:k??N?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!N&&!x){v===0&&w.comma?n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<i.items.length-1&&n(w.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),w.comment&&(l.comment?l.comment+=`
|
|
70
|
+
`+w.comment:l.comment=w.comment),d=w.end;continue}!o&&r.options.strict&&NP.containsNewline(k)&&n(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)w.comma&&n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(w.comma||n(w.start,"MISSING_CHAR",`Missing , between ${s} items`),w.comment){let S="";e:for(let E of b)switch(E.type){case"comma":case"space":break;case"comment":S=E.source.substring(1);break e;default:break e}if(S){let E=l.items[l.items.length-1];vP.isPair(E)&&(E=E.value??E.key),E.comment?E.comment+=`
|
|
71
|
+
`+S:E.comment=S,w.comment=w.comment.substring(S.length+1)}}if(!o&&!N&&!w.found){let S=x?e(r,x,w,n):t(r,w.end,N,null,w,n);l.items.push(S),d=S.range[2],jd(x)&&n(S.range,"BLOCK_IN_FLOW",Td)}else{r.atKey=!0;let S=w.end,E=k?e(r,k,w,n):t(r,S,b,null,w,n);jd(k)&&n(E.range,"BLOCK_IN_FLOW",Td),r.atKey=!1;let y=jg.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:x,offset:E.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(y.found){if(!o&&!w.found&&r.options.strict){if(N)for(let T of N){if(T===y.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}}w.start<y.found.offset-1024&&n(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source?.[0]===":"?n(x,"MISSING_CHAR",`Missing space after : in ${s}`):n(y.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=x?e(r,x,y,n):y.found?t(r,y.end,N,null,y,n):null;C?jd(x)&&n(C.range,"BLOCK_IN_FLOW",Td):y.comment&&(E.comment?E.comment+=`
|
|
72
|
+
`+y.comment:E.comment=y.comment);let O=new gP.Pair(E,C);if(r.options.keepSourceTokens&&(O.srcToken=g),o){let T=l;bP.mapIncludes(r,T.items,E)&&n(S,"DUPLICATE_KEY","Map keys must be unique"),T.items.push(O)}else{let T=new Tg.YAMLMap(r.schema);T.flow=!0,T.items.push(O);let Q=(C??E).range;T.range=[E.range[0],Q[1],Q[2]],l.items.push(T)}d=C?C.range[2]:y.end}}let p=o?"}":"]",[f,...m]=i.end,h=d;if(f?.source===p)h=f.offset+f.source.length;else{let v=s[0].toUpperCase()+s.substring(1),g=u?`${v} must end with a ${p}`:`${v} in block collection must be sufficiently indented and end with a ${p}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",g),f&&f.source.length!==1&&m.unshift(f)}if(m.length>0){let v=yP.resolveEnd(m,h,r.options.strict,n);v.comment&&(l.comment?l.comment+=`
|
|
73
|
+
`+v.comment:l.comment=v.comment),l.range=[i.offset,h,v.offset]}else l.range=[i.offset,h,h];return l}$g.resolveFlowCollection=kP});var Dg=R(Hg=>{"use strict";var SP=z(),EP=pe(),xP=jr(),CP=$r(),RP=Pg(),PP=Ag(),_P=Og();function $d(e,t,r,i,n,a){let o=r.type==="block-map"?RP.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?PP.resolveBlockSeq(e,t,r,i,a):_P.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function AP(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,p=>n(a,"TAG_RESOLVE_FAILED",p)):null;if(r.type==="block-seq"){let{anchor:p,newlineAfterProp:f}=i,m=p&&a?p.offset>a.offset?p:a:p??a;m&&(!f||f.offset<m.offset)&&n(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===xP.YAMLMap.tagName&&s==="map"||o===CP.YAMLSeq.tagName&&s==="seq")return $d(e,t,r,n,o);let c=t.schema.tags.find(p=>p.tag===o&&p.collection===s);if(!c){let p=t.schema.knownTags[o];if(p?.collection===s)t.schema.tags.push(Object.assign({},p,{default:!1})),c=p;else return p?n(a,"BAD_COLLECTION_TYPE",`${p.tag} used for ${s} collection, but expects ${p.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),$d(e,t,r,n,o)}let l=$d(e,t,r,n,o,c),u=c.resolve?.(l,p=>n(a,"TAG_RESOLVE_FAILED",p),t.options)??l,d=SP.isNode(u)?u:new EP.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Hg.composeCollection=AP});var Hd=R(Bg=>{"use strict";var Od=pe();function IP(e,t,r){let i=t.offset,n=TP(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Od.Scalar.BLOCK_FOLDED:Od.Scalar.BLOCK_LITERAL,o=t.source?jP(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let v=o[h][1];if(v===""||v==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
|
|
74
74
|
`.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return t.source&&(v+=t.source.length),{value:h,type:a,comment:n.comment,range:[i,v,v]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[v,g]=o[h];if(g===""||g==="\r")n.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&r(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=v.length),u=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+g.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",p="",f=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
|
|
75
|
-
`;for(let h=u;h<s;++h){let[v,g]=o[h];l+=v.length+g.length+1;let b=g[g.length-1]==="\r";if(b&&(g=g.slice(0,-1)),g&&v.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(b?2:1),"BAD_INDENT",N),v=""}a===
|
|
75
|
+
`;for(let h=u;h<s;++h){let[v,g]=o[h];l+=v.length+g.length+1;let b=g[g.length-1]==="\r";if(b&&(g=g.slice(0,-1)),g&&v.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(b?2:1),"BAD_INDENT",N),v=""}a===Od.Scalar.BLOCK_LITERAL?(d+=p+v.slice(c)+g,p=`
|
|
76
76
|
`):v.length>c||g[0]===" "?(p===" "?p=`
|
|
77
77
|
`:!f&&p===`
|
|
78
78
|
`&&(p=`
|
|
@@ -85,65 +85,69 @@ ${l}
|
|
|
85
85
|
`+o[h][0].slice(c);d[d.length-1]!==`
|
|
86
86
|
`&&(d+=`
|
|
87
87
|
`);break;default:d+=`
|
|
88
|
-
`}let m=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,m,m]}}function
|
|
88
|
+
`}let m=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,m,m]}}function TP({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let p=1;p<n.length;++p){let f=n[p];if(!s&&(f==="-"||f==="+"))s=f;else{let m=Number(f);!o&&m?o=m:c===-1&&(c=e+p)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let p=1;p<t.length;++p){let f=t[p];switch(f.type){case"space":l=!0;case"newline":d+=f.source.length;break;case"comment":r&&!l&&i(f,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=f.source.length,u=f.source.substring(1);break;case"error":i(f,"UNEXPECTED_TOKEN",f.message),d+=f.source.length;break;default:{let m=`Unexpected token in block scalar header: ${f.type}`;i(f,"UNEXPECTED_TOKEN",m);let h=f.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function jP(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Bg.resolveBlockScalar=IP});var Bd=R(Lg=>{"use strict";var Dd=pe(),$P=an();function OP(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(p,f,m)=>r(i+p,f,m);switch(n){case"scalar":s=Dd.Scalar.PLAIN,c=HP(a,l);break;case"single-quoted-scalar":s=Dd.Scalar.QUOTE_SINGLE,c=DP(a,l);break;case"double-quoted-scalar":s=Dd.Scalar.QUOTE_DOUBLE,c=BP(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let u=i+a.length,d=$P.resolveEnd(o,u,t,r);return{value:c,type:s,comment:d.comment,range:[i,u,d.offset]}}function HP(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),Fg(e)}function DP(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Fg(e.slice(1,-1)).replace(/''/g,"'")}function Fg(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
89
89
|
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
90
90
|
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let n=i[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;i=r.exec(e);)i[1]===""?a===`
|
|
91
91
|
`?n+=a:a=`
|
|
92
|
-
`:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function
|
|
92
|
+
`:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function BP(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
|
|
93
93
|
`))if(n===`
|
|
94
|
-
`){let{fold:a,offset:o}=
|
|
94
|
+
`){let{fold:a,offset:o}=FP(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=LP[a];if(o)r+=o;else if(a===`
|
|
95
95
|
`)for(a=e[i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="\r"&&e[i+1]===`
|
|
96
|
-
`)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=
|
|
96
|
+
`)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=qP(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
|
|
97
97
|
`&&!(o==="\r"&&e[i+2]===`
|
|
98
|
-
`)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function
|
|
98
|
+
`)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function FP(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
|
|
99
99
|
`||i==="\r")&&!(i==="\r"&&e[t+2]!==`
|
|
100
100
|
`);)i===`
|
|
101
101
|
`&&(r+=`
|
|
102
|
-
`),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var
|
|
103
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
102
|
+
`),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var LP={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
103
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function qP(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Lg.resolveFlowScalar=OP});var Vg=R(Mg=>{"use strict";var gi=z(),qg=pe(),MP=Hd(),VP=Bd();function WP(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?MP.resolveBlockScalar(e,t,i):VP.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[gi.SCALAR]:c?l=zP(e.schema,n,c,r,i):t.type==="scalar"?l=GP(e,n,t,i):l=e.schema[gi.SCALAR];let u;try{let d=l.resolve(n,p=>i(r??t,"TAG_RESOLVE_FAILED",p),e.options);u=gi.isScalar(d)?d:new qg.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",p),u=new qg.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 zP(e,t,r,i,n){if(r==="!")return e[gi.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[gi.SCALAR])}function GP({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[gi.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[gi.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}Mg.composeScalar=WP});var zg=R(Wg=>{"use strict";function JP(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Wg.emptyScalarPosition=JP});var Ug=R(Ld=>{"use strict";var UP=da(),KP=z(),YP=Dg(),Gg=Vg(),XP=an(),QP=zg(),ZP={composeNode:Jg,composeEmptyNode:Fd};function Jg(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=e_(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Gg.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=YP.composeCollection(ZP,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(d){let p=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",p)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Fd(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!KP.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Fd(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:QP.emptyScalarPosition(t,r,i),indent:-1,source:""},d=Gg.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 e_({options:e},{offset:t,source:r,end:i},n){let a=new UP.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=XP.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ld.composeEmptyNode=Fd;Ld.composeNode=Jg});var Xg=R(Yg=>{"use strict";var t_=Ra(),Kg=Ug(),r_=an(),i_=Ia();function n_(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new t_.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=i_.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,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?Kg.composeNode(l,n,u,o):Kg.composeEmptyNode(l,u.end,i,null,u,o);let d=c.contents.range[2],p=r_.resolveEnd(a,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[r,d,p.offset],c}Yg.composeDoc=n_});var Md=R(ew=>{"use strict";var a_=os("process"),o_=Ru(),s_=Ra(),Ta=Aa(),Qg=z(),c_=Xg(),l_=an();function ja(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function Zg(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
|
|
104
104
|
|
|
105
105
|
`:`
|
|
106
|
-
`)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var
|
|
107
|
-
${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(
|
|
106
|
+
`)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var qd=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=ja(r);a?this.warnings.push(new Ta.YAMLWarning(o,i,n)):this.errors.push(new Ta.YAMLParseError(o,i,n))},this.directives=new o_.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Zg(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
|
|
107
|
+
${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(Qg.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Qg.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
|
|
108
108
|
${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
|
|
109
|
-
${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
110
|
-
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new
|
|
109
|
+
${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Zg(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(a_.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=ja(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=c_.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new Ta.YAMLParseError(ja(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Ta.YAMLParseError(ja(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=l_.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
|
|
110
|
+
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Ta.YAMLParseError(ja(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new s_.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};ew.Composer=qd});var iw=R(tc=>{"use strict";var u_=Hd(),d_=Bd(),p_=Aa(),tw=va();function f_(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new p_.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return d_.resolveFlowScalar(e,t,i);case"block-scalar":return u_.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function h_(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=tw.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
|
|
111
111
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
112
112
|
`),u=s.substring(0,l),d=s.substring(l+1)+`
|
|
113
|
-
`,p=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return
|
|
114
|
-
`}),{type:"block-scalar",offset:a,indent:i,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function
|
|
113
|
+
`,p=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return rw(p,c)||p.push({type:"newline",offset:-1,indent:i,source:`
|
|
114
|
+
`}),{type:"block-scalar",offset:a,indent:i,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function m_(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=tw.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">":v_(e,c);break;case'"':Vd(e,c,"double-quoted-scalar");break;case"'":Vd(e,c,"single-quoted-scalar");break;default:Vd(e,c,"scalar")}}function v_(e,t){let r=t.indexOf(`
|
|
115
115
|
`),i=t.substring(0,r),n=t.substring(r+1)+`
|
|
116
|
-
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];
|
|
117
|
-
`});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
|
|
118
|
-
`};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}
|
|
116
|
+
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];rw(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
117
|
+
`});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 rw(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Vd(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
118
|
+
`};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}tc.createScalarToken=h_;tc.resolveAsScalar=f_;tc.setScalarValue=m_});var aw=R(nw=>{"use strict";var g_=e=>"type"in e?ic(e):rc(e);function ic(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=ic(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=rc(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=rc(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=rc(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function rc({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=ic(t)),r)for(let a of r)n+=a.source;return i&&(n+=ic(i)),n}nw.stringify=g_});var lw=R(cw=>{"use strict";var Wd=Symbol("break visit"),w_=Symbol("skip children"),ow=Symbol("remove item");function wi(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),sw(Object.freeze([]),e,t)}wi.BREAK=Wd;wi.SKIP=w_;wi.REMOVE=ow;wi.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};wi.parentCollection=(e,t)=>{let r=wi.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function sw(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=sw(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Wd)return Wd;s===ow&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}cw.visit=wi});var nc=R(Me=>{"use strict";var zd=iw(),y_=aw(),N_=lw(),Gd="\uFEFF",Jd="",Ud="",Kd="",b_=e=>!!e&&"items"in e,k_=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function S_(e){switch(e){case Gd:return"<BOM>";case Jd:return"<DOC>";case Ud:return"<FLOW_END>";case Kd:return"<SCALAR>";default:return JSON.stringify(e)}}function E_(e){switch(e){case Gd:return"byte-order-mark";case Jd:return"doc-mode";case Ud:return"flow-error-end";case Kd:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
119
119
|
`:case`\r
|
|
120
|
-
`: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}Me.createScalarToken=
|
|
121
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
122
|
-
\r `),
|
|
120
|
+
`: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}Me.createScalarToken=zd.createScalarToken;Me.resolveAsScalar=zd.resolveAsScalar;Me.setScalarValue=zd.setScalarValue;Me.stringify=y_.stringify;Me.visit=N_.visit;Me.BOM=Gd;Me.DOCUMENT=Jd;Me.FLOW_END=Ud;Me.SCALAR=Kd;Me.isCollection=b_;Me.isScalar=k_;Me.prettyToken=S_;Me.tokenType=E_});var Qd=R(dw=>{"use strict";var $a=nc();function Nt(e){switch(e){case void 0:case" ":case`
|
|
121
|
+
`:case"\r":case" ":return!0;default:return!1}}var uw=new Set("0123456789ABCDEFabcdef"),x_=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ac=new Set(",[]{}"),C_=new Set(` ,[]{}
|
|
122
|
+
\r `),Yd=e=>!e||C_.has(e),Xd=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
|
|
123
123
|
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
124
124
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
|
|
125
125
|
`||!n&&!this.atEnd)return t+i+1}return r===`
|
|
126
126
|
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Nt(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(`
|
|
127
|
-
`,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]
|
|
127
|
+
`,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]===$a.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield $a.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Nt(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Nt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Nt(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Yd),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&Nt(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield $a.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(Yd),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Nt(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
|
|
128
128
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
|
|
129
129
|
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Nt(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
|
|
130
130
|
`:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
131
131
|
`)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
132
132
|
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
|
|
133
133
|
`;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
134
|
-
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield
|
|
134
|
+
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield $a.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(Nt(a)||t&&ac.has(a))break;r=i}else if(Nt(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
|
|
135
135
|
`?(i+=1,n=`
|
|
136
|
-
`,a=this.buffer[i+1]):r=i),a==="#"||t&&
|
|
137
|
-
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&
|
|
136
|
+
`,a=this.buffer[i+1]):r=i),a==="#"||t&&ac.has(a))break;if(n===`
|
|
137
|
+
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&ac.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield $a.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Yd),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Nt(i)||r&&ac.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!Nt(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(x_.has(r))r=this.buffer[++t];else if(r==="%"&&uw.has(this.buffer[t+1])&&uw.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
138
138
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
139
|
-
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};
|
|
139
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};dw.Lexer=Xd});var ep=R(pw=>{"use strict";var Zd=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};pw.LineCounter=Zd});var rp=R(gw=>{"use strict";var R_=os("process"),fw=nc(),P_=Qd();function Or(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function hw(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 vw(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 oc(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 on(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 sc(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function mw(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Or(t.start,"explicit-key-ind")&&!Or(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,vw(t.value)?t.value.end?sc(t.value.end,t.sep):t.value.end=t.sep:sc(t.start,t.sep),delete t.sep)}var tp=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 P_.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,R_.env.LOG_TOKENS&&console.log("|",fw.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=fw.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&mw(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&hw(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{hw(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=oc(this.peek(2)),i=on(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
|
|
140
140
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
141
|
-
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){
|
|
141
|
+
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){sc(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Or(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(vw(r.key)&&!Or(r.sep,"newline")){let o=on(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Or(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=on(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Or(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Or(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){sc(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Or(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=oc(i),a=on(n);mw(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
|
|
142
142
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
143
|
-
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=nc(t),i=an(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=nc(t),i=an(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};fw.Parser=Qd});var ww=R(Oa=>{"use strict";var hw=Fd(),w_=Ca(),$a=_a(),y_=Du(),N_=z(),b_=Xd(),mw=Zd();function vw(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new b_.LineCounter||null,prettyErrors:t}}function k_(e,t={}){let{lineCounter:r,prettyErrors:i}=vw(t),n=new mw.Parser(r?.addNewLine),a=new hw.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach($a.prettifyError(e,r)),s.warnings.forEach($a.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function gw(e,t={}){let{lineCounter:r,prettyErrors:i}=vw(t),n=new mw.Parser(r?.addNewLine),a=new hw.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 $a.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach($a.prettifyError(e,r)),o.warnings.forEach($a.prettifyError(e,r))),o}function S_(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=gw(e,r);if(!n)return null;if(n.warnings.forEach(a=>y_.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function E_(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return N_.isDocument(e)&&!i?e.toString(r):new w_.Document(e,i,r).toString(r)}Oa.parse=S_;Oa.parseAllDocuments=k_;Oa.parseDocument=gw;Oa.stringify=E_});var Bt=R(U=>{"use strict";var x_=Fd(),C_=Ca(),R_=yd(),ep=_a(),P_=ua(),Hr=z(),__=Ir(),A_=pe(),I_=jr(),T_=$r(),j_=rc(),$_=Kd(),O_=Xd(),H_=Zd(),oc=ww(),yw=oa();U.Composer=x_.Composer;U.Document=C_.Document;U.Schema=R_.Schema;U.YAMLError=ep.YAMLError;U.YAMLParseError=ep.YAMLParseError;U.YAMLWarning=ep.YAMLWarning;U.Alias=P_.Alias;U.isAlias=Hr.isAlias;U.isCollection=Hr.isCollection;U.isDocument=Hr.isDocument;U.isMap=Hr.isMap;U.isNode=Hr.isNode;U.isPair=Hr.isPair;U.isScalar=Hr.isScalar;U.isSeq=Hr.isSeq;U.Pair=__.Pair;U.Scalar=A_.Scalar;U.YAMLMap=I_.YAMLMap;U.YAMLSeq=T_.YAMLSeq;U.CST=j_;U.Lexer=$_.Lexer;U.LineCounter=O_.LineCounter;U.Parser=H_.Parser;U.parse=oc.parse;U.parseAllDocuments=oc.parseAllDocuments;U.parseDocument=oc.parseDocument;U.stringify=oc.stringify;U.visit=yw.visit;U.visitAsync=yw.visitAsync});import tp from"path";function F_(e){return e.toLowerCase().startsWith(".env")}function Ft(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>F_(i))?"environment-file":r.some(i=>B_.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>D_.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function rp(e,t){let r=Ft(t);if(r)return r;let i=tp.resolve(e.projectRoot,...t.split("/")),n=tp.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===tp.resolve(e.configFile)?"native-runtime":null}var D_,B_,Ha=I(()=>{"use strict";D_=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),B_=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Dr(e){return e!==0&&e!==0n&&e!=="0"}function Xe(e,t){return Dr(e.dev)&&Dr(t.dev)&&Dr(e.ino)&&Dr(t.ino)}function G(e,t){let r=Dr(e.dev)&&Dr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Dr(e.ino)&&Dr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Da=I(()=>{"use strict"});var Lt=I(()=>{"use strict";Da()});import{createHash as L_}from"node:crypto";import{promises as bt}from"node:fs";import nt from"node:path";import{TextDecoder as q_}from"node:util";function ip(e,t){let r=nt.relative(e,t);return r===""||!nt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${nt.sep}`)}function M_(e){let t=nt.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})||nt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Ft(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function V_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function W_(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function sc(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Nw(e){let t=await bt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await bt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function z_(e,t){let r=nt.resolve(e),i=nt.resolve(t);if(!ip(r,i))throw new Error("Native artifact path is outside its root");let n=[await Nw(r)],a=r;for(let o of nt.relative(r,i).split(nt.sep).filter(Boolean)){a=nt.join(a,o);let s=await Nw(a);if(!ip(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function bw(e){for(let t of e){let r=await bt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!W_(t,r)||await bt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function re(e){let t=M_(e.ref),r=e.maxBytes===null?null:V_(e.maxBytes??np),i=nt.resolve(e.root,...t.split("/")),n=await z_(e.root,nt.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await bt.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await bt.realpath(i);if(!ip(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await bt.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),bt.lstat(i),bt.realpath(i)]);if(await bw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!sc(a,c)||!sc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],p=0,f=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?f.length:r+1-p,N=await s.read(f,0,Math.min(f.length,k),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,r!==null&&p>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(f.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),bt.lstat(i),bt.realpath(i)]);if(await bw(n),!h.isFile()||h.isSymbolicLink()||v!==o||!sc(c,m)||!sc(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,p),b;try{b=new q_("utf-8",{fatal:!0}).decode(g)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:p,hash:e.includeHash===!1?null:L_("sha256").update(g).digest("hex"),text:b}}finally{await s.close()}}var np,at=I(()=>{"use strict";Ha();Lt();np=1024*1024});import{promises as op}from"node:fs";async function sp(e,t){let r;for(let i=0;i<=ap.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===ap.length||!G_.has(a??""))throw n;await new Promise(o=>setTimeout(o,ap[i]))}throw r}async function cp(e,t){await sp(()=>op.rename(e,t),`rename ${t}`)}async function lp(e){await sp(()=>op.unlink(e),`unlink ${e}`)}async function up(e,t){await sp(()=>op.link(e,t),`link ${t}`)}var G_,ap,dp=I(()=>{"use strict";G_=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),ap=[50,100,200]});import{randomUUID as J_}from"crypto";import{promises as $e}from"fs";import kt from"path";function cc(e,t){let r=kt.relative(e,t);return r===""||!kt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${kt.sep}`)}function U_(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function lc(e,t){return G({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function K_(e,t){return lc(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function kw(e){let t=await $e.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 $e.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function on(e){for(let t of e){let r=await $e.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!U_(t,r)||await $e.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Y_(e,t,r){let[i,n]=await Promise.all([$e.lstat(e),$e.realpath(e),r?on(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!lc(i,t)||r&&!cc(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function X_(e,t){let r=kt.resolve(e),i=kt.resolve(t);if(!cc(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await kw(r)],a=kt.relative(r,i).split(kt.sep).filter(Boolean),o=r;for(let s of a){await on(n),o=kt.join(o,s);try{await $e.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await kw(o);if(!cc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await on(n),n}async function Q_(e){let t;try{t=await $e.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function Z_(e,t,r={}){let i=kt.dirname(e),n=r.containedRoot?await X_(r.containedRoot,i):null;n||await $e.mkdir(i,{recursive:!0});let a=kt.join(i,`.${kt.basename(e)}.${J_()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await $e.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([$e.lstat(a),$e.realpath(a)]);if(await on(n),!l.isFile()||l.isSymbolicLink()||!lc(s,l)||!cc(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(),!lc(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await Y_(a,c,n),await r.beforeCommit?.(),n){await on(n);let l=await $e.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!K_(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await up(a,e),await lp(a)):await cp(a,e),await Q_(i)}catch(l){if(await o?.close(),!n)await $e.rm(a,{force:!0});else try{await on(n),await $e.rm(a,{force:!0})}catch{}throw l}}async function qt(e,t,r={}){await Z_(e,t,r)}async function Oe(e,t,r={}){await qt(e,JSON.stringify(t,null,2)+`
|
|
144
|
-
`,r)}var oe=I(()=>{"use strict";
|
|
145
|
-
|
|
146
|
-
`)}var pp,eA,tA,Sw,fp,yi=I(()=>{"use strict";pp={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:"验证预期"}},eA={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:"结论"}},tA={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:"结论"}},Sw=new Map,fp=new Map;for(let e of Object.keys(pp)){for(let[t,r]of Object.entries(pp[e]))Sw.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(eA[e]))fp.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(tA[e]))fp.set(r.toLocaleLowerCase("en-US"),t)}});import Br from"path";function sA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Br.posix.isAbsolute(r)||Br.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Ni(e){let t=sA(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Tw(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function mc(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Br.posix.isAbsolute(i)||Br.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function sr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function jw(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function vc(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>fc)throw new Error(`${t} exceeds ${fc} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>hc)throw new Error(`${t} contains more than ${hc} wildcard tokens`);return e}function _w(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>vc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Ba(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Aw(e,t,r){let i=Ba(e,t,r);if(i>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return i}function cA(e){if(e===void 0)return{...He,include:[...He.include],exclude:[...He.exclude]};let t=sr(e,"native.snapshot");return{include:_w(t.include,"native.snapshot.include",He.include),exclude:_w(t.exclude,"native.snapshot.exclude",He.exclude),max_files:Ba(t.max_files,He.max_files,"native.snapshot.max_files"),max_total_bytes:Ba(t.max_total_bytes,He.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Ba(t.max_duration_ms,He.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:Ba(t.max_selection_records,He.max_selection_records,"native.snapshot.max_selection_records")}}function lA(e){if(e===void 0)return;let t=sr(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=sr(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:r,fromArtifactRoot:Ni(i),toArtifactRoot:Ni(n),stage:a,...o?{cleanup:o}:{}}}function uA(e){if(e===void 0)return;let t=sr(e,"native.finish");if(t.pull_request===void 0)return{};let r=sr(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Br.posix.isAbsolute(i[0])||Br.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??iA;if(!Number.isSafeInteger(n)||n<1||n>Pw)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Pw}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function dA(e,t={}){let r=sr(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??mp;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=lA(r.pending_root_move),l=uA(r.finish);return{artifact_root:Ni(i),language:jw(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:cA(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function pA(e){let t=sr(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");let a=t.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:Tw(t.artifact_layout),language:jw(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function fA(e){let r=sr(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>mc(i,`hook.allow_paths[${n}]`)))]}}function hA(e){if(e===void 0)return{...pc};let t=sr(e,"memory"),r=t.learning??pc.learning,i=t.retrieval??pc.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function vp(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function mA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Br.posix.isAbsolute(r)||Br.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>xw)throw new Error(`${t} exceeds ${xw} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>Cw)throw new Error(`${t} contains more than ${Cw} wildcard tokens`);return r}function vA(e){let t=vp(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>mA(n,`knowledge.local.include[${a}]`)))],max_file_mb:Aw(t.max_file_mb,Rw.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Aw(t.max_total_mb,Rw.max_total_mb,"knowledge.local.max_total_mb")};if(i.max_file_mb>i.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return i}function gA(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function wA(e){let t=vp(e,"knowledge.remote"),r=gA(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function yA(e){if(e===void 0)return{...Iw};let t=vp(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:vA(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:wA(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function NA(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function bA(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(p=>p!=="native"&&p!=="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:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function La(e,t={}){let r=(0,hp.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=NA(n.ambient_resume),o=n.hook===void 0?void 0:fA(n.hook),s=hA(n.memory),c=yA(n.knowledge),l=n.native===void 0?void 0:dA(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:pA(n.classic),d=bA(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function gc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...pc},knowledge:{...Iw},native:{artifact_root:Ni(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:mp,snapshot:{...He,include:[...He.include],exclude:[...He.exclude]}}}}var hp,Fa,fc,hc,xw,Cw,mp,pc,Rw,Iw,iA,Pw,nA,aA,oA,He,Fr=I(()=>{"use strict";hp=ir(Bt(),1),Fa=Number.MAX_SAFE_INTEGER,fc=1024,hc=64,xw=1024,Cw=64,mp=5,pc={learning:!0,retrieval:!0},Rw={include:[],max_file_mb:1,max_total_mb:32},Iw={provider:"local"},iA=12e4,Pw=6e5,nA=[".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/**"],aA=["**/.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"],oA=[...nA,...aA].sort((e,t)=>e.localeCompare(t,"en")),He={include:["**/*"],exclude:[...oA],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as wc,promises as bi}from"fs";function gp(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function $w(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function qa(e){return{dev:e.dev,ino:e.ino,birthtime:gp(e)}}function yc(e,t){let r=qa(e),i=qa(t);return Xe(r,i)?G(r,i):G(r,i)&&gp(e)===gp(t)&&$w(e)===$w(t)&&e.size===t.size}async function ki(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await bi.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new St("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new St("too-large",`${i} exceeds ${t} bytes`);let o=await bi.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:qa(a)});let s=process.platform==="win32"?wc.O_RDONLY:wc.O_RDONLY|wc.O_NOFOLLOW|wc.O_NONBLOCK,c;try{c=await bi.open(e,s)}catch(l){throw l.code==="ELOOP"?new St("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),bi.lstat(e,{bigint:n}),bi.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!yc(a,l)||!yc(a,u))throw new St("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:qa(l)}),await r.hooks?.afterOpen?.();let p=[],f=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-f,{bytesRead:k}=await c.read(m,0,Math.min(m.length,b),null);if(k===0)break;if(f+=k,f>t)throw new St("too-large",`${i} exceeds ${t} bytes`);p.push(Buffer.from(m.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat({bigint:n}),bi.lstat(e,{bigint:n}),bi.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!yc(a,h)||!yc(a,v))throw new St("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:qa(h)}),{bytes:Buffer.concat(p,f),stat:h,realPath:g}}finally{await c.close()}}var St,Ma=I(()=>{"use strict";Da();St=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as Nc}from"fs";import Lr from"path";function kA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function wp(e,t){let r=Lr.relative(e,t);return r===""||!Lr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Lr.sep}`)}async function Ow(e,t){let r=Lr.resolve(e),i=await Nc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Nc.realpath(r)}async function Hw(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Lr.join(n,r[a]);let o;try{o=await Nc.lstat(n)}catch(u){if(kA(u))return{exists:!1,kind:"missing"};throw u}let s=Lr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await Nc.realpath(n);if(!wp(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function sn(e,t,r){let i=mc(t,r.label),n=Lr.resolve(e),a=await Ow(n,r.label),o=i.split("/"),s=Lr.resolve(n,...o);if(!wp(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Hw(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Mt(e,t,r,i){let n=await sn(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Ow(n.projectRoot,i.label);return ki(n.target,r,{...i,verify:async(o,s)=>{if(!wp(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Hw(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var cr=I(()=>{"use strict";Ma();Fr()});import{createHash as SA}from"crypto";function EA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function bc(e,t={}){return(await kc(e,t)).document}async function xA(e){try{return(await Mt(e,Va,Fa,{label:Va})).bytes}catch(t){if(EA(t))return null;throw t}}function CA(e){return e?{exists:!0,sha256:SA("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function kc(e,t={}){let r=await xA(e);return{document:r?La(r.toString("utf8"),t):null,identity:CA(r)}}async function yp(e){return(await bc(e))?.config??null}var Va,cn=I(()=>{"use strict";Fr();cr();Va=".comet/config.yaml"});var ln=I(()=>{"use strict";dp();Da()});var B1,Np=I(()=>{"use strict";ln();cn();cr();B1=16*1024});var Sp=I(()=>{"use strict";ln();Fr();cn();cr();Np()});import{existsSync as Bw,promises as qr}from"fs";import B from"path";import IA from"os";async function Ep(e){try{return await qr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jA(e){try{let t=await qr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function dn(e,t){let r=B.relative(e,t);return r===""||!B.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${B.sep}`)}async function un(e){let t=[],r=e;for(;!await Ep(r);){let n=B.dirname(r);if(n===r)break;t.push(B.basename(r)),r=n}let i=await qr.realpath(r);return B.resolve(i,...t.reverse())}async function xp(e){try{return(await qr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ec(e){let t=B.resolve(e);try{(await qr.stat(t)).isDirectory()||(t=B.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=B.resolve(IA.homedir());for(;;){if(!(t===i&&r!==i)){let o=B.join(t,...Sc.split("/")),s=t===r||await jA(o);if(await Ep(o)&&s)return t}if(await Ep(B.join(t,".git")))return t;let a=B.dirname(t);if(a===t)return r;t=a}}function xc(e){return Ni(e)}async function $A(e,t){let r=xc(t),i=B.resolve(e,...r.split("/")),n=await qr.realpath(e),a=await un(i);if(!dn(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Vt(e,t){let r=xc(t),i=await $A(e,r),n=B.join(i,"comet");if(await xp(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([un(i),un(n)]);if(!dn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=B.resolve(e),c=B.join(s,".comet","runtime","native");if(await xp(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([qr.realpath(s),un(c)]);if(!dn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:B.join(e,...Sc.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:B.join(n,"specs"),changesDir:B.join(n,"changes"),archiveDir:B.join(n,"archive"),runtimeDir:c,changesRuntimeDir:B.join(c,"changes"),locksDir:B.join(c,"locks"),transactionsDir:B.join(c,"transactions")}}function Cp(e){if(!TA.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Et(e,t){Cp(t);let r=B.join(e.changesRuntimeDir,t);if(!q(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Lw(e,t){Cp(t);let r=B.join(e.changesDir,t,"runtime");if(!q(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Y(e,t){let r=Et(e,t);if(Bw(r))return r;let i=Lw(e,t);return Bw(i)?i:r}function za(e,t){Cp(t);let r=B.join(e.changesDir,t),i=Y(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:B.join(r,"brief.md"),childrenPath:B.join(r,"children.yaml"),specsDir:B.join(r,"specs"),verificationPath:B.join(r,"verification.md"),statePath:B.join(r,"comet-state.yaml"),runtimeDir:i,runtimeStatePath:B.join(i,"state.json")}}async function Fw(e){try{let t=await qr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Rp(e,t){let r=Et(e,t),i=Lw(e,t),[n,a]=await Promise.all([Fw(r),Fw(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function Mr(e,t){if(!t.startsWith("runtime/")||B.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=B.resolve(e,...t.slice(8).split("/"));if(!q(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function Ne(e,t){let r=B.resolve(t);if(q(e.runtimeDir,r))return e.runtimeDir;if(q(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function q(e,t){return dn(B.resolve(e),B.resolve(t))}async function V(e,t){let r=B.resolve(e),i=B.resolve(t);if(!dn(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await xp(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([un(r),un(i)]);if(!dn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Sc,TA,K=I(()=>{"use strict";Fr();Sc=".comet/config.yaml",TA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function HA(e="docs",t="en"){return gc(e,t)}async function xe(e){let t=(await bc(e))?.config??null;return t?.native?t:null}async function Rc(e){let t=await xe(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function qw(e){let t=await Ec(e.startPath),r=await xe(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Sc} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?xc(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??HA(i??"docs"),a=await Vt(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Pp,Cc,Qe=I(()=>{"use strict";Fr();cn();Sp();oe();K();Pp=He,Cc=vc});import{createHash as Ap,randomUUID as DA}from"node:crypto";import{promises as Ze}from"node:fs";import BA from"node:os";import Ve from"node:path";async function _p(e,t){let r=await Ze.lstat(e,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(t))throw new Error("Invalid process probe cache");let i=await Ze.readFile(e),n=await Ze.lstat(e,{bigint:!0});if(r.ino!==n.ino||r.ctimeNs!==n.ctimeNs||r.size!==n.size)throw new Error("Process probe cache changed");return i}async function Ww(e){try{let t=JSON.parse((await _p(Ve.join(e,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(t.file??""))return null;let r=Ve.join(e,t.file),i=await _p(r,65536);return Ap("sha256").update(i).digest("hex")===t.hash?r:null}catch{return null}}async function qA(e,t){let r,i=DA(),n=Ve.join(e,`probe-${i}.cs`),a=Ve.join(e,`probe-${i}.exe`),o=Ve.join(e,`probe-${i}.json`);try{if(await Ze.mkdir(e,{recursive:!0,mode:448}),(await Ze.lstat(e)).isSymbolicLink())return null;r=await Ze.open(Ve.join(e,"prepare.lock"),"wx",384);let s=await Ww(e);if(s)return s;await Ze.writeFile(n,Vw,{flag:"wx",mode:384});let c;for(let u of["Framework64","Framework"]){let d=Ve.join(t,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await Ze.access(d),c=d;break}catch{}}if(!c)return null;await Er(c,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,n],{timeoutMs:1500,maxBufferBytes:4096});let l=Ap("sha256").update(await _p(a,65536)).digest("hex");return await Ze.writeFile(o,JSON.stringify({file:Ve.basename(a),hash:l}),{flag:"wx",mode:384}),await Ze.rename(o,Ve.join(e,"probe.json")),a}catch{return null}finally{await Ze.unlink(n).catch(()=>{}),await Ze.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await Ze.unlink(Ve.join(e,"prepare.lock")).catch(()=>{}))}}async function Mw(e,t,r){try{let i=await Er(Ve.join(t,"System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"get","creationdate","/value"],{timeoutMs:300,maxBufferBytes:4096,signal:r}),n=/^CreationDate=(\S+)/mu.exec(i);if(n)return`win32-wmic:${n[1]}`}catch{}if(r.aborted)return null;try{let n=(await Er(Ve.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:1e3,maxBufferBytes:4096,signal:r})).trim();return/^\d+$/u.test(n)?`win32-ps:${n}`:null}catch{return null}}function MA(e,t){let r=Pc.get(e);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:qA(e,t),retryAfter:1/0};return Pc.set(e,i),i.promise.then(n=>{Pc.get(e)===i&&(n?Pc.delete(e):i.retryAfter=performance.now()+LA)}),i.promise}async function zw(e,t={}){if(!Number.isSafeInteger(e)||e<=0)return null;let r=t.systemRoot??process.env.SystemRoot??"C:\\Windows",i=Ve.join(t.cacheRoot??Ve.join(BA.tmpdir(),"comet-process-identity"),FA),n=async l=>{if(!l)return null;try{let d=(await Er(l,[String(e)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await Ww(i);if(a){let l=await n(a);return l||Mw(e,r,new AbortController().signal)}let o=MA(i,r),s=new AbortController,c=l=>{if(!l)throw new Error("Probe unavailable");return l};try{return await Promise.any([o.then(n).then(c),Mw(e,r,s.signal).then(c)])}catch{return null}finally{s.abort()}}var Vw,FA,LA,Pc,Gw=I(()=>{"use strict";Ji();Vw=`using System;
|
|
143
|
+
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=oc(t),i=on(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=oc(t),i=on(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};gw.Parser=tp});var kw=R(Ha=>{"use strict";var ww=Md(),__=Ra(),Oa=Aa(),A_=Lu(),I_=z(),T_=ep(),yw=rp();function Nw(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new T_.LineCounter||null,prettyErrors:t}}function j_(e,t={}){let{lineCounter:r,prettyErrors:i}=Nw(t),n=new yw.Parser(r?.addNewLine),a=new ww.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Oa.prettifyError(e,r)),s.warnings.forEach(Oa.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function bw(e,t={}){let{lineCounter:r,prettyErrors:i}=Nw(t),n=new yw.Parser(r?.addNewLine),a=new ww.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 Oa.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Oa.prettifyError(e,r)),o.warnings.forEach(Oa.prettifyError(e,r))),o}function $_(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=bw(e,r);if(!n)return null;if(n.warnings.forEach(a=>A_.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function O_(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return I_.isDocument(e)&&!i?e.toString(r):new __.Document(e,i,r).toString(r)}Ha.parse=$_;Ha.parseAllDocuments=j_;Ha.parseDocument=bw;Ha.stringify=O_});var Bt=R(U=>{"use strict";var H_=Md(),D_=Ra(),B_=kd(),ip=Aa(),F_=da(),Hr=z(),L_=Ir(),q_=pe(),M_=jr(),V_=$r(),W_=nc(),z_=Qd(),G_=ep(),J_=rp(),cc=kw(),Sw=sa();U.Composer=H_.Composer;U.Document=D_.Document;U.Schema=B_.Schema;U.YAMLError=ip.YAMLError;U.YAMLParseError=ip.YAMLParseError;U.YAMLWarning=ip.YAMLWarning;U.Alias=F_.Alias;U.isAlias=Hr.isAlias;U.isCollection=Hr.isCollection;U.isDocument=Hr.isDocument;U.isMap=Hr.isMap;U.isNode=Hr.isNode;U.isPair=Hr.isPair;U.isScalar=Hr.isScalar;U.isSeq=Hr.isSeq;U.Pair=L_.Pair;U.Scalar=q_.Scalar;U.YAMLMap=M_.YAMLMap;U.YAMLSeq=V_.YAMLSeq;U.CST=W_;U.Lexer=z_.Lexer;U.LineCounter=G_.LineCounter;U.Parser=J_.Parser;U.parse=cc.parse;U.parseAllDocuments=cc.parseAllDocuments;U.parseDocument=cc.parseDocument;U.stringify=cc.stringify;U.visit=Sw.visit;U.visitAsync=Sw.visitAsync});import np from"path";function Y_(e){return e.toLowerCase().startsWith(".env")}function Ft(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Y_(i))?"environment-file":r.some(i=>K_.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>U_.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function ap(e,t){let r=Ft(t);if(r)return r;let i=np.resolve(e.projectRoot,...t.split("/")),n=np.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===np.resolve(e.configFile)?"native-runtime":null}var U_,K_,Da=I(()=>{"use strict";U_=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),K_=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Dr(e){return e!==0&&e!==0n&&e!=="0"}function Xe(e,t){return Dr(e.dev)&&Dr(t.dev)&&Dr(e.ino)&&Dr(t.ino)}function G(e,t){let r=Dr(e.dev)&&Dr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Dr(e.ino)&&Dr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Ba=I(()=>{"use strict"});var Lt=I(()=>{"use strict";Ba()});import{createHash as X_}from"node:crypto";import{promises as bt}from"node:fs";import nt from"node:path";import{TextDecoder as Q_}from"node:util";function op(e,t){let r=nt.relative(e,t);return r===""||!nt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${nt.sep}`)}function Z_(e){let t=nt.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})||nt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Ft(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function eA(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function tA(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function lc(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Ew(e){let t=await bt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await bt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function rA(e,t){let r=nt.resolve(e),i=nt.resolve(t);if(!op(r,i))throw new Error("Native artifact path is outside its root");let n=[await Ew(r)],a=r;for(let o of nt.relative(r,i).split(nt.sep).filter(Boolean)){a=nt.join(a,o);let s=await Ew(a);if(!op(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function xw(e){for(let t of e){let r=await bt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!tA(t,r)||await bt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function re(e){let t=Z_(e.ref),r=e.maxBytes===null?null:eA(e.maxBytes??sp),i=nt.resolve(e.root,...t.split("/")),n=await rA(e.root,nt.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await bt.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await bt.realpath(i);if(!op(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await bt.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),bt.lstat(i),bt.realpath(i)]);if(await xw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!lc(a,c)||!lc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],p=0,f=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?f.length:r+1-p,N=await s.read(f,0,Math.min(f.length,k),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,r!==null&&p>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(f.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),bt.lstat(i),bt.realpath(i)]);if(await xw(n),!h.isFile()||h.isSymbolicLink()||v!==o||!lc(c,m)||!lc(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,p),b;try{b=new Q_("utf-8",{fatal:!0}).decode(g)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:p,hash:e.includeHash===!1?null:X_("sha256").update(g).digest("hex"),text:b}}finally{await s.close()}}var sp,at=I(()=>{"use strict";Da();Lt();sp=1024*1024});import{promises as lp}from"node:fs";async function up(e,t){let r;for(let i=0;i<=cp.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===cp.length||!iA.has(a??""))throw n;await new Promise(o=>setTimeout(o,cp[i]))}throw r}async function dp(e,t){await up(()=>lp.rename(e,t),`rename ${t}`)}async function pp(e){await up(()=>lp.unlink(e),`unlink ${e}`)}async function fp(e,t){await up(()=>lp.link(e,t),`link ${t}`)}var iA,cp,hp=I(()=>{"use strict";iA=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),cp=[50,100,200]});import{randomUUID as nA}from"crypto";import{promises as $e}from"fs";import kt from"path";function uc(e,t){let r=kt.relative(e,t);return r===""||!kt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${kt.sep}`)}function aA(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function dc(e,t){return G({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function oA(e,t){return dc(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Cw(e){let t=await $e.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 $e.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function sn(e){for(let t of e){let r=await $e.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!aA(t,r)||await $e.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function sA(e,t,r){let[i,n]=await Promise.all([$e.lstat(e),$e.realpath(e),r?sn(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!dc(i,t)||r&&!uc(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function cA(e,t){let r=kt.resolve(e),i=kt.resolve(t);if(!uc(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Cw(r)],a=kt.relative(r,i).split(kt.sep).filter(Boolean),o=r;for(let s of a){await sn(n),o=kt.join(o,s);try{await $e.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Cw(o);if(!uc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await sn(n),n}async function lA(e){let t;try{t=await $e.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function uA(e,t,r={}){let i=kt.dirname(e),n=r.containedRoot?await cA(r.containedRoot,i):null;n||await $e.mkdir(i,{recursive:!0});let a=kt.join(i,`.${kt.basename(e)}.${nA()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await $e.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([$e.lstat(a),$e.realpath(a)]);if(await sn(n),!l.isFile()||l.isSymbolicLink()||!dc(s,l)||!uc(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(),!dc(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await sA(a,c,n),await r.beforeCommit?.(),n){await sn(n);let l=await $e.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!oA(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await fp(a,e),await pp(a)):await dp(a,e),await lA(i)}catch(l){if(await o?.close(),!n)await $e.rm(a,{force:!0});else try{await sn(n),await $e.rm(a,{force:!0})}catch{}throw l}}async function qt(e,t,r={}){await uA(e,t,r)}async function Oe(e,t,r={}){await qt(e,JSON.stringify(t,null,2)+`
|
|
144
|
+
`,r)}var oe=I(()=>{"use strict";hp();Lt()});function Rw(e,t){return mp[e][t]}function pc(e){return Pw.get(e.trim().toLocaleLowerCase("en-US"))??null}function Iw(e){return vp.get(e.trim().toLocaleLowerCase("en-US"))??null}function fA(e){return yi[e].section}function hA(e,t){return yi[e].subsections[t]}function Tw(e){return`${yi.en.subsections[e]}/${yi["zh-CN"].subsections[e]}`}function jw(e){return _w.has(e.trim().toLocaleLowerCase("en-US"))}function $w(e){return Aw.get(e.trim().toLocaleLowerCase("en-US"))??null}function fc(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>{if(i!=="scope")return`# ${Rw(e,i)}
|
|
145
|
+
`;let n=[`# ${Rw(e,i)}
|
|
146
|
+
`];n.push(`## ${fA(e)}
|
|
147
|
+
`);for(let a of gp)n.push(`### ${hA(e,a)}
|
|
148
|
+
`);return n.join(`
|
|
149
|
+
`)}).join(`
|
|
150
|
+
`)}var gp,mp,dA,pA,Pw,vp,_w,Aw,yi,Ni=I(()=>{"use strict";gp=["created","modified","deleted","notCreated"],mp={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:"验证预期"}},dA={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:"结论"}},pA={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:"结论"}},Pw=new Map,vp=new Map,_w=new Set,Aw=new Map,yi={en:{section:"Directory structure",subsections:{created:"Created",modified:"Modified",deleted:"Deleted",notCreated:"Not created"}},"zh-CN":{section:"目录结构",subsections:{created:"新建",modified:"修改",deleted:"删除",notCreated:"明确不建"}}};for(let e of Object.keys(mp)){for(let[t,r]of Object.entries(mp[e]))Pw.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(dA[e]))vp.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(pA[e]))vp.set(r.toLocaleLowerCase("en-US"),t)}for(let e of Object.keys(yi)){_w.add(yi[e].section.toLocaleLowerCase("en-US"));for(let[t,r]of Object.entries(yi[e].subsections))Aw.set(r.toLocaleLowerCase("en-US"),t)}});import Br from"path";function yA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Br.posix.isAbsolute(r)||Br.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function bi(e){let t=yA(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Mw(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function gc(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Br.posix.isAbsolute(i)||Br.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function sr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Vw(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function wc(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>mc)throw new Error(`${t} exceeds ${mc} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>vc)throw new Error(`${t} contains more than ${vc} wildcard tokens`);return e}function Fw(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>wc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Fa(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Lw(e,t,r){let i=Fa(e,t,r);if(i>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return i}function NA(e){if(e===void 0)return{...He,include:[...He.include],exclude:[...He.exclude]};let t=sr(e,"native.snapshot");return{include:Fw(t.include,"native.snapshot.include",He.include),exclude:Fw(t.exclude,"native.snapshot.exclude",He.exclude),max_files:Fa(t.max_files,He.max_files,"native.snapshot.max_files"),max_total_bytes:Fa(t.max_total_bytes,He.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Fa(t.max_duration_ms,He.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:Fa(t.max_selection_records,He.max_selection_records,"native.snapshot.max_selection_records")}}function bA(e){if(e===void 0)return;let t=sr(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=sr(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:r,fromArtifactRoot:bi(i),toArtifactRoot:bi(n),stage:a,...o?{cleanup:o}:{}}}function kA(e){if(e===void 0)return;let t=sr(e,"native.finish");if(t.pull_request===void 0)return{};let r=sr(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Br.posix.isAbsolute(i[0])||Br.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??mA;if(!Number.isSafeInteger(n)||n<1||n>Bw)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Bw}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function SA(e,t={}){let r=sr(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??yp;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=bA(r.pending_root_move),l=kA(r.finish);return{artifact_root:bi(i),language:Vw(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:NA(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function EA(e){let t=sr(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");let a=t.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:Mw(t.artifact_layout),language:Vw(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function xA(e){let r=sr(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>gc(i,`hook.allow_paths[${n}]`)))]}}function CA(e){if(e===void 0)return{...hc};let t=sr(e,"memory"),r=t.learning??hc.learning,i=t.retrieval??hc.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function Np(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function RA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Br.posix.isAbsolute(r)||Br.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>Ow)throw new Error(`${t} exceeds ${Ow} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>Hw)throw new Error(`${t} contains more than ${Hw} wildcard tokens`);return r}function PA(e){let t=Np(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>RA(n,`knowledge.local.include[${a}]`)))],max_file_mb:Lw(t.max_file_mb,Dw.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Lw(t.max_total_mb,Dw.max_total_mb,"knowledge.local.max_total_mb")};if(i.max_file_mb>i.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return i}function _A(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function AA(e){let t=Np(e,"knowledge.remote"),r=_A(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function IA(e){if(e===void 0)return{...qw};let t=Np(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:PA(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:AA(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function TA(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function jA(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(p=>p!=="native"&&p!=="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:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function qa(e,t={}){let r=(0,wp.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=TA(n.ambient_resume),o=n.hook===void 0?void 0:xA(n.hook),s=CA(n.memory),c=IA(n.knowledge),l=n.native===void 0?void 0:SA(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:EA(n.classic),d=jA(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function yc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...hc},knowledge:{...qw},native:{artifact_root:bi(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:yp,snapshot:{...He,include:[...He.include],exclude:[...He.exclude]}}}}var wp,La,mc,vc,Ow,Hw,yp,hc,Dw,qw,mA,Bw,vA,gA,wA,He,Fr=I(()=>{"use strict";wp=ir(Bt(),1),La=Number.MAX_SAFE_INTEGER,mc=1024,vc=64,Ow=1024,Hw=64,yp=5,hc={learning:!0,retrieval:!0},Dw={include:[],max_file_mb:1,max_total_mb:32},qw={provider:"local"},mA=12e4,Bw=6e5,vA=[".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/**"],gA=["**/.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"],wA=[...vA,...gA].sort((e,t)=>e.localeCompare(t,"en")),He={include:["**/*"],exclude:[...wA],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as Nc,promises as ki}from"fs";function bp(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ww(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ma(e){return{dev:e.dev,ino:e.ino,birthtime:bp(e)}}function bc(e,t){let r=Ma(e),i=Ma(t);return Xe(r,i)?G(r,i):G(r,i)&&bp(e)===bp(t)&&Ww(e)===Ww(t)&&e.size===t.size}async function Si(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await ki.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new St("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new St("too-large",`${i} exceeds ${t} bytes`);let o=await ki.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Ma(a)});let s=process.platform==="win32"?Nc.O_RDONLY:Nc.O_RDONLY|Nc.O_NOFOLLOW|Nc.O_NONBLOCK,c;try{c=await ki.open(e,s)}catch(l){throw l.code==="ELOOP"?new St("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),ki.lstat(e,{bigint:n}),ki.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!bc(a,l)||!bc(a,u))throw new St("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Ma(l)}),await r.hooks?.afterOpen?.();let p=[],f=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-f,{bytesRead:k}=await c.read(m,0,Math.min(m.length,b),null);if(k===0)break;if(f+=k,f>t)throw new St("too-large",`${i} exceeds ${t} bytes`);p.push(Buffer.from(m.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat({bigint:n}),ki.lstat(e,{bigint:n}),ki.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!bc(a,h)||!bc(a,v))throw new St("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:Ma(h)}),{bytes:Buffer.concat(p,f),stat:h,realPath:g}}finally{await c.close()}}var St,Va=I(()=>{"use strict";Ba();St=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as kc}from"fs";import Lr from"path";function $A(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function kp(e,t){let r=Lr.relative(e,t);return r===""||!Lr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Lr.sep}`)}async function zw(e,t){let r=Lr.resolve(e),i=await kc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return kc.realpath(r)}async function Gw(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Lr.join(n,r[a]);let o;try{o=await kc.lstat(n)}catch(u){if($A(u))return{exists:!1,kind:"missing"};throw u}let s=Lr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await kc.realpath(n);if(!kp(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function cn(e,t,r){let i=gc(t,r.label),n=Lr.resolve(e),a=await zw(n,r.label),o=i.split("/"),s=Lr.resolve(n,...o);if(!kp(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Gw(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Mt(e,t,r,i){let n=await cn(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await zw(n.projectRoot,i.label);return Si(n.target,r,{...i,verify:async(o,s)=>{if(!kp(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Gw(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var cr=I(()=>{"use strict";Va();Fr()});import{createHash as OA}from"crypto";function HA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Sc(e,t={}){return(await Ec(e,t)).document}async function DA(e){try{return(await Mt(e,Wa,La,{label:Wa})).bytes}catch(t){if(HA(t))return null;throw t}}function BA(e){return e?{exists:!0,sha256:OA("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Ec(e,t={}){let r=await DA(e);return{document:r?qa(r.toString("utf8"),t):null,identity:BA(r)}}async function Sp(e){return(await Sc(e))?.config??null}var Wa,ln=I(()=>{"use strict";Fr();cr();Wa=".comet/config.yaml"});var un=I(()=>{"use strict";hp();Ba()});var X1,Ep=I(()=>{"use strict";un();ln();cr();X1=16*1024});var Rp=I(()=>{"use strict";un();Fr();ln();cr();Ep()});import{existsSync as Uw,promises as qr}from"fs";import B from"path";import VA from"os";async function Pp(e){try{return await qr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function zA(e){try{let t=await qr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function pn(e,t){let r=B.relative(e,t);return r===""||!B.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${B.sep}`)}async function dn(e){let t=[],r=e;for(;!await Pp(r);){let n=B.dirname(r);if(n===r)break;t.push(B.basename(r)),r=n}let i=await qr.realpath(r);return B.resolve(i,...t.reverse())}async function _p(e){try{return(await qr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Cc(e){let t=B.resolve(e);try{(await qr.stat(t)).isDirectory()||(t=B.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=B.resolve(VA.homedir());for(;;){if(!(t===i&&r!==i)){let o=B.join(t,...xc.split("/")),s=t===r||await zA(o);if(await Pp(o)&&s)return t}if(await Pp(B.join(t,".git")))return t;let a=B.dirname(t);if(a===t)return r;t=a}}function Rc(e){return bi(e)}async function GA(e,t){let r=Rc(t),i=B.resolve(e,...r.split("/")),n=await qr.realpath(e),a=await dn(i);if(!pn(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Vt(e,t){let r=Rc(t),i=await GA(e,r),n=B.join(i,"comet");if(await _p(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([dn(i),dn(n)]);if(!pn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=B.resolve(e),c=B.join(s,".comet","runtime","native");if(await _p(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([qr.realpath(s),dn(c)]);if(!pn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:B.join(e,...xc.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:B.join(n,"specs"),changesDir:B.join(n,"changes"),archiveDir:B.join(n,"archive"),runtimeDir:c,changesRuntimeDir:B.join(c,"changes"),locksDir:B.join(c,"locks"),transactionsDir:B.join(c,"transactions")}}function Ap(e){if(!WA.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Et(e,t){Ap(t);let r=B.join(e.changesRuntimeDir,t);if(!q(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Yw(e,t){Ap(t);let r=B.join(e.changesDir,t,"runtime");if(!q(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Y(e,t){let r=Et(e,t);if(Uw(r))return r;let i=Yw(e,t);return Uw(i)?i:r}function Ga(e,t){Ap(t);let r=B.join(e.changesDir,t),i=Y(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:B.join(r,"brief.md"),childrenPath:B.join(r,"children.yaml"),specsDir:B.join(r,"specs"),verificationPath:B.join(r,"verification.md"),statePath:B.join(r,"comet-state.yaml"),runtimeDir:i,runtimeStatePath:B.join(i,"state.json")}}async function Kw(e){try{let t=await qr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Ip(e,t){let r=Et(e,t),i=Yw(e,t),[n,a]=await Promise.all([Kw(r),Kw(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function Mr(e,t){if(!t.startsWith("runtime/")||B.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=B.resolve(e,...t.slice(8).split("/"));if(!q(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function Ne(e,t){let r=B.resolve(t);if(q(e.runtimeDir,r))return e.runtimeDir;if(q(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function q(e,t){return pn(B.resolve(e),B.resolve(t))}async function V(e,t){let r=B.resolve(e),i=B.resolve(t);if(!pn(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await _p(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([dn(r),dn(i)]);if(!pn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var xc,WA,K=I(()=>{"use strict";Fr();xc=".comet/config.yaml",WA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function UA(e="docs",t="en"){return yc(e,t)}async function xe(e){let t=(await Sc(e))?.config??null;return t?.native?t:null}async function _c(e){let t=await xe(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Xw(e){let t=await Cc(e.startPath),r=await xe(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${xc} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?Rc(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??UA(i??"docs"),a=await Vt(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Tp,Pc,Qe=I(()=>{"use strict";Fr();ln();Rp();oe();K();Tp=He,Pc=wc});import{createHash as $p,randomUUID as KA}from"node:crypto";import{promises as Ze}from"node:fs";import YA from"node:os";import Ve from"node:path";async function jp(e,t){let r=await Ze.lstat(e,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(t))throw new Error("Invalid process probe cache");let i=await Ze.readFile(e),n=await Ze.lstat(e,{bigint:!0});if(r.ino!==n.ino||r.ctimeNs!==n.ctimeNs||r.size!==n.size)throw new Error("Process probe cache changed");return i}async function ey(e){try{let t=JSON.parse((await jp(Ve.join(e,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(t.file??""))return null;let r=Ve.join(e,t.file),i=await jp(r,65536);return $p("sha256").update(i).digest("hex")===t.hash?r:null}catch{return null}}async function ZA(e,t){let r,i=KA(),n=Ve.join(e,`probe-${i}.cs`),a=Ve.join(e,`probe-${i}.exe`),o=Ve.join(e,`probe-${i}.json`);try{if(await Ze.mkdir(e,{recursive:!0,mode:448}),(await Ze.lstat(e)).isSymbolicLink())return null;r=await Ze.open(Ve.join(e,"prepare.lock"),"wx",384);let s=await ey(e);if(s)return s;await Ze.writeFile(n,Zw,{flag:"wx",mode:384});let c;for(let u of["Framework64","Framework"]){let d=Ve.join(t,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await Ze.access(d),c=d;break}catch{}}if(!c)return null;await Er(c,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,n],{timeoutMs:1500,maxBufferBytes:4096});let l=$p("sha256").update(await jp(a,65536)).digest("hex");return await Ze.writeFile(o,JSON.stringify({file:Ve.basename(a),hash:l}),{flag:"wx",mode:384}),await Ze.rename(o,Ve.join(e,"probe.json")),a}catch{return null}finally{await Ze.unlink(n).catch(()=>{}),await Ze.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await Ze.unlink(Ve.join(e,"prepare.lock")).catch(()=>{}))}}async function Qw(e,t,r){try{let i=await Er(Ve.join(t,"System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"get","creationdate","/value"],{timeoutMs:300,maxBufferBytes:4096,signal:r}),n=/^CreationDate=(\S+)/mu.exec(i);if(n)return`win32-wmic:${n[1]}`}catch{}if(r.aborted)return null;try{let n=(await Er(Ve.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:1e3,maxBufferBytes:4096,signal:r})).trim();return/^\d+$/u.test(n)?`win32-ps:${n}`:null}catch{return null}}function eI(e,t){let r=Ac.get(e);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:ZA(e,t),retryAfter:1/0};return Ac.set(e,i),i.promise.then(n=>{Ac.get(e)===i&&(n?Ac.delete(e):i.retryAfter=performance.now()+QA)}),i.promise}async function ty(e,t={}){if(!Number.isSafeInteger(e)||e<=0)return null;let r=t.systemRoot??process.env.SystemRoot??"C:\\Windows",i=Ve.join(t.cacheRoot??Ve.join(YA.tmpdir(),"comet-process-identity"),XA),n=async l=>{if(!l)return null;try{let d=(await Er(l,[String(e)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await ey(i);if(a){let l=await n(a);return l||Qw(e,r,new AbortController().signal)}let o=eI(i,r),s=new AbortController,c=l=>{if(!l)throw new Error("Probe unavailable");return l};try{return await Promise.any([o.then(n).then(c),Qw(e,r,s.signal).then(c)])}catch{return null}finally{s.abort()}}var Zw,XA,QA,Ac,ry=I(()=>{"use strict";Ui();Zw=`using System;
|
|
147
151
|
using System.Runtime.InteropServices;
|
|
148
152
|
class CometProcessIdentity {
|
|
149
153
|
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
|
|
@@ -156,43 +160,46 @@ class CometProcessIdentity {
|
|
|
156
160
|
Console.WriteLine(DateTime.FromFileTimeUtc(creation).Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0;
|
|
157
161
|
} finally { CloseHandle(handle); }
|
|
158
162
|
}
|
|
159
|
-
}`,
|
|
160
|
-
`,"utf8"),await r.sync(),i=
|
|
163
|
+
}`,XA=$p("sha256").update(Zw).digest("hex"),QA=1e4,Ac=new Map});import{promises as iy}from"node:fs";function rI(e){let t=Hp.get(e);if(t){if(Date.now()-t.at>tI){Hp.delete(e);return}return t.value}}async function Ja(e){if(e===process.pid&&Op!==null)return Op;let t=rI(e);if(t!==void 0)return t;let r=Ic.get(e);r||(r=iI(e),Ic.set(e,r));let i=await r;return Ic.get(e)===r&&Ic.delete(e),e===process.pid&&i!==null&&(Op=i),i===null&&Hp.set(e,{value:null,at:Date.now()}),i}async function iI(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([iy.readFile(`/proc/${e}/stat`,"utf8"),iy.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32")return await ty(e);if(process.platform==="darwin"){let t=(await Er("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}})).trim();return t?`darwin:${t}`:null}}catch{}return null}function Tc(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function Dp(e,t){if(!Number.isSafeInteger(e)||e<=0)return"alive";try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!t)return"unknown";let r=await Ja(e);return r===t?"alive":r===null||Tc(r)!==Tc(t)&&ny.has(Tc(r))&&ny.has(Tc(t))?"unknown":"dead"}var Op,tI,Hp,Ic,ny,jc=I(()=>{"use strict";Ui();ry();Op=null,tI=1e4,Hp=new Map,Ic=new Map;ny=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as nI}from"async_hooks";import{randomUUID as sy}from"crypto";import{promises as ot}from"fs";import cy from"os";import fe from"path";function sI(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function cI(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${t}`);return r}function ly(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Oc(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Xe(r,i)?G(r,i):G(r,i)&&e.size===t.size}function Ua(e,t){return Oc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function lI(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Ua(e.identity,t.identity)}async function st(e){let t,r;try{let i=await Si(e,ay,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof St?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${ay} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:cI(JSON.parse(t.toString("utf8")),e),identity:ly(r)}}async function uI(e){return(await st(e))?.owner??null}async function Fp(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==cy.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await Dp(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function dI(e,t){try{await ot.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await ot.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Hc(e,t){let r=await st(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ua(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ot.mkdir(t,{recursive:!0});let i=fe.join(t,`${fe.basename(e.file)}.${e.owner.id}.${sy()}.removed`);try{await ot.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await st(i);if(!n||n.owner.id!==e.owner.id||!Oc(n.identity,e.identity))throw await dI(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ot.rm(i,{force:!0}),"removed"}async function uy(e){let t=await Ja(process.pid);return{id:sy(),pid:process.pid,hostname:cy.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function dy(e,t){let r;try{r=await ot.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await uI(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
|
|
164
|
+
`,"utf8"),await r.sync(),i=ly(await r.stat({bigint:!0}))}finally{await r.close()}let n=await st(e);if(!i||!n||n.owner.id!==t.id||!Oc(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function pI(e,t){let r=await V(e.runtimeDir,e.locksDir);await ot.mkdir(r,{recursive:!0});let i=await V(e.runtimeDir,fe.join(r,Bp));await ot.mkdir(i,{recursive:!0});let n=await uy(t),a=fe.join(i,`.${n.id}.tmp`),o=fe.join(i,`${n.id}.claim`);try{let s=await dy(a,n);await ot.rename(a,o);let c=await st(o);if(!c||!Oc(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await ot.rm(a,{force:!0})}}async function fI(e){let t=fe.dirname(e.file),r=!1,i=fe.basename(e.file);for(let n of await ot.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=fe.join(t,n.name);if(fe.resolve(a)!==fe.resolve(e.file))try{let o=await st(a),s=await Fp(o);if(s.status==="missing")continue;let c=await st(a);if(!c)continue;if(!o||c.owner.id!==o.owner.id||!Ua(c.identity,o.identity)){n.name<i&&(r=!0);continue}if(s.status==="stale"&&o){await Hc(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function py(e){let t=await st(e.file);if(t){if(t.owner.id!==e.owner.id||!Ua(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Hc(t,fe.dirname(e.file))}}async function hI(e,t){let r=Date.now()+aI;for(;;){let i=await pI(e,t);if(!await fI(i))return i;if(await py(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function mI(e){let t=$c.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return $c.set(e,n),await t,()=>{r(),$c.get(e)===n&&$c.delete(e)}}async function Lp(e,t,r){let i=fe.resolve(e.locksDir),n=oy.getStore();if(n?.has(i))return r();let a=await mI(i);try{let o=await hI(e,t),s=new Map(n??[]);return s.set(i,o),await oy.run(s,async()=>{try{return await r()}finally{await py(o)}})}finally{a()}}async function Dc(e,t,r){return Lp(e,`acquire ${t}`,async()=>{let i=await V(e.runtimeDir,e.locksDir);await ot.mkdir(i,{recursive:!0});let n=await V(e.runtimeDir,fe.join(i,sI(t))),a=await uy(r),o=await dy(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Bc(e){await st(e.file)&&await Lp({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${fe.basename(e.file)}`,async()=>{let t=await st(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ua(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=fe.join(e.locksDir,Bp);await Hc(t,r)})}function vI(e,t=Date.now()){if(!e)return 0;let r=Date.parse(e.createdAt);return Number.isFinite(r)?Math.max(0,t-r):Number.POSITIVE_INFINITY}async function fy(e){return Fp(await st(e))}async function hy(e,t,r,i={}){return Lp(e,`take over ${fe.basename(t)}`,async()=>{let n=await V(e.runtimeDir,e.locksDir),a=await V(e.runtimeDir,t);if(fe.resolve(fe.dirname(a))!==fe.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await st(a),s=await Fp(o);if(s.status==="missing")return{status:"missing"};if(r&&!lI(r,s))return{status:"changed",diagnosis:s};let c=i.allowAgedUnknown===!0&&s.status==="unknown"&&vI(o?.owner??null)>=oI;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=fe.join(n,Bp);return await Hc(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var ay,Bp,aI,oI,oy,$c,Ka=I(()=>{"use strict";Va();jc();K();Lt();ay=16*1024,Bp=".coordinator",aI=5e3,oI=900*1e3,oy=new nI,$c=new Map});import{createHash as gI}from"node:crypto";function wy(e){return e.replaceAll(`\r
|
|
161
165
|
`,`
|
|
162
166
|
`).replaceAll("\r",`
|
|
163
|
-
`)}function lI(e){return aI("sha256").update(cy(e)).digest("hex")}function Lp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new ie(`${t} must be an object`);return e}function ly(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new ie(`${r} has unknown field(s): ${i.join(", ")}`)}function qp(e,t){if(typeof e!="string"||e.trim().length===0)throw new ie(`${t} must be a non-empty string`);return e.trim()}function oy(e,t){if(e!==void 0){if(typeof e!="string")throw new ie(`${t} must be text`);return cy(e).replace(/^\n+|\n+$/gu,"")}}function Dc(e,t){let r=qp(e,t).toLowerCase();if(!cI.test(r))throw new ie(`${t} must be a SHA-256 hash`);return r}function sy(e,t,r){let i=Lp(e,t),n=Object.entries(i);if(n.length>ay)throw new ie(`${t} must contain at most ${ay} entries`);let a={};for(let[o,s]of n){if(Bp(o,`${t} ID`)!==o)throw new ie(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=Dc(s,`${t}.${o}`)}return a}function Bp(e,t){let r=qp(e,t);if(!sI.test(r))throw new ie(`${t} is not a valid stable requirement ID`);return r}function uI(e,t){let r=qp(e,t);if(!oI.test(r))throw new ie(`${t} is not a valid capability ID`);return r}function dI(e,t){let r=`Native delta operations[${t}]`,i=Lp(e,r);ly(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=Bp(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new ie(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:Bp(i.to_id,`${r}.to_id`),c=oy(i.title,`${r}.title`),l=oy(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:Dc(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!l?.trim())throw new ie(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!l?.trim())throw new ie(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||c!==void 0||l!==void 0||!u)throw new ie(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||l==="")throw new ie(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l},...u===void 0?{}:{expected_hash:u}}}function pI(e){let t=Lp(e,"Native delta");if(ly(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==Dp)throw new ie(`Native delta schema must be ${Dp}`);let r=uI(t.capability,"Native delta capability"),i=Dc(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new ie("Native delta base_version must be a positive integer");let n=t.legacy_hash===void 0?void 0:Dc(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=sy(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:sy(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new ie("Native delta operations must be an array");let s=t.operations.map(dI),c=new Set;for(let[l,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let p of d){if(c.has(p))throw new ie(`Native delta operations contain duplicate or overlapping requirement ID ${p} at ${l}`);c.add(p)}}if(o!==void 0){if(a===void 0)throw new ie("Native delta independent_requirements requires base_requirements");for(let[l,u]of Object.entries(o)){if(c.has(l))throw new ie(`Native delta requirement ${l} cannot be both addressed and independent`);let d=a[l];if(u===null?d!==void 0:d!==u)throw new ie(`Native delta independent_requirements does not match baseline ${l}`)}}return{schema:Dp,capability:r,base_hash:i,base_version:Number(t.base_version),...n===void 0?{}:{legacy_hash:n},...a===void 0?{}:{base_requirements:a},...o===void 0?{}:{independent_requirements:o},operations:s}}function fI(e){let t=(0,Fp.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new ie(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function Mp(e){return pI(typeof e=="string"?fI(e):e)}function Ka(e){return lI(e)}var Fp,Dp,oI,sI,cI,ay,ie,Vp=I(()=>{"use strict";Fp=ir(Bt(),1),Dp="comet.native.delta.v1",oI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sI=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,cI=/^[a-f0-9]{64}$/iu,ay=512,ie=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}}});var Wt,lr,ur,pn,fn,Ya,Xa=I(()=>{"use strict";Wt="comet.native.v3",lr="comet.native.v2",ur="comet.native.v1",pn="comet.native.transition.v3",fn="comet.native.transition.v2",Ya="comet.native.transition.v1"});import hI from"node:path";function Za(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function fy(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Si(e){if(!py.test(e))throw new Error(`Invalid Native change name: ${e}`)}function hy(e){if(!py.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function my(e,t){if(e.length===0||hI.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function kI(e,t){let r=Za(e,`spec_changes[${t}]`);if(fy(r,gI,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(hy(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&my(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!zp.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!zp.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function SI(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 Gp(e,t){if(fy(e,t,zt),typeof e.name!="string")throw new Error("Native change name is required");if(Si(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"||!wI.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&&!yI.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(kI),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!NI.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"&&my(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!SI(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Ei(e){let t=Za(e,zt);if(t.schema!==ur)throw new Error(`Expected ${ur}`);return{schema:ur,...Gp(t,mI)}}function Qa(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Wp(e,t,r){if(e===null)return null;let i=typeof e=="string"?bI.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function EI(e){if(e==null)return null;if(typeof e!="string"||!zp.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function xI(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 xi(e){let t=Za(e,zt);if(t.schema!==lr)throw new Error(`Expected ${lr}`);if(Qa(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${lr} minimum_runtime_version must be 2`);return{schema:lr,minimum_runtime_version:2,revision:Qa(t.revision,"Native v2 revision"),...Gp(t,dy)}}function Gt(e){let t=Za(e,zt);if(t.schema!==Wt){if(t.schema===ur||t.schema===lr){let o=t.schema===ur?Ei(t):xi(t);throw new hn(o.name,o.schema)}throw new dr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Qa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new dr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Qa(t.revision,"Native revision"),n=Gp(t,vI),a=EI(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Wt,minimum_runtime_version:3,revision:i,verification_protocol:xI(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Wp(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Wp(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Wp(t.partial_allowance,"Native partial_allowance","allowances")}}function Bc(e){let t=Za(e,zt);if(t.schema===ur){let n=Ei(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Wt}`}}if(t.schema===lr){let n=xi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Wt}`}}if(t.schema!==Wt){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 dr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Qa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new dr(t.schema,r).message};let i=Gt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var uy,mI,dy,vI,gI,wI,yI,NI,zt,zp,py,bI,hn,dr,Fc=I(()=>{"use strict";Xa();uy=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],mI=new Set(uy),dy=new Set([...uy,"minimum_runtime_version","revision"]),vI=new Set([...dy,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),gI=new Set(["capability","operation","source","base_hash"]),wI=new Set(["shape","build","verify","archive"]),yI=new Set(["implicit","confirmed"]),NI=new Set(["pending","pass","fail"]),zt="comet-state.yaml",zp=/^[a-f0-9]{64}$/u,py=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bI=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,hn=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},dr=class extends Error{constructor(r,i){super(r!==Wt||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});import vy from"node:path";function TI(e,t){return e<t?-1:e>t?1:0}function yy(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{value:r,truncated:!0}}function Ny(e,t){let r=t.toString(36),i=j("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function jI(e){if(!AI.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=II.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 r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.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:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function $I(e,t){let r=yy(e.text,pr.maxTextBytes),i=e.context.slice(0,pr.maxContextItems).map(n=>yy(n,pr.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:i.map(n=>n.value),text:r.value,contextTruncated:e.context.length>i.length||i.some(n=>n.truncated),textTruncated:r.truncated,verificationStatus:t}}function ky(e){let t=jI({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(TI),n=i.slice(0,pr.maxFailedCheckIds),a=e.criteria.slice(t,t+pr.maxItems);for(let c of a){let l=[...r,$I(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(p=>p.verificationStatus==="failed").map(p=>p.id),missingAcceptanceIds:l.filter(p=>p.verificationStatus==="missing").map(p=>p.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:u<e.criteria.length?Ny(e.acceptanceHash,u):null,limits:{...pr}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>pr.maxSerializedBytes){if(r.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}r.push(l.at(-1))}if(e.criteria.length>0&&r.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+r.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:r,failedAcceptanceIds:r.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:r.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:o<e.criteria.length?Ny(e.acceptanceHash,o):null,limits:{...pr}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>pr.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Up(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 Jp(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function by(e){return e.includes("-->")||e.includes("--!>")}function*mn(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
167
|
+
`)}function bI(e){return gI("sha256").update(wy(e)).digest("hex")}function Wp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new ie(`${t} must be an object`);return e}function yy(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new ie(`${r} has unknown field(s): ${i.join(", ")}`)}function zp(e,t){if(typeof e!="string"||e.trim().length===0)throw new ie(`${t} must be a non-empty string`);return e.trim()}function vy(e,t){if(e!==void 0){if(typeof e!="string")throw new ie(`${t} must be text`);return wy(e).replace(/^\n+|\n+$/gu,"")}}function Fc(e,t){let r=zp(e,t).toLowerCase();if(!NI.test(r))throw new ie(`${t} must be a SHA-256 hash`);return r}function gy(e,t,r){let i=Wp(e,t),n=Object.entries(i);if(n.length>my)throw new ie(`${t} must contain at most ${my} entries`);let a={};for(let[o,s]of n){if(Mp(o,`${t} ID`)!==o)throw new ie(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=Fc(s,`${t}.${o}`)}return a}function Mp(e,t){let r=zp(e,t);if(!yI.test(r))throw new ie(`${t} is not a valid stable requirement ID`);return r}function kI(e,t){let r=zp(e,t);if(!wI.test(r))throw new ie(`${t} is not a valid capability ID`);return r}function SI(e,t){let r=`Native delta operations[${t}]`,i=Wp(e,r);yy(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=Mp(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new ie(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:Mp(i.to_id,`${r}.to_id`),c=vy(i.title,`${r}.title`),l=vy(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:Fc(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!l?.trim())throw new ie(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!l?.trim())throw new ie(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||c!==void 0||l!==void 0||!u)throw new ie(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||l==="")throw new ie(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l},...u===void 0?{}:{expected_hash:u}}}function EI(e){let t=Wp(e,"Native delta");if(yy(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==qp)throw new ie(`Native delta schema must be ${qp}`);let r=kI(t.capability,"Native delta capability"),i=Fc(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new ie("Native delta base_version must be a positive integer");let n=t.legacy_hash===void 0?void 0:Fc(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=gy(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:gy(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new ie("Native delta operations must be an array");let s=t.operations.map(SI),c=new Set;for(let[l,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let p of d){if(c.has(p))throw new ie(`Native delta operations contain duplicate or overlapping requirement ID ${p} at ${l}`);c.add(p)}}if(o!==void 0){if(a===void 0)throw new ie("Native delta independent_requirements requires base_requirements");for(let[l,u]of Object.entries(o)){if(c.has(l))throw new ie(`Native delta requirement ${l} cannot be both addressed and independent`);let d=a[l];if(u===null?d!==void 0:d!==u)throw new ie(`Native delta independent_requirements does not match baseline ${l}`)}}return{schema:qp,capability:r,base_hash:i,base_version:Number(t.base_version),...n===void 0?{}:{legacy_hash:n},...a===void 0?{}:{base_requirements:a},...o===void 0?{}:{independent_requirements:o},operations:s}}function xI(e){let t=(0,Vp.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new ie(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function Gp(e){return EI(typeof e=="string"?xI(e):e)}function Ya(e){return bI(e)}var Vp,qp,wI,yI,NI,my,ie,Jp=I(()=>{"use strict";Vp=ir(Bt(),1),qp="comet.native.delta.v1",wI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yI=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,NI=/^[a-f0-9]{64}$/iu,my=512,ie=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}}});var Wt,lr,ur,fn,hn,Xa,Qa=I(()=>{"use strict";Wt="comet.native.v3",lr="comet.native.v2",ur="comet.native.v1",fn="comet.native.transition.v3",hn="comet.native.transition.v2",Xa="comet.native.transition.v1"});import CI from"node:path";function eo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Sy(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Ei(e){if(!ky.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ey(e){if(!ky.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function xy(e,t){if(e.length===0||CI.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function $I(e,t){let r=eo(e,`spec_changes[${t}]`);if(Sy(r,_I,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Ey(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&xy(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Kp.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Kp.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function OI(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 Yp(e,t){if(Sy(e,t,zt),typeof e.name!="string")throw new Error("Native change name is required");if(Ei(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"||!AI.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&&!II.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map($I),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!TI.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"&&xy(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!OI(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function xi(e){let t=eo(e,zt);if(t.schema!==ur)throw new Error(`Expected ${ur}`);return{schema:ur,...Yp(t,RI)}}function Za(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Up(e,t,r){if(e===null)return null;let i=typeof e=="string"?jI.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function HI(e){if(e==null)return null;if(typeof e!="string"||!Kp.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function DI(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 Ci(e){let t=eo(e,zt);if(t.schema!==lr)throw new Error(`Expected ${lr}`);if(Za(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${lr} minimum_runtime_version must be 2`);return{schema:lr,minimum_runtime_version:2,revision:Za(t.revision,"Native v2 revision"),...Yp(t,by)}}function Gt(e){let t=eo(e,zt);if(t.schema!==Wt){if(t.schema===ur||t.schema===lr){let o=t.schema===ur?xi(t):Ci(t);throw new mn(o.name,o.schema)}throw new dr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Za(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new dr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Za(t.revision,"Native revision"),n=Yp(t,PI),a=HI(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Wt,minimum_runtime_version:3,revision:i,verification_protocol:DI(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Up(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Up(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Up(t.partial_allowance,"Native partial_allowance","allowances")}}function Lc(e){let t=eo(e,zt);if(t.schema===ur){let n=xi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Wt}`}}if(t.schema===lr){let n=Ci(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Wt}`}}if(t.schema!==Wt){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 dr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Za(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new dr(t.schema,r).message};let i=Gt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Ny,RI,by,PI,_I,AI,II,TI,zt,Kp,ky,jI,mn,dr,qc=I(()=>{"use strict";Qa();Ny=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],RI=new Set(Ny),by=new Set([...Ny,"minimum_runtime_version","revision"]),PI=new Set([...by,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),_I=new Set(["capability","operation","source","base_hash"]),AI=new Set(["shape","build","verify","archive"]),II=new Set(["implicit","confirmed"]),TI=new Set(["pending","pass","fail"]),zt="comet-state.yaml",Kp=/^[a-f0-9]{64}$/u,ky=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jI=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,mn=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},dr=class extends Error{constructor(r,i){super(r!==Wt||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});import Cy from"node:path";function WI(e,t){return e<t?-1:e>t?1:0}function _y(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{value:r,truncated:!0}}function Ay(e,t){let r=t.toString(36),i=j("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function zI(e){if(!MI.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=VI.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 r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.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:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function GI(e,t){let r=_y(e.text,pr.maxTextBytes),i=e.context.slice(0,pr.maxContextItems).map(n=>_y(n,pr.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:i.map(n=>n.value),text:r.value,contextTruncated:e.context.length>i.length||i.some(n=>n.truncated),textTruncated:r.truncated,verificationStatus:t}}function Ty(e){let t=zI({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(WI),n=i.slice(0,pr.maxFailedCheckIds),a=e.criteria.slice(t,t+pr.maxItems);for(let c of a){let l=[...r,GI(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(p=>p.verificationStatus==="failed").map(p=>p.id),missingAcceptanceIds:l.filter(p=>p.verificationStatus==="missing").map(p=>p.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:u<e.criteria.length?Ay(e.acceptanceHash,u):null,limits:{...pr}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>pr.maxSerializedBytes){if(r.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}r.push(l.at(-1))}if(e.criteria.length>0&&r.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+r.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:r,failedAcceptanceIds:r.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:r.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:o<e.criteria.length?Ay(e.acceptanceHash,o):null,limits:{...pr}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>pr.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Qp(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 Xp(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function Iy(e){return e.includes("-->")||e.includes("--!>")}function*vn(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
164
168
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
165
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=
|
|
166
|
-
`),[],i)),"Brief",i)}function
|
|
167
|
-
`),s.context,i),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of
|
|
168
|
-
`).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=Ey(o),c=LI(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function LI(e){let t=Ey([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var CI,RI,PI,_I,AI,II,pr,eo,gy,wy,to=I(()=>{"use strict";yi();de();CI="comet.native.acceptance.v1",RI=/^acceptance-[a-f0-9]{64}$/u,PI=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),_I=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,AI=/^[a-f0-9]{64}$/u,II=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;pr=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),eo=Object.freeze({maxCriteria:1024}),gy="<!-- comet-native:acceptance-evidence:start -->",wy="<!-- comet-native:acceptance-evidence:end -->"});var Zp=I(()=>{"use strict";to()});function ef(e,t,r,i=""){let n=Object.keys(e),a=t.filter(s=>!Object.hasOwn(e,s)),o=n.filter(s=>!t.includes(s));if(a.length||o.length)throw new ro({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var ro,qc=I(()=>{"use strict";ro=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});function tf(e,t){if(typeof e!="string"||!e.trim()||e.length>4e3||/^<[^>]+>$/u.test(e.trim()))throw new Error(`${t} must contain a concrete statement of at most 4000 characters`);return e.trim()}function rf(e){if(!Array.isArray(e))throw new Error("Native Builder acceptance_review must be an array");return e.map((t,r)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native Builder acceptance review entry must be an object");let i=t,n=`Native Builder acceptance_review[${r}]`;ef(i,["id","status","evidence","note"],n,`/acceptance_review/${r}`);let a=i.status;if(!["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"].includes(a))throw new Error(`${n}.status is invalid`);if(!Array.isArray(i.evidence))throw new Error(`${n}.evidence must be an array`);return{id:tf(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>tf(o,`${n}.evidence`)),note:tf(i.note,`${n}.note`)}})}function nf(e,t){if(!t)throw new vn(e.map(({id:c})=>c),[]);let r=new Set(e.map(({id:c})=>c)),i=t.map(({id:c})=>c),n=new Set(i);if(n.size!==i.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=i.filter(c=>!r.has(c));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=e.filter(({id:c})=>!n.has(c)).map(({id:c})=>c),s=t.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(o.length||s.length)throw new vn(o,s)}var vn,Mc=I(()=>{"use strict";qc();vn=class extends Error{constructor(r,i){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${i.length?`; not ready: ${i.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=i}missingIds;incompleteIds}});function af(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var gn,Vc,Cy,io=I(()=>{"use strict";gn="comet.native.v4",Vc="comet.native.local-execution.v4",Cy=["multi-session","single-session"]});var uf={};VE(uf,{NativePortableStateVersionConflictError:()=>no,appendNativePortableHistory:()=>ao,compareAndSwapNativePortableState:()=>_y,createNativePortableState:()=>Py,parseNativePortableState:()=>ze,readNativePortableState:()=>Vr,writeNativePortableState:()=>lf});import{promises as qI}from"node:fs";function De(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Be(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function be(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function sf(e,t){return e===null?null:be(e,t)}function cf(e,t){let r=be(e,t);if(!zI.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function wn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function se(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function JI(e,t){return e===null?null:se(e,t,Number.MIN_SAFE_INTEGER)}function he(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Jt(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Jc(e,t){return Jt(e,t,(r,i)=>be(r,`${t}[${i}]`))}function Ci(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function yn(e,t){let r=be(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function zc(e,t,r=!1){let i=be(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function ct(e,t){let r=De(e,t);return Be(r,new Set(["text","truncated"]),t),{text:be(r.text,`${t}.text`,{empty:!0}),truncated:wn(r.truncated,`${t}.truncated`)}}function UI(e,t){let r=`Native spec_changes[${t}]`,i=De(e,r);Be(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=be(i.capability,`${r}.capability`);if(!VI.test(n))throw new Error(`${r}.capability is invalid`);let a=he(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:zc(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:zc(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:cf(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function KI(e){let t="Native workspace",r=De(e,t);Be(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=he(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=sf(r.change_branch,`${t}.change_branch`),a=sf(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:he(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function YI(e){let t="Native loop",r=De(e,t);Be(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=Jc(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Ci(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:he(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:he(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:se(r.goal_cycle,`${t}.goal_cycle`,1),iteration:se(r.iteration,`${t}.iteration`),attempt:se(r.attempt,`${t}.attempt`),retry_epoch:se(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:se(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:se(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:se(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:sf(r.next_action,`${t}.next_action`)}}function XI(e,t){let r=`Native acceptance[${t}]`,i=De(e,r);Be(i,new Set(["id","source","text","result","reason"]),r);let n=be(i.id,`${r}.id`);if(!WI.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:zc(i.source,`${r}.source`),text:be(i.text,`${r}.text`),result:he(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ct(i.reason,`${r}.reason`)}}function QI(e,t){let r=`Native builder_handoff.checks[${t}]`,i=De(e,r);return Be(i,new Set(["name","result","note"]),r),{name:ct(i.name,`${r}.name`),result:he(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ct(i.note,`${r}.note`)}}function ZI(e){let t="Native builder_handoff",r=De(e,t);Be(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","acceptance_review","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=Jc(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ci(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:De(r.review,`${t}.review`);return n&&Be(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:be(r.candidate_id,`${t}.candidate_id`),identity_provider:be(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:be(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),summary:ct(r.summary,`${t}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:rf(r.acceptance_review)},checks:Jt(r.checks,`${t}.checks`,QI),checks_truncated:wn(r.checks_truncated,`${t}.checks_truncated`),known_limits:Jt(r.known_limits,`${t}.known_limits`,(a,o)=>ct(a,`${t}.known_limits[${o}]`)),known_limits_truncated:wn(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:he(n.status,["passed"],`${t}.review.status`),summary:ct(n.summary,`${t}.review.summary`),reviewer_execution_ref:be(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:yn(r.submitted_at,`${t}.submitted_at`)}}function eT(e,t){let r=`Native blockers[${t}]`,i=De(e,r);Be(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Jc(i.acceptance_ids,`${r}.acceptance_ids`);return Ci(n,`${r}.acceptance_ids`),{owner:he(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ct(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:he(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function tT(e,t){let r=`Native verification.checks[${t}]`,i=De(e,r);return Be(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:be(i.id,`${r}.id`),name:ct(i.name,`${r}.name`),argv_display:Jt(i.argv_display,`${r}.argv_display`,(n,a)=>ct(n,`${r}.argv_display[${a}]`)),argv_truncated:wn(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:zc(i.cwd_ref,`${r}.cwd_ref`,!0),status:he(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:JI(i.exit_code,`${r}.exit_code`),duration_ms:se(i.duration_ms,`${r}.duration_ms`)}}function rT(e){let t="Native verification",r=De(e,t);Be(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Jt(r.checks,`${t}.checks`,tT);Ci(i.map(a=>a.id),`${t}.checks IDs`);let n=be(r.identity_provider,`${t}.identity_provider`);return{candidate_id:be(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:be(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),attempt:se(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":he(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:he(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ct(r.summary,`${t}.summary`),risks:Jt(r.risks,`${t}.risks`,(a,o)=>ct(a,`${t}.risks[${o}]`)),risks_truncated:wn(r.risks_truncated,`${t}.risks_truncated`),completed_at:yn(r.completed_at,`${t}.completed_at`)}}function Ry(e,t){let r=`Native history[${t}]`,i=De(e,r);Be(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Jc(i.unresolved_ids,`${r}.unresolved_ids`);return Ci(n,`${r}.unresolved_ids`),{goal_cycle:se(i.goal_cycle,`${r}.goal_cycle`,1),iteration:se(i.iteration,`${r}.iteration`),attempt:se(i.attempt,`${r}.attempt`),outcome:he(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ct(i.summary,`${r}.summary`),completed_at:yn(i.completed_at,`${r}.completed_at`)}}function iT(e){let t="Native history_overflow.outcome_counts",r=De(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Be(r,new Set(i),t),{pass:se(r.pass,`${t}.pass`),fail:se(r.fail,`${t}.fail`),blocked:se(r.blocked,`${t}.blocked`),"execution-error":se(r["execution-error"],`${t}.execution-error`),recovery:se(r.recovery,`${t}.recovery`)}}function nT(e){let t="Native history_overflow",r=De(e,t);Be(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=se(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:yn(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:yn(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=iT(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function aT(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);e.builder_handoff?.acceptance_review&&nf(e.acceptance,e.builder_handoff.acceptance_review);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function oT(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function ze(e){let t=De(e,"Native portable state");if(Be(t,GI,"Native portable state"),t.schema!==gn)throw new Error(`Native portable state schema must be ${gn}`);let r=be(t.name,"Native state name");if(!MI.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Jt(t.spec_changes,"Native spec_changes",UI);Ci(i.map(s=>s.capability),"Native spec change capabilities");let n=Jt(t.acceptance,"Native acceptance",XI);Ci(n.map(s=>s.id),"Native acceptance IDs");let a=Jt(t.history,"Native history",Ry);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:gn,name:r,language:he(t.language,["en","zh-CN"],"Native state language"),phase:he(t.phase,["shape","build","verify","archive"],"Native state phase"),status:he(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:se(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1 or 2")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:cf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:cf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:he(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:KI(t.workspace),loop:YI(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:ZI(t.builder_handoff),blockers:Jt(t.blockers,"Native blockers",eT),verification:t.verification===null?null:rT(t.verification),history:a,history_overflow:nT(t.history_overflow),verification_result:he(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:he(t.verification_report,["verification.md"],"Native verification_report"),archived:wn(t.archived,"Native archived"),created_at:yn(t.created_at,"Native created_at")};return aT(o),oT(o),o}function Py(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return ze({schema:gn,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:af(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ao(e,t){let r=ze(e),i=Ry(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return ze({...r,history:n,history_overflow:a})}function sT(e,t){let r=(0,Gc.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Vr(e){let t=await qI.readFile(e,"utf8");return ze(sT(t,"Native portable state"))}async function lf(e,t,r={}){let i=ze(t);await qt(e,(0,Gc.stringify)(i),r)}async function cT(e,t){let r=Wc.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Wc.set(e,a),await r;try{return await t()}finally{i(),Wc.get(e)===a&&Wc.delete(e)}}async function _y(e){return cT(e.file,async()=>{let t=se(e.expectedStateVersion,"Native expected state version",1),r=ze(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Vr(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new no(t,i.state_version);return await lf(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Vr(e.file);if(n.state_version!==t)throw new no(t,n.state_version)}}),r})}var Gc,MI,VI,WI,zI,GI,no,Wc,xt=I(()=>{"use strict";Mc();Gc=ir(Bt(),1);oe();io();MI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WI=/^A[1-9][0-9]*$/u,zI=/^[a-f0-9]{64}$/u,GI=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),no=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};Wc=new Map});var Ri=I(()=>{"use strict"});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){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function Iy(e){let t=hT(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!lT.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Ay)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!dT.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!uT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!fT.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!pT.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Ay,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:mT(t.createdAt,"Native portable migration transaction createdAt")}}var Ay,lT,uT,dT,pT,fT,Ty=I(()=>{"use strict";Fc();Zp();xt();Ri();io();Xa();Ay="comet.native.portable-migration.v1",lT=new Set(["schema","id","change","fromSchema","status","createdAt"]),uT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dT=/^[a-z0-9][a-z0-9-]{7,127}$/u,pT=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),fT=new Set([ur,lr,Wt])});import vT from"node:path";function Dy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function By(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function df(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function $y(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function ET(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Dy(e,r);if(By(i,ST,r),typeof i.capability!="string"||!Hy.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(p=>p==="."||p==="..")))throw new Error(`${r}.delta_source is invalid`);let o=df(i.base_hash,`${r}.base_hash`),s=$y(i.delta_content,`${r}.delta_content`),c=$y(i.source_content,`${r}.source_content`),l=df(i.expected_target_hash,`${r}.expected_target_hash`),u=df(i.result_hash,`${r}.result_hash`),d=a!==void 0;if(d&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(d&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!d&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let p=Mp(s);if(p.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(p.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(Ka(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(Ka(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(p=>p==="."||p===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||Ka(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function xT(e){let t=Dy(e,"Native portable Archive transaction");if(By(t,kT,"Native portable Archive transaction"),t.schema!==jy)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!yT.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Hy.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!NT.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!bT.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(ET);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:jy,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function pf(e){let t=gT.exec(e);if(t)return{kind:"archive",change:t[1]};let r=wT.exec(e);return r?{kind:"migration",change:r[1]}:null}async function Fy(e,t){let r=pf(t);if(!r)return null;let i=await re({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=vT.join(e.transactionsDir,t);if(r.kind==="archive"){let s=xT(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Iy(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function Ly(e){return e.kind==="archive"||e.journal.status!=="committed"}var jy,Oy,gT,wT,yT,NT,bT,kT,ST,Hy,ff=I(()=>{"use strict";at();Vp();Ty();jy="comet.native.archive-transaction.v4",Oy="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",gT=new RegExp(`^portable-archive-(${Oy})\\.json$`,"u"),wT=new RegExp(`^portable-migration-(${Oy})\\.json$`,"u"),yT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,NT=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bT=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),kT=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ST=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),Hy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as qy}from"node:crypto";import{constants as Wr,promises as me}from"node:fs";import Ge from"node:path";import{TextDecoder as CT}from"node:util";function Nn(e,t){let r=Ge.relative(e,t);return r===""||!Ge.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ge.sep}`)}function My(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function RT(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Vy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function zr(e,t){return G({...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 Uc(e,t){let r=await me.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await me.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Kc(e,t,r){let i=Ge.resolve(e),n=Ge.resolve(t);if(!Nn(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Uc(i,r)],o=i;for(let s of Ge.relative(i,n).split(Ge.sep).filter(Boolean)){await Fe(a,r),o=Ge.join(o,s);let c=await Uc(o,r);if(!Nn(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Fe(a,r),a}async function Fe(e,t){for(let r of e){let i=await me.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!RT(r,i)||await me.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function PT(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,t!==null&&n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Gr(e){let t=e.maxBytes===null?null:My(e.maxBytes),r=Ge.resolve(e.file),i=await Kc(e.root,Ge.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Uc(Ge.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Fe(i,e.label);let a=await me.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=Vy(a),s=await me.realpath(r);if(!Nn(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Nn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Wr.O_RDONLY:Wr.O_RDONLY|Wr.O_NOFOLLOW|Wr.O_NONBLOCK,l=await me.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,p]=await Promise.all([me.lstat(r),me.realpath(r)]);if(await Fe(i,e.label),await Fe(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==s||!zr(o,u)||!zr(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let f=await PT(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),me.lstat(r),me.realpath(r)]);if(await Fe(i,e.label),await Fe(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!zr(o,m)||!zr(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:f,hash:qy("sha256").update(f).digest("hex"),size:f.length}}finally{await l.close()}}async function hf(e){let t=Ge.resolve(e.file),r=await Kc(e.root,Ge.dirname(t),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(l=>Uc(Ge.resolve(l),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Fe(r,e.label);let n=await me.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let a=Vy(n),o=await me.realpath(t);if(!Nn(r[0].realPath,o))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(l=>Nn(l.realPath,o)))throw new Error(`${e.label} resolves inside an excluded root`);let s=process.platform==="win32"?Wr.O_RDONLY:Wr.O_RDONLY|Wr.O_NOFOLLOW|Wr.O_NONBLOCK,c=await me.open(t,s);try{let l=await c.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([me.lstat(t),me.realpath(t)]);if(await Fe(r,e.label),await Fe(i,e.label),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!zr(a,l)||!zr(a,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=qy("sha256"),f=0,m=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:b}=await c.read(m,0,m.length,null);if(b===0)break;f+=b,p.update(m.subarray(0,b))}await e.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat(),me.lstat(t),me.realpath(t)]);if(await Fe(r,e.label),await Fe(i,e.label),!v.isFile()||v.isSymbolicLink()||g!==o||!zr(a,h)||!zr(a,v))throw new Error(`${e.label} changed while reading`);return{hash:p.digest("hex"),size:f}}finally{await c.close()}}async function Wy(e){let t=await Gr(e),r;try{r=new CT("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function so(e){let t=await Kc(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await me.readdir(e.directory,{withFileTypes:!0});else{let i=My(e.maxEntries);r=[];let n=await me.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Fe(t,e.label),{entries:r,verify:()=>Fe(t,e.label)}}async function mf(e){let t=await Kc(e.root,e.directory,e.label);return{verify:()=>Fe(t,e.label)}}var Ct=I(()=>{"use strict";oe();Lt()});import fr from"path";import{TextDecoder as AT}from"util";function Xc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qc(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Uy(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function vf(e,t){if(typeof e!="string"||e.length===0||fr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Yc(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function zy(e,t){if(vf(e,t),e.includes("\\")||e!==fr.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function HT(e,t){let r=Xc(e,`transaction operations[${t}]`);if(Qc(r,TT,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);vf(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&vf(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function Ky(e){let t=Xc(e,"Native Archive transaction journal");if(Qc(t,jT,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Jy.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Uy(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Yc(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=Xc(s,`Archive transaction operations[${c}]`);if(Qc(l,$T,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);zy(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&zy(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Yc(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Yc(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Yc(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function DT(e){let t=Xc(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Ky(t);if(Qc(t,IT,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Jy.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!fr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!fr.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Uy(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(HT),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function BT(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return fr.join(e.transactionsDir,t)}function Yy(e,t){let r=BT(e,t);return{directory:r,journal:fr.join(r,"transaction.json"),events:fr.join(r,"events.jsonl"),staged:fr.join(r,"staged"),backups:fr.join(r,"backups")}}async function gf(e,t){let r=Yy(e,t);return await Promise.all(Object.values(r).map(i=>V(e.runtimeDir,i))),r}async function wf(e,t,r={}){let i=await gf(e,t),n=await Gr({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(OT.decode(n.bytes)),o=DT(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var IT,TT,jT,$T,Jy,OT,Zc=I(()=>{"use strict";oe();K();Ct();IT=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),TT=new Set(["id","type","source","target","staged","backup"]),jT=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),$T=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Jy=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),OT=new AT("utf-8",{fatal:!0})});import{promises as FT}from"fs";import LT from"path";async function qT(e,t,r){let i;try{i=await FT.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await wf(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(pf(n.name))try{let a=await Fy(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Ly(a))return!0}catch{return!0}return!1}async function MT(e,t){let r=Date.now()+5e3,i=LT.join(e.locksDir,"root-move.lock");for(;;)try{return await Oc(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await iy(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await ny(e,i,o);if(s.status==="removed"||s.status==="missing")continue;throw n}if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function Ce(e,t,r,i){let n=await MT(e,t);try{if(await Rc(e.projectRoot),await qT(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Hc(n)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${n.file} (${a.message}); run comet native doctor --repair if commands start failing
|
|
169
|
-
`)}}}var Re=I(()=>{"use strict";Qe();Ua();ff();Zc()});import{createHash as Xy}from"crypto";import{createReadStream as VT}from"fs";async function yf(e){let t=Xy("sha256");for await(let r of VT(e))t.update(r);return t.digest("hex")}function ee(e){return Xy("sha256").update(e).digest("hex")}var Ut=I(()=>{"use strict"});import{createHash as nl}from"crypto";import{spawn as sN}from"node:child_process";import{promises as ne}from"fs";import F from"path";import{performance as Qy}from"node:perf_hooks";function lN(e){let t=e.deadlineMs??sj;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Rt(e){return Math.max(0,e.deadlineAt-Date.now())}function H(e){return Rt(e)>=1}function Nf(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 Sn(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function dj(e,t){let r={...uj,...t===void 0?{}:{maxNodes:t},...e};if(!Number.isSafeInteger(r.maxNodes)||r.maxNodes<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxPathBytes)||r.maxPathBytes<1||r.maxPathBytes>r.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return r}async function pj(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&F.win32.isAbsolute(i)?F.win32.resolve(i):"C:\\Windows",a=F.win32.join(n,"System32","taskkill.exe");if(!F.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=(p,f=!1)=>{c||(c=!0,u&&clearTimeout(u),f&&l?.kill("SIGKILL"),s(p))};try{l=sN(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",p=>d(p===0)),u=setTimeout(()=>d(!1,!0),cj),u.unref()}catch{d(!1)}});for(let s=0;s<lj;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(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function Cf(e,t,r,i){let n=Rt(e);if(n<1)throw Nf();let a=e.gitProcess,o=Qy.now(),s=sN(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),c=null,l=!1,u=null;s.once("error",m=>{c=m});let d=new Promise(m=>{s.once("close",m)}),p=setTimeout(()=>{l=!0,u=pj(s,a).then(()=>({error:null}),m=>({error:m}))},n);p.unref();let f=d.then(async m=>{if(clearTimeout(p),l){let h=await u;throw h?.error?Nf(h.error):Nf()}return{code:m,spawnError:c}}).finally(()=>os(Qy.now()-o));return{child:s,completion:f}}function uN(e,t){let r={...xf,...t===void 0?{}:{maxRecords:t},...e};if(!Number.isSafeInteger(r.maxRecords)||r.maxRecords<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxRecordBytes)||r.maxRecordBytes<1||r.maxRecordBytes>r.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return r}async function tl(e,t,r,i=Sf){let{child:n,completion:a}=Cf(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",f=>{let m=Math.max(0,i-l);m>0&&o.push(Buffer.from(f).subarray(0,m)),l+=f.byteLength,l>i&&(u=!0)}),n.stderr.on("data",f=>{if(c>=xn)return;let m=xn-c,h=Buffer.from(f).subarray(0,m);s.push(h),c+=h.byteLength});let{code:d,spawnError:p}=await a;if(d===0&&p===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${p?`: ${p.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function bf(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function lo(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.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}=Cf(e,t,r,i.stdin!==void 0),c=[],l=nl("sha256"),u=[],d=0,p=0,f=0,m=0,h=Buffer.alloc(0),v=!1,g=!1,b=!1,k=N=>{let x=0;for(;x<N.byteLength;){let w=N.indexOf(0,x),S=w<0?N.byteLength:w,E=N.subarray(x,S);if(!v&&E.byteLength>0&&(h.byteLength+E.byteLength>i.maxRecordBytes?(h=Buffer.alloc(0),v=!0,g=!0):h=Buffer.concat([h,E])),w<0)break;m+=1,h.byteLength===0&&!v&&(b=!0);let y=h.byteLength+1;!v&&m<=i.maxRecords&&f+y<=i.maxBytes?(c.push(h),f+=y):g=!0,h=Buffer.alloc(0),v=!1,x=w+1}};o.stdout.on("data",N=>{l.update(N),p+=N.byteLength,p>i.maxBytes&&(g=!0);let x=i.outputChunkBytes;if(x===void 0){k(N);return}for(let w=0;w<N.byteLength;w+=x)k(N.subarray(w,Math.min(N.byteLength,w+x)))}),o.stderr.on("data",N=>{if(d>=xn)return;let x=xn-d,w=Buffer.from(N).subarray(0,x);u.push(w),d+=w.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:x})=>{let w=i.acceptedExitCodes??[0];if(N!==null&&w.includes(N)&&x===null&&!b&&h.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:m,stdoutBytes:p});return}a(new Error(`git ${r.join(" ")} failed${x?`: ${x.message}`:b||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function rl(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 fj(e,t,r){if(r.length===0)return new Set;let i=await lo(e,t,["check-ignore","--no-index","-z","--stdin"],{...xf,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=rl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function hj(e,t,r){let{child:i,completion:n}=Cf(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=xn)return;let d=xn-o,p=Buffer.from(u).subarray(0,d);a.push(p),o+=p.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function En(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||F.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||F.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function mj(e,t){return e.map(r=>{let i=En(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function vj(e){let t=F.resolve(e);for(;;){try{return await ne.lstat(F.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=F.dirname(t);if(r===t)return!1;t=r}}function gj(e){return e?e.filter(t=>t&&!t.startsWith("!")).flatMap(t=>t.includes("**")?[`:(exclude,glob)${t}`]:[`:(exclude)${t}`]):[]}async function dN(e,t,r,i={},n){let a=F.resolve(t.projectRoot),o=F.join(a,".comet","current-change.json"),c=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,o].map(f=>{let m=F.relative(a,F.resolve(f)).replaceAll("\\","/"),h=En(m);if(h===null)throw new Error("Native Git snapshot exclusion escaped the project root");return h}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`]),...gj(n)],l={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},u=await lo(e,a,["ls-files","--stage","-z",...c],l);await i.afterStageBefore?.();let d=await lo(e,a,["ls-files","--cached","--others","--exclude-standard","-z",...c],l);await i.afterCombined?.();let p=await lo(e,a,["ls-files","--stage","-z",...c],l);return{stagedBefore:u,combined:d,stagedAfter:p}}function pN(e){return{stageBefore:bf(e.stagedBefore),combined:bf(e.combined),stageAfter:bf(e.stagedAfter)}}async function fN(e,t,r=xf,i={},n){let a=F.resolve(t.projectRoot);if(!await vj(a))return null;let o;try{o=await tl(e,a,["rev-parse","--is-inside-work-tree"])}catch(k){throw Sn(k)?k:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:k})}if(o.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let s;try{s=await dN(e,t,r,i,n)}catch(k){throw Sn(k)?k:new Error("Native Git snapshot provider failed after repository detection",{cause:k})}let{stagedBefore:c,combined:l,stagedAfter:u}=s,d=new Set,p=new Map,f=new Set,m=k=>{for(let N of k){let x=rl(N),w=x.indexOf(" ");if(w<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let S=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(x.slice(0,w))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let E=En(x.slice(w+1));if(E===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");d.add(E),S.stage==="0"&&p.set(E,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(E)}};m(c.records),m(u.records);let h=l.records.map(rl),v=mj(h,"combined"),g=new Set(v.filter(k=>!d.has(k))),b=new Set(v.filter((k,N)=>!d.has(k)&&h[N].endsWith("/")));for(let k of f)b.delete(k);return{tracked:d,trackedObjectIds:p,untracked:g,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:pN(s)}}function Ur(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Zy(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function wj(e,t){return!Ur(e.stageBefore,e.stageAfter)||!Ur(e.stageAfter,t.stageBefore)||!Ur(e.combined,t.combined)||!Ur(t.stageBefore,t.stageAfter)}async function hN(e,t,r,i,n,a){let o;try{o=await dN(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}},a)}catch(d){throw Sn(d)?d:new Error("Native Git snapshot provider failed during its final selection fence",{cause:d})}let s=i.initialFence,c=pN(o),l=Zy(s)||Zy(c),u=wj(s,c);l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),u&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.evidence=l||u?{schema:"comet.native.git-selection.v1",status:l&&u?"overflow-and-changed":l?"overflow":"changed",...s,finalStageBefore:c.stageBefore,finalCombined:c.combined,finalStageAfter:c.stageAfter}:null,(s.combined.overflow||c.combined.overflow)&&(i.overflow={count:Math.max(1,s.combined.recordCount-s.combined.storedRecordCount,c.combined.recordCount-c.combined.storedRecordCount),hash:ee(`comet.native.git-selection-overflow.v2
|
|
170
|
-
${JSON.stringify({initial:s.combined,final:c.combined})}`)})}function
|
|
169
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=Xp(l,t);else if(r)Iy(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=Xp(l,null);if(d!==null)t=d;else{let p=l.trimStart();if(p.startsWith("<!--")&&!Iy(p))r=!0;else{let f=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(p);f&&n.has(f[1].toLowerCase())&&!p.startsWith("</")&&!p.endsWith("/>")&&!new RegExp(`</${f[1]}\\s*>`,"iu").test(p)&&(i=f[1])}}}if(c===-1)break;o=c+1}}function JI(e){return[...vn(e)].map(({line:t,body:r})=>({line:t,body:r}))}function Mc(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function UI(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Zp(e,t,r,i=[],n="content-hash"){let a=Mc(r),o=t.replaceAll("\\","/").trim(),s=i.map(Mc);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(BI,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function ef(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function KI(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of vn(e)){n=s+1;let c=o?Qp(a):null;c?.level===1&&(pc(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function tf(e,t="brief.md",r=to.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=KI(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of vn(e)){if(d<n.start||d>=n.end)continue;let p=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(p===null)continue;let f=p[1].length;a=a===null?f:Math.min(a,f)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of vn(e)){if(d<n.start||d>=n.end)continue;let p=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;p&&p[1].length===a?(c(),s=[p[2]]):s!==null&&s.push(l)}return c(),ef(o.map(l=>Zp("brief-example",t,l.join(`
|
|
170
|
+
`),[],i)),"Brief",i)}function rf(e,t="spec.md",r=to.maxCriteria,i="content-hash",n={}){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let a=[],o=[],s=null,c=()=>{if(s===null)return;if(a.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let l=(n.resolveBriefReferences?s.body:[]).map(u=>/^\s*(?:Acceptance|验收)\s*[::]\s*(.*)$/iu.exec(u)?.[1]).filter(u=>u!==void 0);if(l.some(u=>!/^A[1-9]\d*$/u.test(u)))throw new Error("A Spec acceptance reference must be one brief ID such as A1");if(l.length>1)throw new Error("A Spec scenario may reference only one brief acceptance criterion");a.push({...Zp("spec-scenario",t,[s.title,...s.body].join(`
|
|
171
|
+
`),s.context,i),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of vn(e)){let d=u?Qp(l):null,p=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(p){for(c();o.at(-1)&&o.at(-1).level>=d.level;)o.pop();let f=Mc(p[1]);if(f.length===0)throw new Error("Scenario title must not be empty");s={level:d.level,title:f,body:[],context:o.map(m=>m.text)}}else if(d){for(s!==null&&d.level<=s.level?c():s!==null&&s.body.push(l);o.at(-1)&&o.at(-1).level>=d.level;)o.pop();o.push(d)}else s!==null&&u&&s.body.push(l)}return c(),ef(a,"Specification",i)}function jy(e,t="spec.md",r=to.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Zp("spec-must",t,s.parts.join(" "),s.context,i)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of vn(e)){let p=d?Qp(u):null;if(p){for(c(),o!==null&&p.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=p.level;)a.pop();a.push(p),/^Scenario\s*:/iu.test(p.text)&&(o=p.level);continue}let f=u.trim();if(!d||o!==null||l()){c();continue}if(f.length===0||Xp(u,null)!==null||f.startsWith("<!--")||f==="-->"||f==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(f)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(f)||/^(?:[-*_]\s*){3,}$/u.test(f)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(f)){c();continue}let m=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(m){c(),s={parts:[m[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(f)){c(),s={parts:[f],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[f],context:a.map(h=>h.text)}:s.parts.push(f)}return c(),ef(n,"Specification mandatory requirements",i)}function YI(e,t){let r=e.trim().replaceAll("\\","/");if(r.length===0||UI(r)||Cy.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(r)||r.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let i=Cy.posix.normalize(r);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(i.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!qI.test(i))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return i}function XI(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let r=e,i=Object.keys(r).filter(n=>!LI.has(n));if(i.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${i.join(", ")}`);return r}function $y(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((r,i)=>{let n=XI(r,i),a=n.acceptance_id;if(typeof a!="string"||!FI.test(a))throw new Error(`Acceptance evidence entry ${i} 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 YI(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 Oy(e){let t=JI(e);if(t.some(({line:l,body:u})=>!u&&(l===Ry||l===Py)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let i=t.flatMap(({line:l,body:u},d)=>u&&l===Ry?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===Py?[d]:[]);if(i.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(i[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(i[0]+1,n[0]).map(({line:l})=>l).join(`
|
|
172
|
+
`).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=$y(o),c=QI(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function QI(e){let t=$y([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var BI,FI,LI,qI,MI,VI,pr,to,Ry,Py,ro=I(()=>{"use strict";Ni();de();BI="comet.native.acceptance.v1",FI=/^acceptance-[a-f0-9]{64}$/u,LI=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),qI=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,MI=/^[a-f0-9]{64}$/u,VI=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;pr=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),to=Object.freeze({maxCriteria:1024}),Ry="<!-- comet-native:acceptance-evidence:start -->",Py="<!-- comet-native:acceptance-evidence:end -->"});var nf=I(()=>{"use strict";ro()});function af(e,t,r,i=""){let n=Object.keys(e),a=t.filter(s=>!Object.hasOwn(e,s)),o=n.filter(s=>!t.includes(s));if(a.length||o.length)throw new io({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var io,Vc=I(()=>{"use strict";io=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});function of(e,t){if(typeof e!="string"||!e.trim()||e.length>4e3||/^<[^>]+>$/u.test(e.trim()))throw new Error(`${t} must contain a concrete statement of at most 4000 characters`);return e.trim()}function sf(e){if(!Array.isArray(e))throw new Error("Native Builder acceptance_review must be an array");return e.map((t,r)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native Builder acceptance review entry must be an object");let i=t,n=`Native Builder acceptance_review[${r}]`;af(i,["id","status","evidence","note"],n,`/acceptance_review/${r}`);let a=i.status;if(!["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"].includes(a))throw new Error(`${n}.status is invalid`);if(!Array.isArray(i.evidence))throw new Error(`${n}.evidence must be an array`);return{id:of(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>of(o,`${n}.evidence`)),note:of(i.note,`${n}.note`)}})}function cf(e,t){if(!t)throw new gn(e.map(({id:c})=>c),[]);let r=new Set(e.map(({id:c})=>c)),i=t.map(({id:c})=>c),n=new Set(i);if(n.size!==i.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=i.filter(c=>!r.has(c));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=e.filter(({id:c})=>!n.has(c)).map(({id:c})=>c),s=t.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(o.length||s.length)throw new gn(o,s)}var gn,Wc=I(()=>{"use strict";Vc();gn=class extends Error{constructor(r,i){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${i.length?`; not ready: ${i.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=i}missingIds;incompleteIds}});function lf(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var wn,zc,Hy,no=I(()=>{"use strict";wn="comet.native.v4",zc="comet.native.local-execution.v4",Hy=["multi-session","single-session"]});var hf={};ex(hf,{NativePortableStateVersionConflictError:()=>ao,appendNativePortableHistory:()=>oo,compareAndSwapNativePortableState:()=>Fy,createNativePortableState:()=>By,parseNativePortableState:()=>ze,readNativePortableState:()=>Vr,writeNativePortableState:()=>ff});import{promises as ZI}from"node:fs";function De(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Be(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function be(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function df(e,t){return e===null?null:be(e,t)}function pf(e,t){let r=be(e,t);if(!iT.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function yn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function se(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function aT(e,t){return e===null?null:se(e,t,Number.MIN_SAFE_INTEGER)}function he(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Jt(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Kc(e,t){return Jt(e,t,(r,i)=>be(r,`${t}[${i}]`))}function Ri(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Nn(e,t){let r=be(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Jc(e,t,r=!1){let i=be(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function ct(e,t){let r=De(e,t);return Be(r,new Set(["text","truncated"]),t),{text:be(r.text,`${t}.text`,{empty:!0}),truncated:yn(r.truncated,`${t}.truncated`)}}function oT(e,t){let r=`Native spec_changes[${t}]`,i=De(e,r);Be(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=be(i.capability,`${r}.capability`);if(!tT.test(n))throw new Error(`${r}.capability is invalid`);let a=he(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Jc(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:Jc(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:pf(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function sT(e){let t="Native workspace",r=De(e,t);Be(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=he(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=df(r.change_branch,`${t}.change_branch`),a=df(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:he(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function cT(e){let t="Native loop",r=De(e,t);Be(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=Kc(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Ri(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:he(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:he(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:se(r.goal_cycle,`${t}.goal_cycle`,1),iteration:se(r.iteration,`${t}.iteration`),attempt:se(r.attempt,`${t}.attempt`),retry_epoch:se(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:se(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:se(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:se(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:df(r.next_action,`${t}.next_action`)}}function lT(e,t){let r=`Native acceptance[${t}]`,i=De(e,r);Be(i,new Set(["id","source","text","result","reason"]),r);let n=be(i.id,`${r}.id`);if(!rT.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Jc(i.source,`${r}.source`),text:be(i.text,`${r}.text`),result:he(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ct(i.reason,`${r}.reason`)}}function uT(e,t){let r=`Native builder_handoff.checks[${t}]`,i=De(e,r);return Be(i,new Set(["name","result","note"]),r),{name:ct(i.name,`${r}.name`),result:he(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ct(i.note,`${r}.note`)}}function dT(e){let t="Native builder_handoff",r=De(e,t);Be(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","acceptance_review","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=Kc(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ri(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:De(r.review,`${t}.review`);return n&&Be(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:be(r.candidate_id,`${t}.candidate_id`),identity_provider:be(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:be(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),summary:ct(r.summary,`${t}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:sf(r.acceptance_review)},checks:Jt(r.checks,`${t}.checks`,uT),checks_truncated:yn(r.checks_truncated,`${t}.checks_truncated`),known_limits:Jt(r.known_limits,`${t}.known_limits`,(a,o)=>ct(a,`${t}.known_limits[${o}]`)),known_limits_truncated:yn(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:he(n.status,["passed"],`${t}.review.status`),summary:ct(n.summary,`${t}.review.summary`),reviewer_execution_ref:be(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Nn(r.submitted_at,`${t}.submitted_at`)}}function pT(e,t){let r=`Native blockers[${t}]`,i=De(e,r);Be(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Kc(i.acceptance_ids,`${r}.acceptance_ids`);return Ri(n,`${r}.acceptance_ids`),{owner:he(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ct(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:he(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function fT(e,t){let r=`Native verification.checks[${t}]`,i=De(e,r);return Be(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:be(i.id,`${r}.id`),name:ct(i.name,`${r}.name`),argv_display:Jt(i.argv_display,`${r}.argv_display`,(n,a)=>ct(n,`${r}.argv_display[${a}]`)),argv_truncated:yn(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Jc(i.cwd_ref,`${r}.cwd_ref`,!0),status:he(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:aT(i.exit_code,`${r}.exit_code`),duration_ms:se(i.duration_ms,`${r}.duration_ms`)}}function hT(e){let t="Native verification",r=De(e,t);Be(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Jt(r.checks,`${t}.checks`,fT);Ri(i.map(a=>a.id),`${t}.checks IDs`);let n=be(r.identity_provider,`${t}.identity_provider`);return{candidate_id:be(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:be(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),attempt:se(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":he(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:he(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ct(r.summary,`${t}.summary`),risks:Jt(r.risks,`${t}.risks`,(a,o)=>ct(a,`${t}.risks[${o}]`)),risks_truncated:yn(r.risks_truncated,`${t}.risks_truncated`),completed_at:Nn(r.completed_at,`${t}.completed_at`)}}function Dy(e,t){let r=`Native history[${t}]`,i=De(e,r);Be(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Kc(i.unresolved_ids,`${r}.unresolved_ids`);return Ri(n,`${r}.unresolved_ids`),{goal_cycle:se(i.goal_cycle,`${r}.goal_cycle`,1),iteration:se(i.iteration,`${r}.iteration`),attempt:se(i.attempt,`${r}.attempt`),outcome:he(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ct(i.summary,`${r}.summary`),completed_at:Nn(i.completed_at,`${r}.completed_at`)}}function mT(e){let t="Native history_overflow.outcome_counts",r=De(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Be(r,new Set(i),t),{pass:se(r.pass,`${t}.pass`),fail:se(r.fail,`${t}.fail`),blocked:se(r.blocked,`${t}.blocked`),"execution-error":se(r["execution-error"],`${t}.execution-error`),recovery:se(r.recovery,`${t}.recovery`)}}function vT(e){let t="Native history_overflow",r=De(e,t);Be(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=se(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Nn(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Nn(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=mT(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function gT(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);e.builder_handoff?.acceptance_review&&cf(e.acceptance,e.builder_handoff.acceptance_review);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function wT(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function ze(e){let t=De(e,"Native portable state");if(Be(t,nT,"Native portable state"),t.schema!==wn)throw new Error(`Native portable state schema must be ${wn}`);let r=be(t.name,"Native state name");if(!eT.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Jt(t.spec_changes,"Native spec_changes",oT);Ri(i.map(s=>s.capability),"Native spec change capabilities");let n=Jt(t.acceptance,"Native acceptance",lT);Ri(n.map(s=>s.id),"Native acceptance IDs");let a=Jt(t.history,"Native history",Dy);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:wn,name:r,language:he(t.language,["en","zh-CN"],"Native state language"),phase:he(t.phase,["shape","build","verify","archive"],"Native state phase"),status:he(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:se(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2||t.document_constraints_version===3?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1, 2, or 3")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:pf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:pf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:he(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:sT(t.workspace),loop:cT(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:dT(t.builder_handoff),blockers:Jt(t.blockers,"Native blockers",pT),verification:t.verification===null?null:hT(t.verification),history:a,history_overflow:vT(t.history_overflow),verification_result:he(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:he(t.verification_report,["verification.md"],"Native verification_report"),archived:yn(t.archived,"Native archived"),created_at:Nn(t.created_at,"Native created_at")};return gT(o),wT(o),o}function By(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return ze({schema:wn,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:lf(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function oo(e,t){let r=ze(e),i=Dy(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return ze({...r,history:n,history_overflow:a})}function yT(e,t){let r=(0,Uc.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Vr(e){let t=await ZI.readFile(e,"utf8");return ze(yT(t,"Native portable state"))}async function ff(e,t,r={}){let i=ze(t);await qt(e,(0,Uc.stringify)(i),r)}async function NT(e,t){let r=Gc.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Gc.set(e,a),await r;try{return await t()}finally{i(),Gc.get(e)===a&&Gc.delete(e)}}async function Fy(e){return NT(e.file,async()=>{let t=se(e.expectedStateVersion,"Native expected state version",1),r=ze(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Vr(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new ao(t,i.state_version);return await ff(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Vr(e.file);if(n.state_version!==t)throw new ao(t,n.state_version)}}),r})}var Uc,eT,tT,rT,iT,nT,ao,Gc,xt=I(()=>{"use strict";Wc();Uc=ir(Bt(),1);oe();no();eT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rT=/^A[1-9][0-9]*$/u,iT=/^[a-f0-9]{64}$/u,nT=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),ao=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};Gc=new Map});var Pi=I(()=>{"use strict"});function CT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function RT(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function qy(e){let t=CT(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!bT.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Ly)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!ST.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!kT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!xT.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!ET.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Ly,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:RT(t.createdAt,"Native portable migration transaction createdAt")}}var Ly,bT,kT,ST,ET,xT,My=I(()=>{"use strict";qc();nf();xt();Pi();no();Qa();Ly="comet.native.portable-migration.v1",bT=new Set(["schema","id","change","fromSchema","status","createdAt"]),kT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ST=/^[a-z0-9][a-z0-9-]{7,127}$/u,ET=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),xT=new Set([ur,lr,Wt])});import PT from"node:path";function Jy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Uy(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function mf(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function Wy(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function HT(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Jy(e,r);if(Uy(i,OT,r),typeof i.capability!="string"||!Gy.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(p=>p==="."||p==="..")))throw new Error(`${r}.delta_source is invalid`);let o=mf(i.base_hash,`${r}.base_hash`),s=Wy(i.delta_content,`${r}.delta_content`),c=Wy(i.source_content,`${r}.source_content`),l=mf(i.expected_target_hash,`${r}.expected_target_hash`),u=mf(i.result_hash,`${r}.result_hash`),d=a!==void 0;if(d&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(d&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!d&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let p=Gp(s);if(p.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(p.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(Ya(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(Ya(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(p=>p==="."||p===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||Ya(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function DT(e){let t=Jy(e,"Native portable Archive transaction");if(Uy(t,$T,"Native portable Archive transaction"),t.schema!==Vy)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!IT.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Gy.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!TT.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!jT.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(HT);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Vy,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function vf(e){let t=_T.exec(e);if(t)return{kind:"archive",change:t[1]};let r=AT.exec(e);return r?{kind:"migration",change:r[1]}:null}async function Ky(e,t){let r=vf(t);if(!r)return null;let i=await re({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=PT.join(e.transactionsDir,t);if(r.kind==="archive"){let s=DT(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=qy(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function Yy(e){return e.kind==="archive"||e.journal.status!=="committed"}var Vy,zy,_T,AT,IT,TT,jT,$T,OT,Gy,gf=I(()=>{"use strict";at();Jp();My();Vy="comet.native.archive-transaction.v4",zy="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",_T=new RegExp(`^portable-archive-(${zy})\\.json$`,"u"),AT=new RegExp(`^portable-migration-(${zy})\\.json$`,"u"),IT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,TT=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jT=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),$T=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),OT=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),Gy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as Xy}from"node:crypto";import{constants as Wr,promises as me}from"node:fs";import Ge from"node:path";import{TextDecoder as BT}from"node:util";function bn(e,t){let r=Ge.relative(e,t);return r===""||!Ge.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ge.sep}`)}function Qy(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function FT(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Zy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function zr(e,t){return G({...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 Yc(e,t){let r=await me.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await me.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Xc(e,t,r){let i=Ge.resolve(e),n=Ge.resolve(t);if(!bn(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Yc(i,r)],o=i;for(let s of Ge.relative(i,n).split(Ge.sep).filter(Boolean)){await Fe(a,r),o=Ge.join(o,s);let c=await Yc(o,r);if(!bn(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Fe(a,r),a}async function Fe(e,t){for(let r of e){let i=await me.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!FT(r,i)||await me.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function LT(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,t!==null&&n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Gr(e){let t=e.maxBytes===null?null:Qy(e.maxBytes),r=Ge.resolve(e.file),i=await Xc(e.root,Ge.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Yc(Ge.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Fe(i,e.label);let a=await me.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=Zy(a),s=await me.realpath(r);if(!bn(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>bn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Wr.O_RDONLY:Wr.O_RDONLY|Wr.O_NOFOLLOW|Wr.O_NONBLOCK,l=await me.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,p]=await Promise.all([me.lstat(r),me.realpath(r)]);if(await Fe(i,e.label),await Fe(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==s||!zr(o,u)||!zr(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let f=await LT(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),me.lstat(r),me.realpath(r)]);if(await Fe(i,e.label),await Fe(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!zr(o,m)||!zr(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:f,hash:Xy("sha256").update(f).digest("hex"),size:f.length}}finally{await l.close()}}async function wf(e){let t=Ge.resolve(e.file),r=await Xc(e.root,Ge.dirname(t),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(l=>Yc(Ge.resolve(l),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Fe(r,e.label);let n=await me.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let a=Zy(n),o=await me.realpath(t);if(!bn(r[0].realPath,o))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(l=>bn(l.realPath,o)))throw new Error(`${e.label} resolves inside an excluded root`);let s=process.platform==="win32"?Wr.O_RDONLY:Wr.O_RDONLY|Wr.O_NOFOLLOW|Wr.O_NONBLOCK,c=await me.open(t,s);try{let l=await c.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([me.lstat(t),me.realpath(t)]);if(await Fe(r,e.label),await Fe(i,e.label),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!zr(a,l)||!zr(a,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=Xy("sha256"),f=0,m=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:b}=await c.read(m,0,m.length,null);if(b===0)break;f+=b,p.update(m.subarray(0,b))}await e.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat(),me.lstat(t),me.realpath(t)]);if(await Fe(r,e.label),await Fe(i,e.label),!v.isFile()||v.isSymbolicLink()||g!==o||!zr(a,h)||!zr(a,v))throw new Error(`${e.label} changed while reading`);return{hash:p.digest("hex"),size:f}}finally{await c.close()}}async function eN(e){let t=await Gr(e),r;try{r=new BT("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function co(e){let t=await Xc(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await me.readdir(e.directory,{withFileTypes:!0});else{let i=Qy(e.maxEntries);r=[];let n=await me.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Fe(t,e.label),{entries:r,verify:()=>Fe(t,e.label)}}async function yf(e){let t=await Xc(e.root,e.directory,e.label);return{verify:()=>Fe(t,e.label)}}var Ct=I(()=>{"use strict";oe();Lt()});import fr from"path";import{TextDecoder as MT}from"util";function Zc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function el(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function nN(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Nf(e,t){if(typeof e!="string"||e.length===0||fr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Qc(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function tN(e,t){if(Nf(e,t),e.includes("\\")||e!==fr.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function UT(e,t){let r=Zc(e,`transaction operations[${t}]`);if(el(r,WT,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);Nf(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Nf(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function aN(e){let t=Zc(e,"Native Archive transaction journal");if(el(t,zT,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!iN.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!nN(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Qc(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=Zc(s,`Archive transaction operations[${c}]`);if(el(l,GT,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);tN(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&tN(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Qc(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Qc(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Qc(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function KT(e){let t=Zc(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return aN(t);if(el(t,VT,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!iN.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!fr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!fr.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!nN(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(UT),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function YT(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return fr.join(e.transactionsDir,t)}function oN(e,t){let r=YT(e,t);return{directory:r,journal:fr.join(r,"transaction.json"),events:fr.join(r,"events.jsonl"),staged:fr.join(r,"staged"),backups:fr.join(r,"backups")}}async function bf(e,t){let r=oN(e,t);return await Promise.all(Object.values(r).map(i=>V(e.runtimeDir,i))),r}async function kf(e,t,r={}){let i=await bf(e,t),n=await Gr({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(JT.decode(n.bytes)),o=KT(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var VT,WT,zT,GT,iN,JT,tl=I(()=>{"use strict";oe();K();Ct();VT=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),WT=new Set(["id","type","source","target","staged","backup"]),zT=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),GT=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),iN=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),JT=new MT("utf-8",{fatal:!0})});import{promises as XT}from"fs";import QT from"path";async function ZT(e,t,r){let i;try{i=await XT.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await kf(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(vf(n.name))try{let a=await Ky(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Yy(a))return!0}catch{return!0}return!1}async function ej(e,t){let r=Date.now()+5e3,i=QT.join(e.locksDir,"root-move.lock");for(;;)try{return await Dc(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await fy(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await hy(e,i,o);if(s.status==="removed"||s.status==="missing")continue;throw n}if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function Ce(e,t,r,i){let n=await ej(e,t);try{if(await _c(e.projectRoot),await ZT(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Bc(n)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${n.file} (${a.message}); run comet native doctor --repair if commands start failing
|
|
173
|
+
`)}}}var Re=I(()=>{"use strict";Qe();Ka();gf();tl()});import{createHash as sN}from"crypto";import{createReadStream as tj}from"fs";async function Sf(e){let t=sN("sha256");for await(let r of tj(e))t.update(r);return t.digest("hex")}function ee(e){return sN("sha256").update(e).digest("hex")}var Ut=I(()=>{"use strict"});import{createHash as ol}from"crypto";import{spawn as gN}from"node:child_process";import{promises as ne}from"fs";import F from"path";import{performance as cN}from"node:perf_hooks";function yN(e){let t=e.deadlineMs??yj;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Rt(e){return Math.max(0,e.deadlineAt-Date.now())}function H(e){return Rt(e)>=1}function Ef(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 En(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function Sj(e,t){let r={...kj,...t===void 0?{}:{maxNodes:t},...e};if(!Number.isSafeInteger(r.maxNodes)||r.maxNodes<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxPathBytes)||r.maxPathBytes<1||r.maxPathBytes>r.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return r}async function Ej(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&F.win32.isAbsolute(i)?F.win32.resolve(i):"C:\\Windows",a=F.win32.join(n,"System32","taskkill.exe");if(!F.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=(p,f=!1)=>{c||(c=!0,u&&clearTimeout(u),f&&l?.kill("SIGKILL"),s(p))};try{l=gN(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",p=>d(p===0)),u=setTimeout(()=>d(!1,!0),Nj),u.unref()}catch{d(!1)}});for(let s=0;s<bj;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(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function Af(e,t,r,i){let n=Rt(e);if(n<1)throw Ef();let a=e.gitProcess,o=cN.now(),s=gN(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),c=null,l=!1,u=null;s.once("error",m=>{c=m});let d=new Promise(m=>{s.once("close",m)}),p=setTimeout(()=>{l=!0,u=Ej(s,a).then(()=>({error:null}),m=>({error:m}))},n);p.unref();let f=d.then(async m=>{if(clearTimeout(p),l){let h=await u;throw h?.error?Ef(h.error):Ef()}return{code:m,spawnError:c}}).finally(()=>cs(cN.now()-o));return{child:s,completion:f}}function NN(e,t){let r={..._f,...t===void 0?{}:{maxRecords:t},...e};if(!Number.isSafeInteger(r.maxRecords)||r.maxRecords<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxRecordBytes)||r.maxRecordBytes<1||r.maxRecordBytes>r.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return r}async function il(e,t,r,i=Rf){let{child:n,completion:a}=Af(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",f=>{let m=Math.max(0,i-l);m>0&&o.push(Buffer.from(f).subarray(0,m)),l+=f.byteLength,l>i&&(u=!0)}),n.stderr.on("data",f=>{if(c>=Cn)return;let m=Cn-c,h=Buffer.from(f).subarray(0,m);s.push(h),c+=h.byteLength});let{code:d,spawnError:p}=await a;if(d===0&&p===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${p?`: ${p.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function xf(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function uo(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.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}=Af(e,t,r,i.stdin!==void 0),c=[],l=ol("sha256"),u=[],d=0,p=0,f=0,m=0,h=Buffer.alloc(0),v=!1,g=!1,b=!1,k=N=>{let x=0;for(;x<N.byteLength;){let w=N.indexOf(0,x),S=w<0?N.byteLength:w,E=N.subarray(x,S);if(!v&&E.byteLength>0&&(h.byteLength+E.byteLength>i.maxRecordBytes?(h=Buffer.alloc(0),v=!0,g=!0):h=Buffer.concat([h,E])),w<0)break;m+=1,h.byteLength===0&&!v&&(b=!0);let y=h.byteLength+1;!v&&m<=i.maxRecords&&f+y<=i.maxBytes?(c.push(h),f+=y):g=!0,h=Buffer.alloc(0),v=!1,x=w+1}};o.stdout.on("data",N=>{l.update(N),p+=N.byteLength,p>i.maxBytes&&(g=!0);let x=i.outputChunkBytes;if(x===void 0){k(N);return}for(let w=0;w<N.byteLength;w+=x)k(N.subarray(w,Math.min(N.byteLength,w+x)))}),o.stderr.on("data",N=>{if(d>=Cn)return;let x=Cn-d,w=Buffer.from(N).subarray(0,x);u.push(w),d+=w.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:x})=>{let w=i.acceptedExitCodes??[0];if(N!==null&&w.includes(N)&&x===null&&!b&&h.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:m,stdoutBytes:p});return}a(new Error(`git ${r.join(" ")} failed${x?`: ${x.message}`:b||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function nl(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 xj(e,t,r){if(r.length===0)return new Set;let i=await uo(e,t,["check-ignore","--no-index","-z","--stdin"],{..._f,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=nl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function Cj(e,t,r){let{child:i,completion:n}=Af(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=Cn)return;let d=Cn-o,p=Buffer.from(u).subarray(0,d);a.push(p),o+=p.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function xn(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||F.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||F.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function Rj(e,t){return e.map(r=>{let i=xn(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function Pj(e){let t=F.resolve(e);for(;;){try{return await ne.lstat(F.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=F.dirname(t);if(r===t)return!1;t=r}}function _j(e){return e?e.filter(t=>t&&!t.startsWith("!")).flatMap(t=>t.includes("**")?[`:(exclude,glob)${t}`]:[`:(exclude)${t}`]):[]}async function bN(e,t,r,i={},n){let a=F.resolve(t.projectRoot),o=F.join(a,".comet","current-change.json"),c=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,o].map(f=>{let m=F.relative(a,F.resolve(f)).replaceAll("\\","/"),h=xn(m);if(h===null)throw new Error("Native Git snapshot exclusion escaped the project root");return h}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`]),..._j(n)],l={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},u=await uo(e,a,["ls-files","--stage","-z",...c],l);await i.afterStageBefore?.();let d=await uo(e,a,["ls-files","--cached","--others","--exclude-standard","-z",...c],l);await i.afterCombined?.();let p=await uo(e,a,["ls-files","--stage","-z",...c],l);return{stagedBefore:u,combined:d,stagedAfter:p}}function kN(e){return{stageBefore:xf(e.stagedBefore),combined:xf(e.combined),stageAfter:xf(e.stagedAfter)}}async function SN(e,t,r=_f,i={},n){let a=F.resolve(t.projectRoot);if(!await Pj(a))return null;let o;try{o=await il(e,a,["rev-parse","--is-inside-work-tree"])}catch(k){throw En(k)?k:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:k})}if(o.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let s;try{s=await bN(e,t,r,i,n)}catch(k){throw En(k)?k:new Error("Native Git snapshot provider failed after repository detection",{cause:k})}let{stagedBefore:c,combined:l,stagedAfter:u}=s,d=new Set,p=new Map,f=new Set,m=k=>{for(let N of k){let x=nl(N),w=x.indexOf(" ");if(w<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let S=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(x.slice(0,w))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let E=xn(x.slice(w+1));if(E===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");d.add(E),S.stage==="0"&&p.set(E,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(E)}};m(c.records),m(u.records);let h=l.records.map(nl),v=Rj(h,"combined"),g=new Set(v.filter(k=>!d.has(k))),b=new Set(v.filter((k,N)=>!d.has(k)&&h[N].endsWith("/")));for(let k of f)b.delete(k);return{tracked:d,trackedObjectIds:p,untracked:g,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:kN(s)}}function Ur(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function lN(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function Aj(e,t){return!Ur(e.stageBefore,e.stageAfter)||!Ur(e.stageAfter,t.stageBefore)||!Ur(e.combined,t.combined)||!Ur(t.stageBefore,t.stageAfter)}async function EN(e,t,r,i,n,a){let o;try{o=await bN(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}},a)}catch(d){throw En(d)?d:new Error("Native Git snapshot provider failed during its final selection fence",{cause:d})}let s=i.initialFence,c=kN(o),l=lN(s)||lN(c),u=Aj(s,c);l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),u&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.evidence=l||u?{schema:"comet.native.git-selection.v1",status:l&&u?"overflow-and-changed":l?"overflow":"changed",...s,finalStageBefore:c.stageBefore,finalCombined:c.combined,finalStageAfter:c.stageAfter}:null,(s.combined.overflow||c.combined.overflow)&&(i.overflow={count:Math.max(1,s.combined.recordCount-s.combined.storedRecordCount,c.combined.recordCount-c.combined.storedRecordCount),hash:ee(`comet.native.git-selection-overflow.v2
|
|
174
|
+
${JSON.stringify({initial:s.combined,final:c.combined})}`)})}function Tj(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function uN(e){let t=F.resolve(e.paths.projectRoot),r=F.resolve(e.paths.nativeRoot),i=F.resolve(e.paths.runtimeDir),n=F.resolve(e.paths.configFile),a=F.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,p=0,f=!1,m=!1,h=!1,v=()=>Rt(e.execution)>=1?!0:(f=!0,h=!0,!1),g=N=>{let x=Buffer.from(`${N.type}\0${N.path}`,"utf8"),w=ol("sha256").update("comet.native.physical-selection-record.v1\0").update(x).digest();for(let S=0;S<c.length;S+=1)c[S]^=w[S];if(l=l+BigInt(`0x${w.toString("hex")}`)&Ij,d+=1,p+=x.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||p>e.limits.maxBytes){f=!0,h=!0;return}o.push(N)},b=async N=>{if(h||!v())return;let x;try{x=await ne.opendir(N)}catch(C){if(!v())return;if(!ge(C)&&!ve(C)||N===t&&ge(C))throw C;m||=ve(C),f||=ge(C),h=!0;return}if(!v()){try{await x.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let w=!1,S;try{for(;!h&&v();){let C;try{C=await x.read()}catch(Z){if(!v())break;if(!ge(Z)&&!ve(Z)||N===t&&ge(Z))throw Z;m||=ve(Z),f||=ge(Z),h=!0;break}if(!v()||C===null)break;if(u+=1,u>e.limits.maxNodes){f=!0,h=!0;break}let O=F.join(N,C.name),T=$j(t,O);if(O===n||O===a||Pt(r,O)||Pt(i,O)||e.denylist.some(Z=>Pt(Z,O))||Ft(T)!==null)continue;if(!v())break;let Q;try{Q=await ne.lstat(O)}catch(Z){if(!v())break;if(!ge(Z)&&!ve(Z))throw Z;if(m=!0,g({path:T,type:"other"}),s.push({path:T,size:null,type:"file",reason:ge(Z)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!v())break;continue}if(!v())break;let Te=Tj(Q);if(Te==="directory"){if(Bj(e.policy,T))continue;if(!v())break;let Z;try{Z=await ne.realpath(O)}catch(Ot){if(!v())break;if(!ge(Ot)&&!ve(Ot))throw Ot;if(m=!0,g({path:T,type:Te}),s.push({path:T,size:null,type:"directory",reason:ge(Ot)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!v())break;continue}if(!v())break;if(!q(e.physicalProjectRoot,Z)||Pt(e.physicalNativeRoot,Z))continue;if(g({path:T,type:Te}),await e.hooks?.afterNode?.(T),!v()||(await b(O),h))break;continue}if(g({path:T,type:Te}),await e.hooks?.afterNode?.(T),!v()||h)break}}catch(C){w=!0,S=C}let E;try{await x.close()}catch(C){E=C}let y=v();if(w)throw S;if(y&&E!==void 0&&E.code!=="ERR_DIR_CLOSED")throw E};await b(t),v(),f?(o.length=0,d=0,p=0):(o.sort((N,x)=>N.path.localeCompare(x.path,"en")),s.sort((N,x)=>N.path.localeCompare(x.path,"en")));let k=f?ee(`comet.native.physical-selection-incomplete.v1
|
|
171
175
|
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):ee(`comet.native.physical-selection.v1
|
|
172
|
-
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:p,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:k,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:p,overflow:f,unstable:m}}}function
|
|
173
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function
|
|
176
|
+
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:p,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:k,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:p,overflow:f,unstable:m}}}function xN(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 jj(e,t){let r=e.overflow||t.overflow,i=e.unstable||t.unstable||!xN(e,t),n=[];return r&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),i&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:r||i?{schema:"comet.native.physical-selection.v1",status:r&&i?"overflow-and-changed":r?"overflow":"changed",before:e,after:t}:null}}function CN(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,r)=>t.localeCompare(r,"en"))}async function dN(e,t){let i=(await il(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!wN.test(i))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return ee(`gitlink:${i}`)}async function pN(e,t){let r=await dN(e,t),i=await Cj(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await dN(e,t);if(n!==r)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:i}}function lo(e,t){if(Ft(t)!==null)return!1;let r=F.resolve(e.projectRoot,...t.split("/"));return!Pt(F.resolve(e.nativeRoot),r)&&!Pt(F.resolve(e.runtimeDir),r)}function $j(e,t){return F.relative(e,t).split(F.sep).join("/")}function Oj(e,t){return t.map(r=>F.resolve(e,...r.split(/[\\/]/u)))}function Pt(e,t){let r=F.resolve(e),i=F.resolve(t);return i===r||q(r,i)}function ge(e){return wj.has(e.code??"")}function ve(e){return e.code==="ENOENT"}function Hj(e,t){return ee(`comet.native.snapshot-policy.v1
|
|
177
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Cf(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function Dj(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function fN(e){let t=Pc(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?Dj(n):void 0;if(a&&!a())return!1;let o=Cf(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[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=Cf(r,c,a),o===null||o.size===0)return!1}return Cf(r,o,a)?.has(r.length)??!1}}function RN(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Pc(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>Pc(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 i=Hj(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(fN),excludeMatchers:r.map(fN),excludedDirectoryPrefixes:r.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 Bj(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function hN(e,t,r){if(!e)return!0;let i=()=>H(r),n=!1;for(let a of e.includeMatchers){if(!i())return!1;if(a(t,i)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!i()||a(t,i))return!1;return!0}function al(e,t,r){let i=JSON.stringify(r);return ee(`${e}
|
|
174
178
|
${Buffer.byteLength(t)}:${t}
|
|
175
|
-
${Buffer.byteLength(i)}:${i}`)}function wN(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function yN(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!wN(r))return e.splice(t,1),r}return null}function Jr(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Rj(e,t,r,i){if(!H(i))return{status:"budget-exhausted"};let n;try{n=await ne.open(e,"r")}catch(c){if(!H(i))return{status:"budget-exhausted"};throw c}if(!H(i))return await n.close(),{status:"budget-exhausted"};let a=nl("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!H(i))return{status:"budget-exhausted"};let c=await n.stat();if(!H(i))return{status:"budget-exhausted"};if(!c.isFile()||!Jr(r,c))return{status:"changed"};for(;;){if(!H(i))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(!H(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!H(i))return{status:"budget-exhausted"};let d=await n.stat();return H(i)?!d.isFile()||!Jr(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 lt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ut(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function kn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Kt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function NN(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 r=F.posix.normalize(e);if(r!==e||F.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function Pj(e,t){let r=lt(e,`Native snapshot entry ${t}`);ut(r,ej,`Native snapshot entry ${t}`);let i=NN(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!al.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Kt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!cN.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function _j(e,t){let r=lt(e,`Native snapshot omission ${t}`);if(ut(r,tj,`Native snapshot omission ${t}`),!nj.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!aj.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:NN(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Kt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function Aj(e){let t=lt(e,"Native snapshot omission overflow");if(ut(t,rj,"Native snapshot omission overflow"),typeof t.hash!="string"||!al.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:kn(t.count,"Native snapshot omission overflow count")}}function bn(e,t){let r=lt(e,t);if(ut(r,XT,t),typeof r.hash!="string"||!al.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Kt(r.recordCount,`${t} recordCount`),n=Kt(r.storedRecordCount,`${t} storedRecordCount`),a=Kt(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function aN(e){let t=lt(e,"Native Git selection evidence");if(ut(t,YT,"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 r=bn(t.stageBefore,"Native Git selection stageBefore"),i=bn(t.combined,"Native Git selection combined"),n=bn(t.stageAfter,"Native Git selection stageAfter"),a=bn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=bn(t.finalCombined,"Native Git selection finalCombined"),s=bn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Ur(r,n)||!Ur(n,a)||!Ur(i,o)||!Ur(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:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function oN(e,t){let r=lt(e,t);if(ut(r,ZT,t),typeof r.hash!="string"||!al.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Kt(r.visitedNodeCount,`${t} visitedNodeCount`),n=Kt(r.recordCount,`${t} recordCount`),a=Kt(r.storedRecordCount,`${t} storedRecordCount`),o=Kt(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function Ij(e){let t=lt(e,"Native physical selection evidence");if(ut(t,QT,"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 r=oN(t.before,"Native physical selection before"),i=oN(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!mN(r,i);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:r,after:i}}function Pi(e){let t=lt(e,"Native content snapshot manifest");if(ut(t,zT,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!ij.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let w=lt(t.capture,"Native content snapshot capture");if(ut(w,UT,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let S=w.gitSelection===void 0?void 0:aN(w.gitSelection),E=w.physicalSelection===void 0?void 0:Ij(w.physicalSelection),y=null;if(w.projection!==void 0){let C=lt(w.projection,"Native content snapshot projection");if(ut(C,KT,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");y={provider:"git",...C.selection===void 0?{}:{selection:aN(C.selection)}}}if(w.provider==="git"){if(E||y)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...S?{gitSelection:S}:{}}}else{if(S)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(E&&y)throw new Error("Native physical-tree capture cannot combine selection and projection");r=y?{provider:"physical-tree",projection:y}:{provider:"physical-tree",...E?{physicalSelection:E}:{}}}}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 i=lt(t.limits,"Native content snapshot limits");ut(i,GT,"Native content snapshot limits");let n={maxFiles:kn(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:kn(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:kn(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:kn(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:kn(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=lt(t.policy,"Native snapshot policy");if(ut(w,JT,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=gN({include:w.include,exclude:w.exclude,hash:w.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(Pj),s=t.omitted.map(_j),c=Kt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:Aj(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>n.maxFileBytes)||o.reduce((w,S)=>w+S.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Ef||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(w=>w.reason==="git-enumeration-limit"),p=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...d,...p])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||p.length>1)throw new Error("Native Git selection omissions must not be duplicated");let f=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=f?.status==="overflow"||f?.status==="overflow-and-changed",h=f?.status==="changed"||f?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(p.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(w=>w.reason==="physical-enumeration-limit"),g=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...v,...g])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,k=b?.status==="overflow"||b?.status==="overflow-and-changed",N=b?.status==="changed"||b?.status==="overflow-and-changed";if(k!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}async function bN(e,t,r={}){let i=Pi(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=F.resolve(e.projectRoot),a=lN(r),o=uN(r.gitSelectionLimits),s=await fN(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(vN(s).filter(S=>co(e,S))),l=[...s.gitlinks].filter(S=>c.has(S)),u=[...s.nestedRepositories].filter(S=>co(e,S)),d=(S,E)=>E.some(y=>S===y||S.startsWith(`${y}/`)),p=S=>d(S,l),f=S=>d(S,u),m=[...i.entries.map(S=>S.path),...i.omitted.flatMap(S=>S.type==="directory"?[S.path,`${S.path}/`]:[S.path])].filter(S=>!c.has(S)&&!p(S)&&!f(S)),h=await fj(a,n,m),v=i.entries.filter(S=>!p(S.path)&&!f(S.path)&&co(e,S.path)&&(c.has(S.path)||!h.has(S.path)));await hN(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let S of l)g.push({path:S,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((S,E)=>S.path.localeCompare(E.path,"en"));let b=i.omitted.filter(S=>p(S.path)||f(S.path)||!co(e,S.path)?!1:h.has(S.path)?c.has(S.path)||[...c].some(E=>E.startsWith(`${S.path}/`)):!0);for(let S of g)b.some(E=>E.path===S.path&&E.reason===S.reason)||b.push(S);b.sort((S,E)=>S.path.localeCompare(E.path,"en"));let k=i.omissionOverflow?.count??0,N=i.omissionOverflow?.hash??ee("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,N=il(N,"git-selection",{source:"git-selection",...s.overflow}));let x=S=>{k+=1,N=il(N,"omission",S)};for(;b.length>Ef;){let S=yN(b);if(S===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");x(S)}return Pi({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:b.length+k===0,entries:v,omitted:b,omittedCount:b.length+k,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:k}}:{}})}function Tj(e,t){if(!WT.test(t))throw new Error(`Invalid Native change name: ${t}`);return F.join(Y(e,t),"baseline-manifest.json")}async function kN(e,t={}){let r={maxFiles:t.limits?.maxFiles??el.maxFiles,maxFileBytes:t.limits?.maxFileBytes??el.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??el.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??el.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=gN(t.policy),n=lN({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=uN(t.gitSelectionLimits,t.maxSelectionRecords),o=dj(t.physicalSelectionLimits,t.maxSelectionRecords);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=F.resolve(e.projectRoot),c=await ne.realpath(s),l=F.resolve(e.nativeRoot),u=await ne.realpath(l),d=F.resolve(e.runtimeDir),p=F.resolve(e.configFile),f=F.join(s,".comet","current-change.json"),m=Sj(s,t.denylist??[]),h=[],v=[],g=new Map,b=new Map,k=0,N=0,x=ee("comet.native.snapshot-omission-overflow.v1"),w=0,S=!1,E=null,y=_=>{N+=1,x=il(x,"omission",_)},C=_=>{if(k+=1,v.length<Ef){v.push(_);return}if(wN(_)){let A=yN(v);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(A),v.push(_);return}y(_)},O=_=>{k+=_.count,N+=_.count,x=il(x,"git-selection",{source:"git-selection",..._})},T=async(_,A)=>{h.push(_),w+=_.size,g.set(_.path,A),S||(S=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Q=(_,A)=>{let $=h.findIndex(te=>te.path===_);if($<0)return;let[W]=h.splice($,1);w-=W.size,g.delete(_),C(A)},Te=async(_,A,$,W)=>{if(!$.isFile()||$.isSymbolicLink()||!H(n))return;let te;try{te=await ne.realpath(_)}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;C({path:A,size:$.size,type:"file",reason:ve(P)?"changed-during-read":"unreadable"});return}if(!H(n)||!q(c,te)||Pt(u,te))return;if(h.length>=r.maxFiles){C({path:A,size:$.size,type:"file",reason:"file-count"});return}if($.size>r.maxFileBytes){C({path:A,size:$.size,type:"file",reason:"file-size"});return}if(w+$.size>r.maxTotalBytes){C({path:A,size:$.size,type:"file",reason:"total-size"});return}let J,D,le;try{if(J=await Rj(te,$.size,$,n),J.status==="budget-exhausted"||!H(n))return;if(J.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!H(n)||(le=await ne.realpath(_),!H(n)))return;D=await ne.lstat(_)}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;C({path:A,size:$.size,type:"file",reason:ve(P)?"changed-during-read":"unreadable"});return}if(H(n)){if(J.bytes!==$.size||le!==te||!Jr($,J.finalStat)||!Jr(J.finalStat,D)||!D.isFile()||D.isSymbolicLink()||D.size!==$.size||D.mtimeMs!==$.mtimeMs||D.ctimeMs!==$.ctimeMs){C({path:A,size:D.isFile()?D.size:null,type:D.isFile()?"file":"other",reason:"changed-during-read"});return}H(n)&&await T({path:A,hash:J.hash,size:D.size,type:"file",...W===void 0?{}:{gitObjectId:W}},{kind:"file",target:_,realTarget:te,stat:D})}},Z=async(_,A,$)=>{if(!H(n))return;let W,te,J;try{if(W=await ne.readlink(_,{encoding:"buffer"}),!H(n)||(J=await ne.lstat(_),!H(n)))return;te=await ne.readlink(_,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;C({path:A,size:null,type:"other",reason:ve(P)?"changed-during-read":"unreadable"});return}if(!H(n))return;if(!J.isSymbolicLink()||!Jr($,J)||J.mtimeMs!==$.mtimeMs||J.ctimeMs!==$.ctimeMs||!W.equals(te)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let D=W.byteLength;if(h.length>=r.maxFiles){C({path:A,size:D,type:"other",reason:"file-count"});return}if(D>r.maxFileBytes){C({path:A,size:D,type:"other",reason:"file-size"});return}if(w+D>r.maxTotalBytes){C({path:A,size:D,type:"other",reason:"total-size"});return}let le=nl("sha256").update("symlink\0").update(W).digest("hex");H(n)&&await T({path:A,hash:le,size:D,type:"file"},{kind:"symlink",target:_,rawTarget:W,stat:J})},Ot=async()=>{for(let[_,A]of[...g]){if(!H(n))return;if(A.kind==="file"){let D,le;try{if(D=await ne.realpath(A.target),!H(n))return;le=await ne.lstat(A.target)}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;Q(_,{path:_,size:null,type:"file",reason:ge(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(D!==A.realTarget||!le.isFile()||le.isSymbolicLink()||!Jr(A.stat,le)||le.size!==A.stat.size||le.mtimeMs!==A.stat.mtimeMs||le.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:le.isFile()?le.size:null,type:le.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let D,le;try{if(D=await ne.lstat(A.target),!H(n))return;le=await ne.readlink(A.target,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;Q(_,{path:_,size:null,type:"other",reason:ge(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(!D.isSymbolicLink()||!Jr(A.stat,D)||D.mtimeMs!==A.stat.mtimeMs||D.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(le))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let $,W;try{if($=await ne.realpath(A.target),!H(n))return;W=await ne.lstat(A.target)}catch{if(!H(n))return;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;if(!($===A.realTarget&&W.isDirectory()&&!W.isSymbolicLink()&&Jr(A.stat,W)&&q(c,$)&&!Pt(u,$))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let J;try{if(!H(n))return;J=await rN(n,$)}catch(D){if(Sn(D))throw D;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;J.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):J.hash!==A.hash&&Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of b){if(!H(n))return;try{let $=await ne.lstat(A);if(!H(n))return;C({path:_,size:$.isFile()?$.size:null,type:$.isFile()?"file":$.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch($){if(!H(n))return;if(ve($))continue;if(!ge($))throw $;C({path:_,size:null,type:"file",reason:"unreadable"})}}},ce=await fN(n,e,a,t.gitSelectionHooks,i?.manifest.exclude);if(ce===null){let _=await eN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let W of _.records){if(W.type!=="file"&&W.type!=="symlink"||g.has(W.path))continue;if(Rt(n)<1)break;if(!nN(i,W.path,n))continue;if(Rt(n)<1)break;let te=F.resolve(s,...W.path.split("/")),J;try{J=await ne.lstat(te)}catch(D){if(!H(n))break;if(!ge(D)&&!ve(D))throw D;C({path:W.path,size:null,type:"file",reason:ve(D)?"changed-during-read":"unreadable"});continue}if(Rt(n)<1)break;if(W.type==="symlink"&&J.isSymbolicLink()){if(await Z(te,W.path,J),Rt(n)<1)break;continue}if(W.type!=="file"||!J.isFile()||J.isSymbolicLink()){C({path:W.path,size:J.isFile()?J.size:null,type:J.isDirectory()?"directory":J.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Te(te,W.path,J),Rt(n)<1)break}Rt(n)>=1&&await Ot();let A=await eN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o}),$=bj(_.evidence,A.evidence);E=$.evidence;for(let W of[..._.omissions,...A.omissions,...$.omissions])v.some(te=>te.path===W.path&&te.reason===W.reason)||C(W)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,$=!1;if(_){let P=Pi(_);for(let ae of P.entries)ae.gitObjectId!==void 0&&A.set(ae.path,ae);$=A.size>0}let W=new Set,te=!0;try{let P=await lo(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(P.overflow)$=!1,te=!1,A.clear();else for(let ae of P.records){let ue=rl(ae),je=ue.indexOf(" "),Pe=je<0?null:En(ue.slice(je+1));if(je!==1||Pe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ue[0]!=="H"&&W.add(Pe)}}catch(P){if(Sn(P))throw P;$=!1,te=!1,A.clear()}let J=new Set;try{let P=await tl(n,s,["ls-files","--modified","-z"],Sf);for(let ae of P.toString("utf8").split("\0")){let ue=En(ae);ue!==null&&J.add(ue)}}catch{$=!1,te=!1,A.clear()}let D=new Set,le=new Set;for(let P of vN(ce)){if(g.has(P)||!co(e,P))continue;if(Rt(n)<1)break;if(!nN(i,P,n))continue;if(Rt(n)<1)break;let ae=F.resolve(s,...P.split("/"));if(ae===p||ae===f||Pt(d,ae)||m.some(Ye=>Pt(Ye,ae)))continue;if(ce.gitlinks.has(P)){if(h.length>=r.maxFiles){C({path:P,size:0,type:"file",reason:"file-count"});continue}let Ye,is;try{[Ye,is]=await Promise.all([ne.realpath(ae),ne.lstat(ae)])}catch{C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(is.isSymbolicLink()||!is.isDirectory()||!q(c,Ye)||Pt(u,Ye)){C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let zi=await rN(n,Ye);if(zi.dirty){C({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await T({path:P,hash:zi.hash,size:0,type:"file"},{kind:"gitlink",target:ae,realTarget:Ye,stat:is,hash:zi.hash})}catch(zi){if(Sn(zi))throw zi;C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ue;try{ue=await ne.lstat(ae)}catch(Ye){if(ve(Ye)&&ce.tracked.has(P)){b.set(P,ae);continue}if(!ge(Ye)&&!ve(Ye))throw Ye;C({path:P,size:null,type:"file",reason:ve(Ye)?"changed-during-read":"unreadable"});continue}if(ue.isSymbolicLink()){await Z(ae,P,ue);continue}if(!ue.isFile()){ce.nestedRepositories.has(P)||C({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let je=ce.trackedObjectIds.get(P),Pe=je?A.get(P):void 0;if($&&Pe?.gitObjectId!==void 0&&Pe.gitObjectId===je&&!W.has(P)&&!J.has(P)){if(h.length>=r.maxFiles){C({path:P,size:Pe.size,type:"file",reason:"file-count"});continue}if(Pe.size>r.maxFileBytes){C({path:P,size:Pe.size,type:"file",reason:"file-size"});continue}if(w+Pe.size>r.maxTotalBytes){C({path:P,size:Pe.size,type:"file",reason:"total-size"});continue}h.push({...Pe}),w+=Pe.size,D.add(P);continue}let xm=te&&!W.has(P)&&!J.has(P)?je:void 0;await Te(ae,P,ue,xm),xm!==void 0&&le.add(P)}if(await Ot(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await hN(n,e,a,ce,t.gitSelectionHooks?.outputChunkBytes,i?.manifest.exclude),D.size>0||$&&le.size>0){let P=await tl(n,s,["ls-files","--modified","-z"],Sf),ae=new Set;for(let ue of P.toString("utf8").split("\0")){let je=En(ue);je!==null&&ae.add(je)}for(let ue of D){if(!ae.has(ue))continue;let je=h.find(Pe=>Pe.path===ue);Q(ue,{path:ue,size:je?.size??null,type:"file",reason:"changed-during-read"})}for(let ue of le){if(!ae.has(ue))continue;let je=h.find(Pe=>Pe.path===ue);je&&delete je.gitObjectId}}for(let P of ce.omissions)C(P);ce.overflow&&O(ce.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let DE=ce===null?{provider:"physical-tree",...E?{physicalSelection:E}:{}}:{provider:"git",...ce.evidence?{gitSelection:ce.evidence}:{}};return{schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:DE,createdAt:(t.now??new Date).toISOString(),complete:k===0,limits:r,...i?{policy:i.manifest}:{},entries:h,omitted:v,omittedCount:k,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${x}`,hash:x,count:N}}:{}}}async function Rf(e,t,r={}){let n=(await xe(e.projectRoot))?.native.snapshot??Pp;return kN(e,{...r,policy:t.policy,incrementalBaseline:t,maxSelectionRecords:n.max_selection_records,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 ol(e,t){let r=Tj(e,t),i=Ne(e,r);await V(i,r);try{let n=await Wy({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return Pi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var el,Ef,WT,zT,GT,JT,UT,KT,YT,XT,QT,ZT,ej,tj,rj,ij,nj,aj,al,cN,oj,xn,Sf,sj,cj,lj,xf,uj,yj,Cn=I(()=>{"use strict";Gi();oe();Qe();Ut();Lt();K();Ct();Ha();el={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},Ef=1e3,WT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zT=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),GT=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),JT=new Set(["schema","include","exclude","hash"]),UT=new Set(["provider","gitSelection","physicalSelection","projection"]),KT=new Set(["provider","selection"]),YT=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),XT=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),QT=new Set(["schema","status","before","after"]),ZT=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),ej=new Set(["path","hash","size","type","gitObjectId"]),tj=new Set(["path","size","type","reason"]),rj=new Set(["ref","hash","count"]),ij=new Set(["change-created","legacy-migration","explicit"]),nj=new Set(["file","directory","other"]),aj=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"]),al=/^[a-f0-9]{64}$/u,cN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,oj=new Set(["EACCES","EPERM"]),xn=64*1024,Sf=64*1024,sj=6e4,cj=1e3,lj=2,xf={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},uj={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};yj=(1n<<256n)-1n});import{execFileSync as $$}from"node:child_process";function D$(e,t){try{return Qn(()=>$$("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:O$,maxBuffer:H$,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Mf(e,t,i)}}function Je(e,t){return D$(e,t).trim()}var O$,H$,Mf,pt=I(()=>{"use strict";Gi();O$=3e4,H$=8*1024*1024,Mf=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{promises as V0}from"node:fs";import W0 from"node:path";function Il(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Al(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Ab(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function Y0(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function Ib(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Ob(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===sh&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!Tb(e.children,l)),jb(i)?i:null}if(e.schema===$i&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!Tb(e.children,a)),jb(i)?i:null}return null}function Tb(e,t){return e.some(r=>r.covers.includes(t))}function jb(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Zr(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function X0(e){let t=Il(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=Il(n,`Native children acceptance_index.${i}`);if(Al(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function Q0(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let p=["source","text"].filter(f=>d[f]!==u[f]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${p.join(", ")} exactly from the current acceptance catalog`)}}}function Hb(e,t,r={}){let i=(0,$b.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Il(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==$i&&a!==Qr)throw Al(n,_b,"Native children contract"),new Error(`Native children schema must be ${$i} or ${Qr}`);let o=a===$i?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Al(n,o==="indexed-v2"?G0:_b,"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((p,f)=>{let m=Il(p,`Native child ${f}`);if(Al(m,o==="indexed-v2"?K0:o==="summary-v2"?U0:J0,`Native ${s} child fields (child ${f})`),typeof m.name!="string"||!z0.test(m.name))throw new Error(`Native child ${f} name is invalid`);let h=o==="summary-v2";if(h){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:h?m.summary:null,depends_on:Ab(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Ab(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:p})=>p);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let p of c){let f=p.depends_on.filter(m=>!u.has(m));if(f.length>0)throw new Error(`Native child ${p.name} depends on unknown child: ${f.join(", ")}`)}Y0(c);let d=r.policy==="advisory";if(a===sh){if(o==="indexed-v2"){let p=X0(n.acceptance_index);d||Q0(p,t,r);let f=Object.keys(p);return d||Ib(c,f,f),{schema:Qr,acceptance_index:p,children:c}}return{schema:Qr,children:c}}return t&&!d&&Ib(c,t),{schema:$i,children:c}}async function Qt(e){let t=W0.join(e.changeDir,oh);try{await V0.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await re({root:e.changeDir,ref:oh}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Hb(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Ob(a,e.acceptanceIds,e.validation??{}):null}}var $b,oh,$i,Qr,sh,z0,_b,G0,J0,U0,K0,Tl=I(()=>{"use strict";$b=ir(Bt(),1);at();oh="children.yaml",$i="comet.native.children.v1",Qr="comet.native.children.v2",sh=Qr,z0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_b=new Set(["schema","children"]),G0=new Set(["schema","acceptance_index","children"]),J0=new Set(["name","depends_on","covers"]),U0=new Set(["name","summary","depends_on"]),K0=new Set(["name","depends_on","covers"])});var Ro=I(()=>{"use strict"});var jl=I(()=>{"use strict";qc();Ro()});function gr(e,t){if(!eO.test(e))throw new Error(`${t} must be a Git commit`)}function ch(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function Ol(e){gr(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:lh(e.contract,i.name),contractHash:j("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:Po,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function lh(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function Hl(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:(i.status==="ready"||i.status==="active")&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:i.builderFailureCount??0}));return{contractHash:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var eO,Po,$l,Oi=I(()=>{"use strict";de();jl();eO=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;Po="comet.native.supervisor.v2",$l=3});import _o from"node:path";import{promises as Bb}from"node:fs";function uh(e,t){return _o.join(Et(e,t),"supervisor")}function Ao(e,t){return _o.join(uh(e,t),"state.json")}function Fb(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!==Po)throw new Error(`Native Supervisor state schema must be ${Po}`);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(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(gr(t.integration.targetCommit,"Native Supervisor target commit"),gr(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");gr(n.candidateCommit,"Native Supervisor integration candidate commit"),gr(n.integrationCommit,"Native Supervisor integration check commit"),Db(n.checkStates,"Native Supervisor integration")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.builderFailureCount!==void 0&&(!Number.isSafeInteger(n.builderFailureCount)||n.builderFailureCount<0))throw new Error(`Native Supervisor child ${n.name} Builder failure count 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&&gr(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(gr(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.checkExecution&&Db(n.task.checkExecution.checkStates,`Native Supervisor child ${n.name}`),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 et(e,t,r={}){try{let i=await Bb.readFile(Ao(e,t),"utf8"),n=JSON.parse(i);if(Fb(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(xt(),uf)),c=await s(_o.join(o.changesDir,t,"comet-state.yaml")),l=await Qt({changeDir:_o.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:Zr(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)l.contract.children.some(({name:d})=>d===u.name)&&(u.acceptanceScope=lh(l.contract,u.name),u.contractHash=j("comet.native.supervisor-contract.v1",l.contract),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractHash=u.contractHash,u.task.verificationBoundary="child-scope-parent-reverifies-all",u.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(xt(),uf)),s=await o(_o.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ei(e,t){Fb(t),await Bb.mkdir(e.changesRuntimeDir,{recursive:!0}),await Oe(Ao(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Db(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw new Error(`${t} check states are invalid`);let r=new Set;for(let i of e){if(!i||typeof i.id!="string"||!i.id||r.has(i.id)||typeof i.name!="string"||!["planned","running","passed","failed","interrupted"].includes(i.status)||typeof i.repeatable!="boolean"||!Number.isSafeInteger(i.executionCount)||i.executionCount<0||!Array.isArray(i.argvDisplay)||!i.argvDisplay.every(n=>typeof n=="string")||typeof i.cwdRef!="string"||!Number.isSafeInteger(i.durationMs)||i.durationMs<0||i.exitCode!==null&&!Number.isSafeInteger(i.exitCode)||i.signal!==null&&typeof i.signal!="string"||typeof i.timedOut!="boolean"||i.startedAt!==null&&typeof i.startedAt!="string"||i.completedAt!==null&&typeof i.completedAt!="string"||i.logRef!==null&&typeof i.logRef!="string")throw new Error(`${t} check state is invalid`);r.add(i.id)}}var ti=I(()=>{"use strict";oe();de();Tl();K();Oi()});var dh=I(()=>{"use strict"});function mt(e){return e.replace(tO,"$1 [REDACTED]").replace(rO,"[REDACTED PRIVATE KEY]").replace(iO,"$1[REDACTED]@").replace(nO,"[REDACTED TOKEN]").replace(aO,'$1"[REDACTED]"').replace(oO,"$1$2$1$3$4[REDACTED]$4").replace(sO,"$1$2[REDACTED]")}var tO,rO,iO,nO,aO,oO,sO,Hi=I(()=>{"use strict";tO=/\b(Bearer|Basic)\s+[^\s"']+/giu,rO=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,iO=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,nO=/\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,aO=/("(?:[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,oO=/(["'])((?:[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,sO=/\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});import{accessSync as $G,constants as OG,createWriteStream as HG,existsSync as DG,promises as BG,statSync as uO}from"node:fs";import Di from"node:path";function dO(e,t){let r=Di.relative(e,t);return r===""||!Di.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Di.sep}`)}function Lb(e,t){if(t.length===0||t.includes("\\")||Di.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Di.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Di.resolve(e),i=Di.resolve(r,...t.split("/"));if(!dO(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=uO(i)}catch(a){throw new Error(`Native check cwd does not exist: ${t}`,{cause:a})}if(!n.isDirectory())throw new Error(`Native check cwd is not a directory: ${t}`);return i}var Dl=I(()=>{"use strict";ea();dh();Hi()});var qb=I(()=>{"use strict";pt();Dl();de()});var Bl=I(()=>{"use strict";pt();oe()});import{createHash as ek}from"node:crypto";import Jb from"path";function Ae(e,t){return e<t?-1:e>t?1:0}function gh(e){if(!Nh.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function LO(e,t){return e===t?0:e===null?-1:t===null?1:Ae(e,t)}function ii(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 r=Jb.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||Jb.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function ik(e,t){return e==="."?e:ii(e,t)}function Dn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function qO(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:ii(e.path,`${t} path`),hash:e.hash,size:Dn(e.size,`${t} size`),type:"file"}}function MO(e,t){return{path:ik(e.path,`${t} path`),size:e.size===null?null:Dn(e.size,`${t} size`),type:e.type,reason:e.reason}}function VO(e,t){return Ae(e.path,t.path)||Ae(e.hash,t.hash)||e.size-t.size}function WO(e,t){return Ae(e.path,t.path)||Ae(e.reason,t.reason)||Ae(e.type,t.type)||(e.size??-1)-(t.size??-1)}function $o(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
179
|
+
${Buffer.byteLength(i)}:${i}`)}function PN(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function _N(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!PN(r))return e.splice(t,1),r}return null}function Jr(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Fj(e,t,r,i){if(!H(i))return{status:"budget-exhausted"};let n;try{n=await ne.open(e,"r")}catch(c){if(!H(i))return{status:"budget-exhausted"};throw c}if(!H(i))return await n.close(),{status:"budget-exhausted"};let a=ol("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!H(i))return{status:"budget-exhausted"};let c=await n.stat();if(!H(i))return{status:"budget-exhausted"};if(!c.isFile()||!Jr(r,c))return{status:"changed"};for(;;){if(!H(i))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(!H(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!H(i))return{status:"budget-exhausted"};let d=await n.stat();return H(i)?!d.isFile()||!Jr(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 lt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ut(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Sn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Kt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function AN(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 r=F.posix.normalize(e);if(r!==e||F.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function Lj(e,t){let r=lt(e,`Native snapshot entry ${t}`);ut(r,pj,`Native snapshot entry ${t}`);let i=AN(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!sl.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Kt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!wN.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function qj(e,t){let r=lt(e,`Native snapshot omission ${t}`);if(ut(r,fj,`Native snapshot omission ${t}`),!vj.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!gj.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:AN(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Kt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function Mj(e){let t=lt(e,"Native snapshot omission overflow");if(ut(t,hj,"Native snapshot omission overflow"),typeof t.hash!="string"||!sl.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:Sn(t.count,"Native snapshot omission overflow count")}}function kn(e,t){let r=lt(e,t);if(ut(r,lj,t),typeof r.hash!="string"||!sl.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Kt(r.recordCount,`${t} recordCount`),n=Kt(r.storedRecordCount,`${t} storedRecordCount`),a=Kt(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function mN(e){let t=lt(e,"Native Git selection evidence");if(ut(t,cj,"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 r=kn(t.stageBefore,"Native Git selection stageBefore"),i=kn(t.combined,"Native Git selection combined"),n=kn(t.stageAfter,"Native Git selection stageAfter"),a=kn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=kn(t.finalCombined,"Native Git selection finalCombined"),s=kn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Ur(r,n)||!Ur(n,a)||!Ur(i,o)||!Ur(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:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function vN(e,t){let r=lt(e,t);if(ut(r,dj,t),typeof r.hash!="string"||!sl.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Kt(r.visitedNodeCount,`${t} visitedNodeCount`),n=Kt(r.recordCount,`${t} recordCount`),a=Kt(r.storedRecordCount,`${t} storedRecordCount`),o=Kt(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function Vj(e){let t=lt(e,"Native physical selection evidence");if(ut(t,uj,"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 r=vN(t.before,"Native physical selection before"),i=vN(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!xN(r,i);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:r,after:i}}function _i(e){let t=lt(e,"Native content snapshot manifest");if(ut(t,ij,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!mj.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let w=lt(t.capture,"Native content snapshot capture");if(ut(w,oj,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let S=w.gitSelection===void 0?void 0:mN(w.gitSelection),E=w.physicalSelection===void 0?void 0:Vj(w.physicalSelection),y=null;if(w.projection!==void 0){let C=lt(w.projection,"Native content snapshot projection");if(ut(C,sj,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");y={provider:"git",...C.selection===void 0?{}:{selection:mN(C.selection)}}}if(w.provider==="git"){if(E||y)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...S?{gitSelection:S}:{}}}else{if(S)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(E&&y)throw new Error("Native physical-tree capture cannot combine selection and projection");r=y?{provider:"physical-tree",projection:y}:{provider:"physical-tree",...E?{physicalSelection:E}:{}}}}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 i=lt(t.limits,"Native content snapshot limits");ut(i,nj,"Native content snapshot limits");let n={maxFiles:Sn(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Sn(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Sn(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Sn(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Sn(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=lt(t.policy,"Native snapshot policy");if(ut(w,aj,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=RN({include:w.include,exclude:w.exclude,hash:w.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(Lj),s=t.omitted.map(qj),c=Kt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:Mj(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>n.maxFileBytes)||o.reduce((w,S)=>w+S.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Pf||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(w=>w.reason==="git-enumeration-limit"),p=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...d,...p])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||p.length>1)throw new Error("Native Git selection omissions must not be duplicated");let f=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=f?.status==="overflow"||f?.status==="overflow-and-changed",h=f?.status==="changed"||f?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(p.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(w=>w.reason==="physical-enumeration-limit"),g=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...v,...g])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,k=b?.status==="overflow"||b?.status==="overflow-and-changed",N=b?.status==="changed"||b?.status==="overflow-and-changed";if(k!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}async function IN(e,t,r={}){let i=_i(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=F.resolve(e.projectRoot),a=yN(r),o=NN(r.gitSelectionLimits),s=await SN(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(CN(s).filter(S=>lo(e,S))),l=[...s.gitlinks].filter(S=>c.has(S)),u=[...s.nestedRepositories].filter(S=>lo(e,S)),d=(S,E)=>E.some(y=>S===y||S.startsWith(`${y}/`)),p=S=>d(S,l),f=S=>d(S,u),m=[...i.entries.map(S=>S.path),...i.omitted.flatMap(S=>S.type==="directory"?[S.path,`${S.path}/`]:[S.path])].filter(S=>!c.has(S)&&!p(S)&&!f(S)),h=await xj(a,n,m),v=i.entries.filter(S=>!p(S.path)&&!f(S.path)&&lo(e,S.path)&&(c.has(S.path)||!h.has(S.path)));await EN(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let S of l)g.push({path:S,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((S,E)=>S.path.localeCompare(E.path,"en"));let b=i.omitted.filter(S=>p(S.path)||f(S.path)||!lo(e,S.path)?!1:h.has(S.path)?c.has(S.path)||[...c].some(E=>E.startsWith(`${S.path}/`)):!0);for(let S of g)b.some(E=>E.path===S.path&&E.reason===S.reason)||b.push(S);b.sort((S,E)=>S.path.localeCompare(E.path,"en"));let k=i.omissionOverflow?.count??0,N=i.omissionOverflow?.hash??ee("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,N=al(N,"git-selection",{source:"git-selection",...s.overflow}));let x=S=>{k+=1,N=al(N,"omission",S)};for(;b.length>Pf;){let S=_N(b);if(S===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");x(S)}return _i({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:b.length+k===0,entries:v,omitted:b,omittedCount:b.length+k,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:k}}:{}})}function Wj(e,t){if(!rj.test(t))throw new Error(`Invalid Native change name: ${t}`);return F.join(Y(e,t),"baseline-manifest.json")}async function TN(e,t={}){let r={maxFiles:t.limits?.maxFiles??rl.maxFiles,maxFileBytes:t.limits?.maxFileBytes??rl.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??rl.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??rl.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=RN(t.policy),n=yN({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=NN(t.gitSelectionLimits,t.maxSelectionRecords),o=Sj(t.physicalSelectionLimits,t.maxSelectionRecords);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=F.resolve(e.projectRoot),c=await ne.realpath(s),l=F.resolve(e.nativeRoot),u=await ne.realpath(l),d=F.resolve(e.runtimeDir),p=F.resolve(e.configFile),f=F.join(s,".comet","current-change.json"),m=Oj(s,t.denylist??[]),h=[],v=[],g=new Map,b=new Map,k=0,N=0,x=ee("comet.native.snapshot-omission-overflow.v1"),w=0,S=!1,E=null,y=_=>{N+=1,x=al(x,"omission",_)},C=_=>{if(k+=1,v.length<Pf){v.push(_);return}if(PN(_)){let A=_N(v);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(A),v.push(_);return}y(_)},O=_=>{k+=_.count,N+=_.count,x=al(x,"git-selection",{source:"git-selection",..._})},T=async(_,A)=>{h.push(_),w+=_.size,g.set(_.path,A),S||(S=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Q=(_,A)=>{let $=h.findIndex(te=>te.path===_);if($<0)return;let[W]=h.splice($,1);w-=W.size,g.delete(_),C(A)},Te=async(_,A,$,W)=>{if(!$.isFile()||$.isSymbolicLink()||!H(n))return;let te;try{te=await ne.realpath(_)}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;C({path:A,size:$.size,type:"file",reason:ve(P)?"changed-during-read":"unreadable"});return}if(!H(n)||!q(c,te)||Pt(u,te))return;if(h.length>=r.maxFiles){C({path:A,size:$.size,type:"file",reason:"file-count"});return}if($.size>r.maxFileBytes){C({path:A,size:$.size,type:"file",reason:"file-size"});return}if(w+$.size>r.maxTotalBytes){C({path:A,size:$.size,type:"file",reason:"total-size"});return}let J,D,le;try{if(J=await Fj(te,$.size,$,n),J.status==="budget-exhausted"||!H(n))return;if(J.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!H(n)||(le=await ne.realpath(_),!H(n)))return;D=await ne.lstat(_)}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;C({path:A,size:$.size,type:"file",reason:ve(P)?"changed-during-read":"unreadable"});return}if(H(n)){if(J.bytes!==$.size||le!==te||!Jr($,J.finalStat)||!Jr(J.finalStat,D)||!D.isFile()||D.isSymbolicLink()||D.size!==$.size||D.mtimeMs!==$.mtimeMs||D.ctimeMs!==$.ctimeMs){C({path:A,size:D.isFile()?D.size:null,type:D.isFile()?"file":"other",reason:"changed-during-read"});return}H(n)&&await T({path:A,hash:J.hash,size:D.size,type:"file",...W===void 0?{}:{gitObjectId:W}},{kind:"file",target:_,realTarget:te,stat:D})}},Z=async(_,A,$)=>{if(!H(n))return;let W,te,J;try{if(W=await ne.readlink(_,{encoding:"buffer"}),!H(n)||(J=await ne.lstat(_),!H(n)))return;te=await ne.readlink(_,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;C({path:A,size:null,type:"other",reason:ve(P)?"changed-during-read":"unreadable"});return}if(!H(n))return;if(!J.isSymbolicLink()||!Jr($,J)||J.mtimeMs!==$.mtimeMs||J.ctimeMs!==$.ctimeMs||!W.equals(te)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let D=W.byteLength;if(h.length>=r.maxFiles){C({path:A,size:D,type:"other",reason:"file-count"});return}if(D>r.maxFileBytes){C({path:A,size:D,type:"other",reason:"file-size"});return}if(w+D>r.maxTotalBytes){C({path:A,size:D,type:"other",reason:"total-size"});return}let le=ol("sha256").update("symlink\0").update(W).digest("hex");H(n)&&await T({path:A,hash:le,size:D,type:"file"},{kind:"symlink",target:_,rawTarget:W,stat:J})},Ot=async()=>{for(let[_,A]of[...g]){if(!H(n))return;if(A.kind==="file"){let D,le;try{if(D=await ne.realpath(A.target),!H(n))return;le=await ne.lstat(A.target)}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;Q(_,{path:_,size:null,type:"file",reason:ge(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(D!==A.realTarget||!le.isFile()||le.isSymbolicLink()||!Jr(A.stat,le)||le.size!==A.stat.size||le.mtimeMs!==A.stat.mtimeMs||le.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:le.isFile()?le.size:null,type:le.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let D,le;try{if(D=await ne.lstat(A.target),!H(n))return;le=await ne.readlink(A.target,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;Q(_,{path:_,size:null,type:"other",reason:ge(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(!D.isSymbolicLink()||!Jr(A.stat,D)||D.mtimeMs!==A.stat.mtimeMs||D.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(le))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let $,W;try{if($=await ne.realpath(A.target),!H(n))return;W=await ne.lstat(A.target)}catch{if(!H(n))return;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;if(!($===A.realTarget&&W.isDirectory()&&!W.isSymbolicLink()&&Jr(A.stat,W)&&q(c,$)&&!Pt(u,$))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let J;try{if(!H(n))return;J=await pN(n,$)}catch(D){if(En(D))throw D;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;J.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):J.hash!==A.hash&&Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of b){if(!H(n))return;try{let $=await ne.lstat(A);if(!H(n))return;C({path:_,size:$.isFile()?$.size:null,type:$.isFile()?"file":$.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch($){if(!H(n))return;if(ve($))continue;if(!ge($))throw $;C({path:_,size:null,type:"file",reason:"unreadable"})}}},ce=await SN(n,e,a,t.gitSelectionHooks,i?.manifest.exclude);if(ce===null){let _=await uN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let W of _.records){if(W.type!=="file"&&W.type!=="symlink"||g.has(W.path))continue;if(Rt(n)<1)break;if(!hN(i,W.path,n))continue;if(Rt(n)<1)break;let te=F.resolve(s,...W.path.split("/")),J;try{J=await ne.lstat(te)}catch(D){if(!H(n))break;if(!ge(D)&&!ve(D))throw D;C({path:W.path,size:null,type:"file",reason:ve(D)?"changed-during-read":"unreadable"});continue}if(Rt(n)<1)break;if(W.type==="symlink"&&J.isSymbolicLink()){if(await Z(te,W.path,J),Rt(n)<1)break;continue}if(W.type!=="file"||!J.isFile()||J.isSymbolicLink()){C({path:W.path,size:J.isFile()?J.size:null,type:J.isDirectory()?"directory":J.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Te(te,W.path,J),Rt(n)<1)break}Rt(n)>=1&&await Ot();let A=await uN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o}),$=jj(_.evidence,A.evidence);E=$.evidence;for(let W of[..._.omissions,...A.omissions,...$.omissions])v.some(te=>te.path===W.path&&te.reason===W.reason)||C(W)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,$=!1;if(_){let P=_i(_);for(let ae of P.entries)ae.gitObjectId!==void 0&&A.set(ae.path,ae);$=A.size>0}let W=new Set,te=!0;try{let P=await uo(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(P.overflow)$=!1,te=!1,A.clear();else for(let ae of P.records){let ue=nl(ae),je=ue.indexOf(" "),Pe=je<0?null:xn(ue.slice(je+1));if(je!==1||Pe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ue[0]!=="H"&&W.add(Pe)}}catch(P){if(En(P))throw P;$=!1,te=!1,A.clear()}let J=new Set;try{let P=await il(n,s,["ls-files","--modified","-z"],Rf);for(let ae of P.toString("utf8").split("\0")){let ue=xn(ae);ue!==null&&J.add(ue)}}catch{$=!1,te=!1,A.clear()}let D=new Set,le=new Set;for(let P of CN(ce)){if(g.has(P)||!lo(e,P))continue;if(Rt(n)<1)break;if(!hN(i,P,n))continue;if(Rt(n)<1)break;let ae=F.resolve(s,...P.split("/"));if(ae===p||ae===f||Pt(d,ae)||m.some(Ye=>Pt(Ye,ae)))continue;if(ce.gitlinks.has(P)){if(h.length>=r.maxFiles){C({path:P,size:0,type:"file",reason:"file-count"});continue}let Ye,as;try{[Ye,as]=await Promise.all([ne.realpath(ae),ne.lstat(ae)])}catch{C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(as.isSymbolicLink()||!as.isDirectory()||!q(c,Ye)||Pt(u,Ye)){C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Gi=await pN(n,Ye);if(Gi.dirty){C({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await T({path:P,hash:Gi.hash,size:0,type:"file"},{kind:"gitlink",target:ae,realTarget:Ye,stat:as,hash:Gi.hash})}catch(Gi){if(En(Gi))throw Gi;C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ue;try{ue=await ne.lstat(ae)}catch(Ye){if(ve(Ye)&&ce.tracked.has(P)){b.set(P,ae);continue}if(!ge(Ye)&&!ve(Ye))throw Ye;C({path:P,size:null,type:"file",reason:ve(Ye)?"changed-during-read":"unreadable"});continue}if(ue.isSymbolicLink()){await Z(ae,P,ue);continue}if(!ue.isFile()){ce.nestedRepositories.has(P)||C({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let je=ce.trackedObjectIds.get(P),Pe=je?A.get(P):void 0;if($&&Pe?.gitObjectId!==void 0&&Pe.gitObjectId===je&&!W.has(P)&&!J.has(P)){if(h.length>=r.maxFiles){C({path:P,size:Pe.size,type:"file",reason:"file-count"});continue}if(Pe.size>r.maxFileBytes){C({path:P,size:Pe.size,type:"file",reason:"file-size"});continue}if(w+Pe.size>r.maxTotalBytes){C({path:P,size:Pe.size,type:"file",reason:"total-size"});continue}h.push({...Pe}),w+=Pe.size,D.add(P);continue}let _m=te&&!W.has(P)&&!J.has(P)?je:void 0;await Te(ae,P,ue,_m),_m!==void 0&&le.add(P)}if(await Ot(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await EN(n,e,a,ce,t.gitSelectionHooks?.outputChunkBytes,i?.manifest.exclude),D.size>0||$&&le.size>0){let P=await il(n,s,["ls-files","--modified","-z"],Rf),ae=new Set;for(let ue of P.toString("utf8").split("\0")){let je=xn(ue);je!==null&&ae.add(je)}for(let ue of D){if(!ae.has(ue))continue;let je=h.find(Pe=>Pe.path===ue);Q(ue,{path:ue,size:je?.size??null,type:"file",reason:"changed-during-read"})}for(let ue of le){if(!ae.has(ue))continue;let je=h.find(Pe=>Pe.path===ue);je&&delete je.gitObjectId}}for(let P of ce.omissions)C(P);ce.overflow&&O(ce.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let UE=ce===null?{provider:"physical-tree",...E?{physicalSelection:E}:{}}:{provider:"git",...ce.evidence?{gitSelection:ce.evidence}:{}};return{schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:UE,createdAt:(t.now??new Date).toISOString(),complete:k===0,limits:r,...i?{policy:i.manifest}:{},entries:h,omitted:v,omittedCount:k,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${x}`,hash:x,count:N}}:{}}}async function If(e,t,r={}){let n=(await xe(e.projectRoot))?.native.snapshot??Tp;return TN(e,{...r,policy:t.policy,incrementalBaseline:t,maxSelectionRecords:n.max_selection_records,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 cl(e,t){let r=Wj(e,t),i=Ne(e,r);await V(i,r);try{let n=await eN({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return _i(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var rl,Pf,rj,ij,nj,aj,oj,sj,cj,lj,uj,dj,pj,fj,hj,mj,vj,gj,sl,wN,wj,Cn,Rf,yj,Nj,bj,_f,kj,Ij,Rn=I(()=>{"use strict";Ji();oe();Qe();Ut();Lt();K();Ct();Da();rl={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},Pf=1e3,rj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ij=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),nj=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),aj=new Set(["schema","include","exclude","hash"]),oj=new Set(["provider","gitSelection","physicalSelection","projection"]),sj=new Set(["provider","selection"]),cj=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),lj=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),uj=new Set(["schema","status","before","after"]),dj=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),pj=new Set(["path","hash","size","type","gitObjectId"]),fj=new Set(["path","size","type","reason"]),hj=new Set(["ref","hash","count"]),mj=new Set(["change-created","legacy-migration","explicit"]),vj=new Set(["file","directory","other"]),gj=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"]),sl=/^[a-f0-9]{64}$/u,wN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,wj=new Set(["EACCES","EPERM"]),Cn=64*1024,Rf=64*1024,yj=6e4,Nj=1e3,bj=2,_f={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},kj={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};Ij=(1n<<256n)-1n});import{execFileSync as J$}from"node:child_process";function Y$(e,t){try{return Zn(()=>J$("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:U$,maxBuffer:K$,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Gf(e,t,i)}}function Je(e,t){return Y$(e,t).trim()}var U$,K$,Gf,pt=I(()=>{"use strict";Ji();U$=3e4,K$=8*1024*1024,Gf=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{promises as rO}from"node:fs";import iO from"node:path";function $l(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function jl(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function qb(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function lO(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function Mb(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Gb(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===dh&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!Vb(e.children,l)),Wb(i)?i:null}if(e.schema===Oi&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!Vb(e.children,a)),Wb(i)?i:null}return null}function Vb(e,t){return e.some(r=>r.covers.includes(t))}function Wb(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Zr(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function uO(e){let t=$l(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=$l(n,`Native children acceptance_index.${i}`);if(jl(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function dO(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let p=["source","text"].filter(f=>d[f]!==u[f]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${p.join(", ")} exactly from the current acceptance catalog`)}}}function Jb(e,t,r={}){let i=(0,zb.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=$l(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Oi&&a!==Qr)throw jl(n,Lb,"Native children contract"),new Error(`Native children schema must be ${Oi} or ${Qr}`);let o=a===Oi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(jl(n,o==="indexed-v2"?aO:Lb,"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((p,f)=>{let m=$l(p,`Native child ${f}`);if(jl(m,o==="indexed-v2"?cO:o==="summary-v2"?sO:oO,`Native ${s} child fields (child ${f})`),typeof m.name!="string"||!nO.test(m.name))throw new Error(`Native child ${f} name is invalid`);let h=o==="summary-v2";if(h){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:h?m.summary:null,depends_on:qb(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?qb(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:p})=>p);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let p of c){let f=p.depends_on.filter(m=>!u.has(m));if(f.length>0)throw new Error(`Native child ${p.name} depends on unknown child: ${f.join(", ")}`)}lO(c);let d=r.policy==="advisory";if(a===dh){if(o==="indexed-v2"){let p=uO(n.acceptance_index);d||dO(p,t,r);let f=Object.keys(p);return d||Mb(c,f,f),{schema:Qr,acceptance_index:p,children:c}}return{schema:Qr,children:c}}return t&&!d&&Mb(c,t),{schema:Oi,children:c}}async function Qt(e){let t=iO.join(e.changeDir,uh);try{await rO.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await re({root:e.changeDir,ref:uh}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Jb(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Gb(a,e.acceptanceIds,e.validation??{}):null}}var zb,uh,Oi,Qr,dh,nO,Lb,aO,oO,sO,cO,Ol=I(()=>{"use strict";zb=ir(Bt(),1);at();uh="children.yaml",Oi="comet.native.children.v1",Qr="comet.native.children.v2",dh=Qr,nO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Lb=new Set(["schema","children"]),aO=new Set(["schema","acceptance_index","children"]),oO=new Set(["name","depends_on","covers"]),sO=new Set(["name","summary","depends_on"]),cO=new Set(["name","depends_on","covers"])});var _o=I(()=>{"use strict"});var Hl=I(()=>{"use strict";Vc();_o()});function gr(e,t){if(!fO.test(e))throw new Error(`${t} must be a Git commit`)}function ph(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function Bl(e){gr(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:fh(e.contract,i.name),contractHash:j("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:Ao,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function fh(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function Fl(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:(i.status==="ready"||i.status==="active")&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:i.builderFailureCount??0}));return{contractHash:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var fO,Ao,Dl,Hi=I(()=>{"use strict";de();Hl();fO=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;Ao="comet.native.supervisor.v2",Dl=3});import Io from"node:path";import{promises as Kb}from"node:fs";function hh(e,t){return Io.join(Et(e,t),"supervisor")}function To(e,t){return Io.join(hh(e,t),"state.json")}function Yb(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!==Ao)throw new Error(`Native Supervisor state schema must be ${Ao}`);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(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(gr(t.integration.targetCommit,"Native Supervisor target commit"),gr(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");gr(n.candidateCommit,"Native Supervisor integration candidate commit"),gr(n.integrationCommit,"Native Supervisor integration check commit"),Ub(n.checkStates,"Native Supervisor integration")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.builderFailureCount!==void 0&&(!Number.isSafeInteger(n.builderFailureCount)||n.builderFailureCount<0))throw new Error(`Native Supervisor child ${n.name} Builder failure count 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&&gr(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(gr(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.checkExecution&&Ub(n.task.checkExecution.checkStates,`Native Supervisor child ${n.name}`),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 et(e,t,r={}){try{let i=await Kb.readFile(To(e,t),"utf8"),n=JSON.parse(i);if(Yb(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(xt(),hf)),c=await s(Io.join(o.changesDir,t,"comet-state.yaml")),l=await Qt({changeDir:Io.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:Zr(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)l.contract.children.some(({name:d})=>d===u.name)&&(u.acceptanceScope=fh(l.contract,u.name),u.contractHash=j("comet.native.supervisor-contract.v1",l.contract),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractHash=u.contractHash,u.task.verificationBoundary="child-scope-parent-reverifies-all",u.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(xt(),hf)),s=await o(Io.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ei(e,t){Yb(t),await Kb.mkdir(e.changesRuntimeDir,{recursive:!0}),await Oe(To(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Ub(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw new Error(`${t} check states are invalid`);let r=new Set;for(let i of e){if(!i||typeof i.id!="string"||!i.id||r.has(i.id)||typeof i.name!="string"||!["planned","running","passed","failed","interrupted"].includes(i.status)||typeof i.repeatable!="boolean"||!Number.isSafeInteger(i.executionCount)||i.executionCount<0||!Array.isArray(i.argvDisplay)||!i.argvDisplay.every(n=>typeof n=="string")||typeof i.cwdRef!="string"||!Number.isSafeInteger(i.durationMs)||i.durationMs<0||i.exitCode!==null&&!Number.isSafeInteger(i.exitCode)||i.signal!==null&&typeof i.signal!="string"||typeof i.timedOut!="boolean"||i.startedAt!==null&&typeof i.startedAt!="string"||i.completedAt!==null&&typeof i.completedAt!="string"||i.logRef!==null&&typeof i.logRef!="string")throw new Error(`${t} check state is invalid`);r.add(i.id)}}var ti=I(()=>{"use strict";oe();de();Ol();K();Hi()});var mh=I(()=>{"use strict"});function mt(e){return e.replace(hO,"$1 [REDACTED]").replace(mO,"[REDACTED PRIVATE KEY]").replace(vO,"$1[REDACTED]@").replace(gO,"[REDACTED TOKEN]").replace(wO,'$1"[REDACTED]"').replace(yO,"$1$2$1$3$4[REDACTED]$4").replace(NO,"$1$2[REDACTED]")}var hO,mO,vO,gO,wO,yO,NO,Di=I(()=>{"use strict";hO=/\b(Bearer|Basic)\s+[^\s"']+/giu,mO=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,vO=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,gO=/\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,wO=/("(?:[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,yO=/(["'])((?:[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,NO=/\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});import{accessSync as JG,constants as UG,createWriteStream as KG,existsSync as YG,promises as XG,statSync as SO}from"node:fs";import Bi from"node:path";function EO(e,t){let r=Bi.relative(e,t);return r===""||!Bi.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Bi.sep}`)}function Xb(e,t){if(t.length===0||t.includes("\\")||Bi.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Bi.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Bi.resolve(e),i=Bi.resolve(r,...t.split("/"));if(!EO(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=SO(i)}catch(a){throw new Error(`Native check cwd does not exist: ${t}`,{cause:a})}if(!n.isDirectory())throw new Error(`Native check cwd is not a directory: ${t}`);return i}var Ll=I(()=>{"use strict";ta();mh();Di()});var Qb=I(()=>{"use strict";pt();Ll();de()});var ql=I(()=>{"use strict";pt();oe()});import{createHash as dk}from"node:crypto";import nk from"path";function Ae(e,t){return e<t?-1:e>t?1:0}function bh(e){if(!Eh.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function ZO(e,t){return e===t?0:e===null?-1:t===null?1:Ae(e,t)}function ii(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 r=nk.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||nk.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function hk(e,t){return e==="."?e:ii(e,t)}function Bn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function eH(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:ii(e.path,`${t} path`),hash:e.hash,size:Bn(e.size,`${t} size`),type:"file"}}function tH(e,t){return{path:hk(e.path,`${t} path`),size:e.size===null?null:Bn(e.size,`${t} size`),type:e.type,reason:e.reason}}function rH(e,t){return Ae(e.path,t.path)||Ae(e.hash,t.hash)||e.size-t.size}function iH(e,t){return Ae(e.path,t.path)||Ae(e.reason,t.reason)||Ae(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Ho(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
176
180
|
`,"utf8")}function ri(e,t,r){let i=`${t}
|
|
177
|
-
${
|
|
178
|
-
`),e.omissionOverflow&&ri(a,"existing-overflow",e.omissionOverflow);let o=(p,f)=>{f||(i+=1),n+=1,ri(a,"omission",p)},s=p=>{i+=1,n+=1,ri(a,"entry",p)},c=()=>{for(let p=r.length-1;p>=0;p-=1){let f=r[p];if(!(f.reason==="git-enumeration-limit"||f.reason==="git-selection-changed"||f.reason==="physical-enumeration-limit"||f.reason==="physical-selection-changed"))return r.splice(p,1),f}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(
|
|
179
|
-
`);let r=0;bh(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){ri(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Ho(o,n.path)&&(a+=1,ri(t,"change-attribution",o));ri(t,"change-end",{attributionCount:a}),a===0&&ri(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&ri(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function lk(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=KO(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let S=new Set(r.externalDrift.paths),E=new Set(o.changePaths),y=r.externalDrift.paths.filter(C=>!E.has(C)||n.some(O=>Ho(O,C)));if(y.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${y.slice(0,8).join(", ")}`);if(S.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=j(To,e),c=j(To,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[S,E]of[["baseline",e],["current",t]])for(let y of E.omitted){if(l.length>=FO)break;l.push(wr({kind:"snapshot-omission",source:S,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${S} snapshot omitted ${y.path}: ${y.reason}`))}let d=e.omitted.length+t.omitted.length,p=[...Kb("baseline",e),...Kb("current",t),...o.totalChanges===0&&a===null?[wr({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")]:[]],f=()=>{if(r.gitChangedPaths===void 0)return;let S=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(E=>S.has(E)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(E=>!S.has(E))}},m=S=>{let E=o.candidates.slice(0,S.detailedChangeCount),y=E.filter(ce=>ce.attributedTo.length===0&&!u.has(ce.path)),C=o.totalChanges-E.length,O=o.totalUnattributed-y.length,T=d-S.detailedOmissionCount,Q=O+T,Te=[...y.map(ce=>wr({kind:"unattributed-change",source:"implementation-scope",path:ce.path,evidence:{after:ce.after,before:ce.before,changeKind:ce.kind}},`Changed path is not covered by a declared artifact: ${ce.path}`)),...l.slice(0,S.detailedOmissionCount),...p,...Q>0?[ck(S.overflowHash,{changes:C,unattributed:O,unresolved:Q})]:[]],Z=JO(Te),Ot=S.includeGitAdvisory?f():void 0;return{schema:vh,contractHash:i,baselineProjectionRef:gh(s),baselineProjectionHash:s,currentProjectionRef:gh(c),currentProjectionHash:c,complete:Z.length===0,declaredArtifacts:n,changes:E,unattributed:y,unresolvedScopes:Z,noCodeReason:a,...Ot?{gitAdvisory:Ot}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let S=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:b});if($o({...S,scopeHash:b})<=Fi)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>h||d>v?XO({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:v}):b,x=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:N}),w={...x,scopeHash:j(rk,x)};if($o(w)>Fi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return w}function Sh(e){let t=wh(e.baseline),r=wh(e.current),i=sk(e);return{authority:i,baseline:t,current:r,scope:lk(t,r,i)}}function Zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function er(e,t,r,i){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 Bi(e,t){if(typeof e!="string"||!Nh.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Xb(e,t,r){let i=gh(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function ql(e,t){let r=Zt(e,"Native snapshot projection");if(er(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==tk)throw new Error("Native snapshot projection schema is invalid");let i=Pi({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=wh(i);if(j(To,r)!==j(To,n))throw new Error("Native snapshot projection is not canonical");let a=j(To,n);if(t!==void 0&&Bi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Eh(e,t){let r=Zt(e,`Declared artifact ${t}`);if(er(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:ii(r.path,`Declared artifact ${t} path`),kind:r.kind}}function Qb(e,t){if(e===null)return null;let r=Zt(e,t);return er(r,["hash","size"],[],t),{hash:Bi(r.hash,`${t} hash`),size:Dn(r.size,`${t} size`)}}function Zb(e,t){let r=Zt(e,`Implementation change ${t}`);if(er(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(Eh),n=Oo(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Qb(r.before,`Implementation change ${t} before`),o=Qb(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.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:ii(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function ZO(e,t){let r=Zt(e,`Unresolved scope ${t}`);er(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?ik(r.path,`Unresolved scope ${t} path`):ii(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function jo(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>ii(n,`${t} ${a}`)),i=[...new Set(r)].sort(Ae);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function uk(e){let t=Zt(e,"Native implementation external drift");if(er(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=jo(t.paths,"Native external drift paths");return ok({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function Ml(e){let t=Zt(e,"Native implementation scope"),r=[...QO].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if(er(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==vh)throw new Error("Native implementation scope schema is invalid");let i=Bi(t.contractHash,"Implementation scope contractHash"),n=Bi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Xb(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Bi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Xb(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(Eh);if(JSON.stringify(c)!==JSON.stringify(Oo(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Zb),u=[...l].sort((y,C)=>Ae(y.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(C=>Ho(C,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let p=t.unattributed.map(Zb),f=t.externalDrift===void 0?void 0:uk(t.externalDrift),m=new Set(f?.paths??[]),h=l.filter(y=>y.attributedTo.length===0&&!m.has(y.path));if(JSON.stringify(p)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(ZO),g=v.filter(y=>y.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let b=g[0]===void 0?null:YO(g[0]);if(b&&(b.changes+b.unresolved===0||b.unattributed>b.changes||b.unattributed>b.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let k=t.noCodeReason,N=[...h.map(y=>wr({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(b?.changes??0)===0&&k===null?[wr({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")]:[]],x=v.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(yh))||new Set(v.map(y=>y.id)).size!==v.length||JSON.stringify(x)!==JSON.stringify(N.sort(yh))||t.complete!==(v.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 w;if(t.gitAdvisory!==void 0){let y=Zt(t.gitAdvisory,"Implementation scope Git advisory");if(er(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=jo(y.changedPaths,"Git changed paths"),O=jo(y.pathsPresentInSnapshotChanges,"Git present paths"),T=jo(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),Q=[...O,...T].sort(Ae);if(JSON.stringify(Q)!==JSON.stringify(C)||T.some(Te=>l.some(Z=>Z.path===Te)))throw new Error("Implementation scope Git advisory partition is invalid");w={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:T}}let S={schema:vh,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:p,unresolvedScopes:v,noCodeReason:k,...w?{gitAdvisory:w}:{},...f?{externalDrift:f}:{}},E=Bi(t.scopeHash,"Implementation scope scopeHash");if(j(rk,S)!==E)throw new Error("Implementation scope content hash mismatch");return{...S,scopeHash:E}}function eH(e){let t=Zt(e,"Native implementation scope authority");if(er(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 r=t.declaredArtifacts.map(Eh);if(JSON.stringify(r)!==JSON.stringify(Oo(r)))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 i;t.gitChangedPaths!==void 0&&(i=jo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:uk(t.externalDrift),a=sk({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...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 Do(e){let t=Zt(e,"Native implementation scope bundle");er(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=eH(t.authority),i=ql(t.baseline),n=ql(t.current),a=Ml(t.scope),o=lk(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function dk(e){let t=Ml(e.scope);return Do({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 vh,tk,To,rk,OO,HO,DO,Nh,Fi,BO,FO,QO,Li=I(()=>{"use strict";de();Cn();vh="comet.native.implementation-scope.v2",tk="comet.native.content-snapshot-projection.v1",To="comet.native.content-snapshot-projection.v1",rk="comet.native.implementation-scope.v2",OO="comet.native.unresolved-scope-id.v1",HO="comet.native.scope-detail-overflow.v1",DO="comet.native.snapshot-projection-overflow.v2",Nh=/^[a-f0-9]{64}$/u,Fi=1024*1024,BO=128,FO=128;QO=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import pk from"node:path";function yr(e,t){if(!hk.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function mk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function vk(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 xh(e,t,r=2e3){let i=mt(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function Bo(e,t){let r=pk.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||pk.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function nH(e,t,r){let i=Bo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Ft(i),a=i.toLowerCase(),o=r?Bo(r,"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"}): ${i}`);return i}function Ch(e){let t=Bo(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 Bn(e,t){return e<t?-1:e>t?1:0}function Vl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Wl(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function gk(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function fk(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function aH(e){let t=Vl(e,"Native acceptance trace");if(Wl(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"||!hk.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 r=Bo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=Vl(o,`Native acceptance trace entry ${s}`);if(Wl(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=>Ch(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Bn))||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:Bo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:xh(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Bn(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=yr(t.traceHash,"Native acceptance trace hash");if(j(tH,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function wk(e){let t=Vl(e,"Native partial allowance");if(Wl(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(Bn))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:vk(t.change),scopeHash:yr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:xh(t.reason,"Partial allowance reason"),confirmedSummary:xh(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:mk(t.sourceRevision),confirmedAt:gk(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=yr(t.allowanceHash,"Native partial allowance hash");if(j(rH,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Rh(e){let t=Vl(e,"Native verification evidence");if(Wl(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 r=yr(t.implementationScopeHash,"Native verification implementation scope hash"),i=aH(t.acceptanceTrace),n=yr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.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:yr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(p=>Ch(p));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Bn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(p=>p.evidenceRefs))].sort(Bn);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(p=>Ch(p));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Bn)))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:vk(t.change),sourceRevision:mk(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:yr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:fk(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:nH(t.reportRef,"Native verification report ref"),reportHash:yr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:fk(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:gk(t.createdAt,"Native verification timestamp")},d=yr(t.envelopeHash,"Native verification envelope hash");if(j(iH,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var hk,tH,rH,iH,zl=I(()=>{"use strict";de();Hi();Ha();Li();hk=/^[a-f0-9]{64}$/u,tH="comet.native.acceptance-trace.v2",rH="comet.native.partial-allowance.v1",iH="comet.native.verification-evidence.v2"});import yk from"node:path";function ni(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ai(e,t,r,i=[]){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 Nr(e,t){if(typeof e!="string"||!sH.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function tt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function xk(e,t){let r=tt(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function Sk(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function hH(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>dH||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 r=yk.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||yk.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function mH(e){let t=ni(e,"Native check receipt checker");ai(t,["policy","version","hash","limits"],"Native check receipt checker");let r=ni(t.limits,"Native check receipt limits");if(ai(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Fn||t.version!==Ph||t.hash!==bk||r.maxFiles!==Ue.maxFiles||r.maxFileBytes!==Ue.maxFileBytes||r.maxTotalBytes!==Ue.maxTotalBytes||r.maxIssues!==Ue.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Fn,version:Ph,hash:bk,limits:{...Ue}}}function vH(e){let t=ni(e,"Native check receipt contract");return ai(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Nr(t.expectedHash,"Native check expected contract hash"),beforeHash:Nr(t.beforeHash,"Native check before contract hash"),afterHash:Nr(t.afterHash,"Native check after contract hash")}}function gH(e){let t=ni(e,"Native check receipt implementation");return ai(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Nr(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Nr(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Nr(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Nr(t.afterSnapshotHash,"Native check after snapshot hash")}}function wH(e,t){let r=ni(e,`Native check batch ${t}`);ai(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:tt(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:tt(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:tt(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:tt(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:tt(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:tt(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>Ue.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>Ue.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function yH(e){let t=ni(e,"Native check receipt counts");ai(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:tt(t.filesSelected,"Native check filesSelected"),filesScanned:tt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:tt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:tt(t.bytesScanned,"Native check bytesScanned"),issueCount:tt(t.issueCount,"Native check issueCount"),recordedIssueCount:tt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(wH):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.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({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>Ue.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>Ue.maxFiles||r.bytesScanned>Ue.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function NH(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||kk.indexOf(e.kind)-kk.indexOf(t.kind)}function bH(e){if(!Array.isArray(e)||e.length>Ue.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=ni(i,`Native check issue ${n}`);if(ai(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!pH.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:hH(a.path,`Native check issue ${n} path`),line:xk(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(NH);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function kH(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!fH.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=Ek.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function SH(e){return j(uH,e)}function Ck(e){let t=ni(e,"Native check receipt");if(ai(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Nk)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!cH.test(t.change))throw new Error("Native check receipt change name is invalid");let r=xk(t.sourceRevision,"Native check source revision"),i=mH(t.checker),n=vH(t.contract),a=gH(t.implementation),o=SH({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Nr(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=Sk(t.startedAt,"Native check receipt startedAt"),c=Sk(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=yH(t.counts),u=bH(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=kH(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let p=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==p)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Ue.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>Ue.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let f={schema:Nk,change:t.change,sourceRevision:r,checker:i,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},m=Nr(t.receiptHash,"Native check receipt content hash");if(j(oH,f)!==m)throw new Error("Native check receipt content hash mismatch");return{...f,receiptHash:m}}var Nk,oH,Fn,Ph,Ue,sH,cH,lH,uH,dH,bk,pH,kk,Ek,fH,_h=I(()=>{"use strict";de();Nk="comet.native.check-receipt.v1",oH="comet.native.check-receipt.v1",Fn="scoped-text-safety",Ph=1,Ue=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),sH=/^[a-f0-9]{64}$/u,cH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lH="comet.native.checker-policy.v1",uH="comet.native.check-input.v1",dH=2048,bk=j(lH,{policy:Fn,version:Ph,limits:Ue,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),pH=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),kk=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Ek=["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"],fH=new Set(Ek)});function Ln(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function oi(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function br(e,t){if(typeof e!="string"||!CH.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function jt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=mt(e).trim();if(!r||r.length>AH||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Ah(e,t){let r=jt(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function Fo(e,t,r=jt,i=!1,n=IH){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function jH(e,t){if(typeof e!="string"||!RH.test(e))throw new Error(`${t} is invalid`);return e}function $H(e){let t=Ln(e,"Native verification receipt bindings");if(oi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!PH.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:br(t.contractHash,"Native verification receipt contract hash"),scopeHash:br(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:br(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:br(t.artifactHash,"Native verification receipt artifact hash")}}function OH(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=_H.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function HH(e,t,r,i){let n=Ln(t,`Native ${e} evidence`);if(e==="automated-check"){if(oi(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=Ah(n.startedAt,"Native automated-check start time"),o=Ah(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(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Ln(n.worktree,"Native automated-check worktree");if(oi(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=Ln(n.afterFence,"Native automated-check after fence");if(oi(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:jt(n.executable,"Native automated-check executable"),args:Fo(n.args,"Native automated-check arguments",jt,!0),cwd:jt(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:jt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:br(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:br(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:br(n.outputHash,"Native automated-check output hash"),outputSummary:jt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){oi(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=OH(n.checkReceiptRef);if(br(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Fo(n.subjects,"Native static inspection subjects",jt,i==="required-check"),rule:jt(n.rule,"Native static inspection rule"),resultSummary:jt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return oi(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Fo(n.steps,"Native manual evidence steps"),observations:Fo(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function DH(e){let t=Ln(e,"Native verification receipt");if(oi(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 r=t.kind,i=t.role,n=t.status,a=jt(t.actor,"Native verification receipt actor"),o=Fo(t.acceptanceIds,"Native receipt acceptance IDs",jH,i==="required-check",TH).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Ih,kind:r,role:i,status:n,bindings:$H(t.bindings),acceptanceIds:o,actor:a,issuedAt:Ah(t.issuedAt,"Native verification receipt issue time"),evidence:HH(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Fn||s.actor!==`native-runtime:${Fn}`))throw new Error("Native required check policy identity is invalid");return s}function Rk(e){let t=Ln(e,"Native verification receipt");if(oi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Ih)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=DH(i),a=br(t.receiptHash,"Native verification receipt hash");if(j(EH,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Th(e){return j(xH,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var Ih,EH,xH,CH,RH,PH,_H,AH,IH,TH,Lo=I(()=>{"use strict";de();_h();Hi();Ih="comet.native.verification-receipt.v3",EH=Ih,xH="comet.native.declared-artifacts.v1",CH=/^[a-f0-9]{64}$/u,RH=/^acceptance-[a-f0-9]{64}$/u,PH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_H=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,AH=4096,IH=256,TH=1024});import{createHash as BH}from"node:crypto";import{promises as $t}from"node:fs";import tr from"node:path";function jh(e,t){let r=tr.relative(e,t);return r===""||!tr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${tr.sep}`)}function FH(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Pk(e){let t=await $t.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await $t.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function LH(e,t){let r=tr.resolve(e),i=tr.resolve(t);if(!jh(r,i))throw new Error("Native evidence path is outside its change");let n=[await Pk(r)],a=r;for(let o of tr.relative(r,i).split(tr.sep).filter(Boolean)){a=tr.join(a,o);let s=await Pk(a);if(!jh(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function _k(e){for(let t of e){let r=await $t.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!FH(t,r)||await $t.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function qH(e,t,r={}){let i=await LH(t,tr.dirname(e));await r.afterParentChainCaptured?.();let n=await $t.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await $t.realpath(e);if(!jh(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await $t.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),$t.lstat(e),$t.realpath(e)]);if(await _k(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Gl(s,n)||!Gl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>qn)throw new Error(`Native evidence document exceeds ${qn} bytes`);await r.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(64*1024);for(;;){let v=qn+1-d,g=await o.read(p,0,Math.min(p.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>qn)throw new Error(`Native evidence document exceeds ${qn} bytes`);u.push(Buffer.from(p.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[f,m,h]=await Promise.all([o.stat(),$t.lstat(e),$t.realpath(e)]);if(await _k(i),!m.isFile()||m.isSymbolicLink()||h!==a||!Gl(s,f)||!Gl(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function Tk(e,t){if(!Ik.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function MH(e,t,r,i,n){if(!Ik.test(r))throw new Error("Native report evidence hash is invalid");let a=await qi({paths:e,name:t,kind:"reports",hash:r,hooks:i,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!==r||typeof o.content!="string"||BH("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function Mn(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function VH(e,t,r,i,n){let a=Tk(r,i);return n?tr.join(n,...a.split("/")):Mr(Y(e,t),a)}async function qi(e){let t=VH(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??Ne(e.paths,t);return await V(r,t),qH(t,r,e.hooks)}function Ak(e,t){return ql(e,t)}function WH(e,t){let r=Ml(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function zH(e,t,r){let i=wk(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function GH(e,t,r){let i=Rh(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function JH(e,t,r,i=!1,n){let a=await Jl(e,t,r.implementationScopeRef,void 0,n);if(i&&await MH(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await jk(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function qo(e,t,r,i,n){let a=Mn(r,"scopes"),o=WH(await qi({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=Mn(o.baselineProjectionRef,"snapshots"),c=Mn(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([qi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>Ak(d,s)),qi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>Ak(d,c))]);return dk({baseline:l,current:u,scope:o})}async function Jl(e,t,r,i,n){return(await qo(e,t,r,i,n)).scope}async function jk(e,t,r,i,n){let a=Mn(r,"allowances");return zH(await qi({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function Mo(e,t,r,i,n){let a=Mn(r,"receipts"),o=Rk(await qi({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Vn(e,t,r,i,n){let a=Mn(r,"verifications"),o=GH(await qi({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await JH(e,t,o,!1,n),o}var Ik,qn,uK,si=I(()=>{"use strict";oe();K();Lt();Li();zl();Lo();Ik=/^[a-f0-9]{64}$/u,qn=Fi,uK=3*qn});import Wi from"node:path";import{realpathSync as IF}from"node:fs";Gi();Ji();import{execFileSync as ix}from"child_process";import nx from"fs";import di from"path";import{AsyncLocalStorage as Pm}from"node:async_hooks";ea();var pi=new Pm,_m=new Pm;function Am(e){return pi.getStore()?e():pi.run(new Map,e)}function ax(e){let t=pi.getStore();for(let r of e)t?.set(xr(r.root),e);return e}function ra(e,t){return Qn(()=>ix("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function ia(e,t){return xr(e)===xr(t)}function xr(e){let t=di.resolve(e);try{let r=nx.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function we(e){try{let t=_m.getStore()?.get(xr(e)),r=pi.getStore()?.get(t??xr(e));if(r){let c=na(t??e,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=di.resolve(ra(e,["rev-parse","--show-toplevel"])),n=pi.getStore()?.get(xr(i))??Im(e),a=na(i,n);if(pi.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=ra(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!ia(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function cs(e){try{let t=pi.getStore()?.get(_m.getStore()?.get(xr(e))??xr(e));return t?t.map(r=>({...r})):(ra(e,["rev-parse","--is-inside-work-tree"]),Im(e))}catch{return[]}}function Im(e){let t=ox(ra(e,["worktree","list","--porcelain","-z"]));return ax(t),t.map(r=>({...r}))}function ox(e){let t=e.split("\0"),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:di.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}function Cr(e){return cs(e).map(t=>t.root)}function na(e,t){let r=t.find(a=>ia(di.resolve(a.root),di.resolve(e)));if(!r)return null;let i=di.resolve(t[0].root),n=di.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!ia(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function nr(e,t){try{let r=ra(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}de();var Hf=ir(Bt(),1);import{promises as zN}from"fs";import Kr from"path";at();oe();yi();Qe();Re();K();Ct();Cn();import{createHash as i$}from"crypto";import n$ from"path";var dt=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"});Re();K();import{constants as ul,promises as _t}from"node:fs";import At from"node:path";import{TextDecoder as Qj}from"node:util";import Uj from"path";ln();Fr();var Bj=ir(Bt(),1);ln();Fr();cr();cr();cn();Sp();ln();cr();var oW=4*1024*1024;import{AsyncLocalStorage as Fj}from"node:async_hooks";var Lj=new Fj;function qj(){let e=Lj.getStore();return e?.active?e:null}function Mj(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function SN(e,t){return(...r)=>{let i=qj();if(i===null)return t(...r);let n=Mj(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.get(n)?.value===o&&i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}cn();var pW=SN("hookWritePolicy",async e=>(await yp(e))?.hook??{allow_paths:[]});Ma();import{randomUUID as Vj}from"node:crypto";import{promises as sl}from"node:fs";import xN from"node:path";var cl="comet.selection.v2",CN=16*1024;function ll(e){return xN.join(e,".comet","current-change.json")}function Wj(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function EN(e){return e===null||typeof e=="string"}function RN(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!Wj(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&&!EN(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:cl,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==cl)throw new Error(`current change selection schema must be ${cl}`);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(!EN(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 Pf(e){let t;try{let i=ll(e),{bytes:n}=await ki(i,CN,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...RN(t)}}async function _f(e,t){let r=RN(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=ll(e),n=`${i}.${Vj()}.tmp`;await sl.mkdir(xN.dirname(i),{recursive:!0});try{await sl.writeFile(n,`${JSON.stringify(r.selection,null,2)}
|
|
180
|
-
`,"utf8"),await
|
|
181
|
-
`)])}catch(d){if(!
|
|
182
|
-
${t}`).digest("hex")}async function
|
|
181
|
+
${oa(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function nH(e){if(Ho(e)<=Li)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=dk("sha256");a.update(`${YO}
|
|
182
|
+
`),e.omissionOverflow&&ri(a,"existing-overflow",e.omissionOverflow);let o=(p,f)=>{f||(i+=1),n+=1,ri(a,"omission",p)},s=p=>{i+=1,n+=1,ri(a,"entry",p)},c=()=>{for(let p=r.length-1;p>=0;p-=1){let f=r[p];if(!(f.reason==="git-enumeration-limit"||f.reason==="git-selection-changed"||f.reason==="physical-enumeration-limit"||f.reason==="physical-selection-changed"))return r.splice(p,1),f}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Ho(u)>Li;){if(r.filter(f=>f.reason!=="git-enumeration-limit"&&f.reason!=="git-selection-changed"&&f.reason!=="physical-enumeration-limit"&&f.reason!=="physical-selection-changed").length>0){let f=Math.max(1,Math.ceil(r.length/4));for(let m=0;m<f;m+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let f=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-f))s(m)}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 kh(e){let t=_i(e),r=t.entries.map((n,a)=>eH(n,`Snapshot entry ${a}`));if(r.sort(rH),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>tH(n,`Snapshot omission ${a}`));return i.sort(iH),nH({schema:pk,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:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Do(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:ii(i.path,`Declared artifact ${r} path`),kind:i.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((r,i)=>Ae(r.path,i.path)||Ae(r.kind,i.kind))}function Bo(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function ak(e){return e?{hash:e.hash,size:e.size}:null}function xh(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Ae(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=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&&r({path:u,kind:c?l?"modified":"removed":"added",before:ak(c),after:ak(l)})}}function mk(e,t){return{...e,attributedTo:t.filter(r=>Bo(r,e.path))}}function Ch(e){let t=Do(e.declaredArtifacts),r=[];return xh(e.baseline,e.current,i=>{r.push(mk(i,t))}),r}function wr(e,t){return{id:`scope:${j(UO,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function aH(e,t){let r=t.omitted.map(i=>wr({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(wr({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(wr({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`)),r}function ok(e,t){return aH(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function Sh(e,t){return Ae(e.kind,t.kind)||Ae(e.source,t.source)||ZO(e.path,t.path)||Ae(e.id,t.id)}function oH(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(Sh)}function vk(e){return[...new Set(e.map((t,r)=>ii(t,`Git path ${r}`)))].sort(Ae)}function sk(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 sH(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 gk(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=vk(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:sk(e.baseCommit,"Native external drift base commit"),targetBranch:sH(e.targetBranch,"Native external drift target branch"),targetCommit:sk(e.targetCommit,"Native external drift target commit"),paths:t}}function wk(e){if(typeof e.contractHash!="string"||!Eh.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Do(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:vk(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:gk(e.externalDrift)}}}function cH(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,d=0,p=0;return xh(e,t,f=>{let m=r.some(h=>Bo(h,f.path));if(d+=1,c.push(f.path),!m&&!n?.has(f.path)&&(p+=1),o?.has(f.path)&&s.push(f.path),!u&&a.length<XO){let h=mk(f,r),v=Ho(h);l+v<=Li?(a.push(h),l+=v):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:p}}function yk(e,t){return wr({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 lH(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 r={changes:Bn(Number(t[1]),"Scope overflow change count"),unresolved:Bn(Number(t[2]),"Scope overflow unresolved count"),unattributed:Bn(Number(t[3]),"Scope overflow unattributed count")},i=Fi(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(yk(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function uH(e){let t=dk("sha256");t.update(`${KO}
|
|
183
|
+
`);let r=0;xh(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){ri(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Bo(o,n.path)&&(a+=1,ri(t,"change-attribution",o));ri(t,"change-end",{attributionCount:a}),a===0&&ri(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&ri(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function Nk(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=cH(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let S=new Set(r.externalDrift.paths),E=new Set(o.changePaths),y=r.externalDrift.paths.filter(C=>!E.has(C)||n.some(O=>Bo(O,C)));if(y.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${y.slice(0,8).join(", ")}`);if(S.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=j($o,e),c=j($o,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[S,E]of[["baseline",e],["current",t]])for(let y of E.omitted){if(l.length>=QO)break;l.push(wr({kind:"snapshot-omission",source:S,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${S} snapshot omitted ${y.path}: ${y.reason}`))}let d=e.omitted.length+t.omitted.length,p=[...ok("baseline",e),...ok("current",t),...o.totalChanges===0&&a===null?[wr({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")]:[]],f=()=>{if(r.gitChangedPaths===void 0)return;let S=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(E=>S.has(E)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(E=>!S.has(E))}},m=S=>{let E=o.candidates.slice(0,S.detailedChangeCount),y=E.filter(ce=>ce.attributedTo.length===0&&!u.has(ce.path)),C=o.totalChanges-E.length,O=o.totalUnattributed-y.length,T=d-S.detailedOmissionCount,Q=O+T,Te=[...y.map(ce=>wr({kind:"unattributed-change",source:"implementation-scope",path:ce.path,evidence:{after:ce.after,before:ce.before,changeKind:ce.kind}},`Changed path is not covered by a declared artifact: ${ce.path}`)),...l.slice(0,S.detailedOmissionCount),...p,...Q>0?[yk(S.overflowHash,{changes:C,unattributed:O,unresolved:Q})]:[]],Z=oH(Te),Ot=S.includeGitAdvisory?f():void 0;return{schema:Nh,contractHash:i,baselineProjectionRef:bh(s),baselineProjectionHash:s,currentProjectionRef:bh(c),currentProjectionHash:c,complete:Z.length===0,declaredArtifacts:n,changes:E,unattributed:y,unresolvedScopes:Z,noCodeReason:a,...Ot?{gitAdvisory:Ot}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let S=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:b});if(Ho({...S,scopeHash:b})<=Li)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>h||d>v?uH({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:v}):b,x=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:N}),w={...x,scopeHash:j(fk,x)};if(Ho(w)>Li)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return w}function Rh(e){let t=kh(e.baseline),r=kh(e.current),i=wk(e);return{authority:i,baseline:t,current:r,scope:Nk(t,r,i)}}function Zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function er(e,t,r,i){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 Fi(e,t){if(typeof e!="string"||!Eh.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ck(e,t,r){let i=bh(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function Wl(e,t){let r=Zt(e,"Native snapshot projection");if(er(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==pk)throw new Error("Native snapshot projection schema is invalid");let i=_i({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=kh(i);if(j($o,r)!==j($o,n))throw new Error("Native snapshot projection is not canonical");let a=j($o,n);if(t!==void 0&&Fi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Ph(e,t){let r=Zt(e,`Declared artifact ${t}`);if(er(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:ii(r.path,`Declared artifact ${t} path`),kind:r.kind}}function lk(e,t){if(e===null)return null;let r=Zt(e,t);return er(r,["hash","size"],[],t),{hash:Fi(r.hash,`${t} hash`),size:Bn(r.size,`${t} size`)}}function uk(e,t){let r=Zt(e,`Implementation change ${t}`);if(er(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(Ph),n=Do(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=lk(r.before,`Implementation change ${t} before`),o=lk(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.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:ii(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function pH(e,t){let r=Zt(e,`Unresolved scope ${t}`);er(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?hk(r.path,`Unresolved scope ${t} path`):ii(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function Oo(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>ii(n,`${t} ${a}`)),i=[...new Set(r)].sort(Ae);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function bk(e){let t=Zt(e,"Native implementation external drift");if(er(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=Oo(t.paths,"Native external drift paths");return gk({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function zl(e){let t=Zt(e,"Native implementation scope"),r=[...dH].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if(er(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Nh)throw new Error("Native implementation scope schema is invalid");let i=Fi(t.contractHash,"Implementation scope contractHash"),n=Fi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=ck(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Fi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=ck(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(Ph);if(JSON.stringify(c)!==JSON.stringify(Do(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(uk),u=[...l].sort((y,C)=>Ae(y.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(C=>Bo(C,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let p=t.unattributed.map(uk),f=t.externalDrift===void 0?void 0:bk(t.externalDrift),m=new Set(f?.paths??[]),h=l.filter(y=>y.attributedTo.length===0&&!m.has(y.path));if(JSON.stringify(p)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(pH),g=v.filter(y=>y.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let b=g[0]===void 0?null:lH(g[0]);if(b&&(b.changes+b.unresolved===0||b.unattributed>b.changes||b.unattributed>b.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let k=t.noCodeReason,N=[...h.map(y=>wr({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(b?.changes??0)===0&&k===null?[wr({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")]:[]],x=v.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(Sh))||new Set(v.map(y=>y.id)).size!==v.length||JSON.stringify(x)!==JSON.stringify(N.sort(Sh))||t.complete!==(v.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 w;if(t.gitAdvisory!==void 0){let y=Zt(t.gitAdvisory,"Implementation scope Git advisory");if(er(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Oo(y.changedPaths,"Git changed paths"),O=Oo(y.pathsPresentInSnapshotChanges,"Git present paths"),T=Oo(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),Q=[...O,...T].sort(Ae);if(JSON.stringify(Q)!==JSON.stringify(C)||T.some(Te=>l.some(Z=>Z.path===Te)))throw new Error("Implementation scope Git advisory partition is invalid");w={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:T}}let S={schema:Nh,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:p,unresolvedScopes:v,noCodeReason:k,...w?{gitAdvisory:w}:{},...f?{externalDrift:f}:{}},E=Fi(t.scopeHash,"Implementation scope scopeHash");if(j(fk,S)!==E)throw new Error("Implementation scope content hash mismatch");return{...S,scopeHash:E}}function fH(e){let t=Zt(e,"Native implementation scope authority");if(er(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 r=t.declaredArtifacts.map(Ph);if(JSON.stringify(r)!==JSON.stringify(Do(r)))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 i;t.gitChangedPaths!==void 0&&(i=Oo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:bk(t.externalDrift),a=wk({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...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 Fo(e){let t=Zt(e,"Native implementation scope bundle");er(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=fH(t.authority),i=Wl(t.baseline),n=Wl(t.current),a=zl(t.scope),o=Nk(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function kk(e){let t=zl(e.scope);return Fo({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 Nh,pk,$o,fk,UO,KO,YO,Eh,Li,XO,QO,dH,qi=I(()=>{"use strict";de();Rn();Nh="comet.native.implementation-scope.v2",pk="comet.native.content-snapshot-projection.v1",$o="comet.native.content-snapshot-projection.v1",fk="comet.native.implementation-scope.v2",UO="comet.native.unresolved-scope-id.v1",KO="comet.native.scope-detail-overflow.v1",YO="comet.native.snapshot-projection-overflow.v2",Eh=/^[a-f0-9]{64}$/u,Li=1024*1024,XO=128,QO=128;dH=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import Sk from"node:path";function yr(e,t){if(!xk.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ck(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Rk(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 _h(e,t,r=2e3){let i=mt(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function Lo(e,t){let r=Sk.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||Sk.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function gH(e,t,r){let i=Lo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Ft(i),a=i.toLowerCase(),o=r?Lo(r,"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"}): ${i}`);return i}function Ah(e){let t=Lo(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 Fn(e,t){return e<t?-1:e>t?1:0}function Gl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Jl(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function Pk(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Ek(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function wH(e){let t=Gl(e,"Native acceptance trace");if(Jl(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"||!xk.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 r=Lo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=Gl(o,`Native acceptance trace entry ${s}`);if(Jl(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=>Ah(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Fn))||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:Lo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:_h(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Fn(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=yr(t.traceHash,"Native acceptance trace hash");if(j(hH,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function _k(e){let t=Gl(e,"Native partial allowance");if(Jl(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(Fn))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:Rk(t.change),scopeHash:yr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:_h(t.reason,"Partial allowance reason"),confirmedSummary:_h(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Ck(t.sourceRevision),confirmedAt:Pk(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=yr(t.allowanceHash,"Native partial allowance hash");if(j(mH,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Ih(e){let t=Gl(e,"Native verification evidence");if(Jl(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 r=yr(t.implementationScopeHash,"Native verification implementation scope hash"),i=wH(t.acceptanceTrace),n=yr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.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:yr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(p=>Ah(p));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Fn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(p=>p.evidenceRefs))].sort(Fn);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(p=>Ah(p));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Fn)))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:Rk(t.change),sourceRevision:Ck(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:yr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Ek(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:gH(t.reportRef,"Native verification report ref"),reportHash:yr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:Ek(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Pk(t.createdAt,"Native verification timestamp")},d=yr(t.envelopeHash,"Native verification envelope hash");if(j(vH,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var xk,hH,mH,vH,Ul=I(()=>{"use strict";de();Di();Da();qi();xk=/^[a-f0-9]{64}$/u,hH="comet.native.acceptance-trace.v2",mH="comet.native.partial-allowance.v1",vH="comet.native.verification-evidence.v2"});import Ak from"node:path";function ni(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ai(e,t,r,i=[]){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 Nr(e,t){if(typeof e!="string"||!NH.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function tt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Hk(e,t){let r=tt(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function $k(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function RH(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>EH||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 r=Ak.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||Ak.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function PH(e){let t=ni(e,"Native check receipt checker");ai(t,["policy","version","hash","limits"],"Native check receipt checker");let r=ni(t.limits,"Native check receipt limits");if(ai(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Ln||t.version!==Th||t.hash!==Tk||r.maxFiles!==Ue.maxFiles||r.maxFileBytes!==Ue.maxFileBytes||r.maxTotalBytes!==Ue.maxTotalBytes||r.maxIssues!==Ue.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Ln,version:Th,hash:Tk,limits:{...Ue}}}function _H(e){let t=ni(e,"Native check receipt contract");return ai(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Nr(t.expectedHash,"Native check expected contract hash"),beforeHash:Nr(t.beforeHash,"Native check before contract hash"),afterHash:Nr(t.afterHash,"Native check after contract hash")}}function AH(e){let t=ni(e,"Native check receipt implementation");return ai(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Nr(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Nr(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Nr(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Nr(t.afterSnapshotHash,"Native check after snapshot hash")}}function IH(e,t){let r=ni(e,`Native check batch ${t}`);ai(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:tt(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:tt(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:tt(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:tt(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:tt(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:tt(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>Ue.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>Ue.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function TH(e){let t=ni(e,"Native check receipt counts");ai(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:tt(t.filesSelected,"Native check filesSelected"),filesScanned:tt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:tt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:tt(t.bytesScanned,"Native check bytesScanned"),issueCount:tt(t.issueCount,"Native check issueCount"),recordedIssueCount:tt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(IH):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.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({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>Ue.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>Ue.maxFiles||r.bytesScanned>Ue.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function jH(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||jk.indexOf(e.kind)-jk.indexOf(t.kind)}function $H(e){if(!Array.isArray(e)||e.length>Ue.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=ni(i,`Native check issue ${n}`);if(ai(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!xH.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:RH(a.path,`Native check issue ${n} path`),line:Hk(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(jH);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function OH(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!CH.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=Ok.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function HH(e){return j(SH,e)}function Dk(e){let t=ni(e,"Native check receipt");if(ai(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Ik)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!bH.test(t.change))throw new Error("Native check receipt change name is invalid");let r=Hk(t.sourceRevision,"Native check source revision"),i=PH(t.checker),n=_H(t.contract),a=AH(t.implementation),o=HH({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Nr(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=$k(t.startedAt,"Native check receipt startedAt"),c=$k(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=TH(t.counts),u=$H(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=OH(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let p=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==p)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Ue.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>Ue.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let f={schema:Ik,change:t.change,sourceRevision:r,checker:i,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},m=Nr(t.receiptHash,"Native check receipt content hash");if(j(yH,f)!==m)throw new Error("Native check receipt content hash mismatch");return{...f,receiptHash:m}}var Ik,yH,Ln,Th,Ue,NH,bH,kH,SH,EH,Tk,xH,jk,Ok,CH,jh=I(()=>{"use strict";de();Ik="comet.native.check-receipt.v1",yH="comet.native.check-receipt.v1",Ln="scoped-text-safety",Th=1,Ue=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),NH=/^[a-f0-9]{64}$/u,bH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kH="comet.native.checker-policy.v1",SH="comet.native.check-input.v1",EH=2048,Tk=j(kH,{policy:Ln,version:Th,limits:Ue,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),xH=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),jk=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Ok=["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"],CH=new Set(Ok)});function qn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function oi(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function br(e,t){if(typeof e!="string"||!FH.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function jt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=mt(e).trim();if(!r||r.length>VH||r!==e.trim())throw new Error(`${t} is invalid`);return r}function $h(e,t){let r=jt(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function qo(e,t,r=jt,i=!1,n=WH){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function GH(e,t){if(typeof e!="string"||!LH.test(e))throw new Error(`${t} is invalid`);return e}function JH(e){let t=qn(e,"Native verification receipt bindings");if(oi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!qH.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:br(t.contractHash,"Native verification receipt contract hash"),scopeHash:br(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:br(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:br(t.artifactHash,"Native verification receipt artifact hash")}}function UH(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=MH.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function KH(e,t,r,i){let n=qn(t,`Native ${e} evidence`);if(e==="automated-check"){if(oi(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=$h(n.startedAt,"Native automated-check start time"),o=$h(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(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=qn(n.worktree,"Native automated-check worktree");if(oi(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=qn(n.afterFence,"Native automated-check after fence");if(oi(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:jt(n.executable,"Native automated-check executable"),args:qo(n.args,"Native automated-check arguments",jt,!0),cwd:jt(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:jt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:br(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:br(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:br(n.outputHash,"Native automated-check output hash"),outputSummary:jt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){oi(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=UH(n.checkReceiptRef);if(br(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:qo(n.subjects,"Native static inspection subjects",jt,i==="required-check"),rule:jt(n.rule,"Native static inspection rule"),resultSummary:jt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return oi(n,["steps","observations"],"Native manual-evidence evidence"),{steps:qo(n.steps,"Native manual evidence steps"),observations:qo(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function YH(e){let t=qn(e,"Native verification receipt");if(oi(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 r=t.kind,i=t.role,n=t.status,a=jt(t.actor,"Native verification receipt actor"),o=qo(t.acceptanceIds,"Native receipt acceptance IDs",GH,i==="required-check",zH).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Oh,kind:r,role:i,status:n,bindings:JH(t.bindings),acceptanceIds:o,actor:a,issuedAt:$h(t.issuedAt,"Native verification receipt issue time"),evidence:KH(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Ln||s.actor!==`native-runtime:${Ln}`))throw new Error("Native required check policy identity is invalid");return s}function Bk(e){let t=qn(e,"Native verification receipt");if(oi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Oh)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=YH(i),a=br(t.receiptHash,"Native verification receipt hash");if(j(DH,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Hh(e){return j(BH,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var Oh,DH,BH,FH,LH,qH,MH,VH,WH,zH,Mo=I(()=>{"use strict";de();jh();Di();Oh="comet.native.verification-receipt.v3",DH=Oh,BH="comet.native.declared-artifacts.v1",FH=/^[a-f0-9]{64}$/u,LH=/^acceptance-[a-f0-9]{64}$/u,qH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,MH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,VH=4096,WH=256,zH=1024});import{createHash as XH}from"node:crypto";import{promises as $t}from"node:fs";import tr from"node:path";function Dh(e,t){let r=tr.relative(e,t);return r===""||!tr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${tr.sep}`)}function QH(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Kl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Fk(e){let t=await $t.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await $t.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ZH(e,t){let r=tr.resolve(e),i=tr.resolve(t);if(!Dh(r,i))throw new Error("Native evidence path is outside its change");let n=[await Fk(r)],a=r;for(let o of tr.relative(r,i).split(tr.sep).filter(Boolean)){a=tr.join(a,o);let s=await Fk(a);if(!Dh(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function Lk(e){for(let t of e){let r=await $t.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!QH(t,r)||await $t.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function eD(e,t,r={}){let i=await ZH(t,tr.dirname(e));await r.afterParentChainCaptured?.();let n=await $t.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await $t.realpath(e);if(!Dh(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await $t.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),$t.lstat(e),$t.realpath(e)]);if(await Lk(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Kl(s,n)||!Kl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Mn)throw new Error(`Native evidence document exceeds ${Mn} bytes`);await r.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(64*1024);for(;;){let v=Mn+1-d,g=await o.read(p,0,Math.min(p.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>Mn)throw new Error(`Native evidence document exceeds ${Mn} bytes`);u.push(Buffer.from(p.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[f,m,h]=await Promise.all([o.stat(),$t.lstat(e),$t.realpath(e)]);if(await Lk(i),!m.isFile()||m.isSymbolicLink()||h!==a||!Kl(s,f)||!Kl(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function Vk(e,t){if(!Mk.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function tD(e,t,r,i,n){if(!Mk.test(r))throw new Error("Native report evidence hash is invalid");let a=await Mi({paths:e,name:t,kind:"reports",hash:r,hooks:i,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!==r||typeof o.content!="string"||XH("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function Vn(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function rD(e,t,r,i,n){let a=Vk(r,i);return n?tr.join(n,...a.split("/")):Mr(Y(e,t),a)}async function Mi(e){let t=rD(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??Ne(e.paths,t);return await V(r,t),eD(t,r,e.hooks)}function qk(e,t){return Wl(e,t)}function iD(e,t){let r=zl(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function nD(e,t,r){let i=_k(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function aD(e,t,r){let i=Ih(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function oD(e,t,r,i=!1,n){let a=await Yl(e,t,r.implementationScopeRef,void 0,n);if(i&&await tD(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await Wk(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Vo(e,t,r,i,n){let a=Vn(r,"scopes"),o=iD(await Mi({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=Vn(o.baselineProjectionRef,"snapshots"),c=Vn(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Mi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>qk(d,s)),Mi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>qk(d,c))]);return kk({baseline:l,current:u,scope:o})}async function Yl(e,t,r,i,n){return(await Vo(e,t,r,i,n)).scope}async function Wk(e,t,r,i,n){let a=Vn(r,"allowances");return nD(await Mi({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function Wo(e,t,r,i,n){let a=Vn(r,"receipts"),o=Bk(await Mi({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Wn(e,t,r,i,n){let a=Vn(r,"verifications"),o=aD(await Mi({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await oD(e,t,o,!1,n),o}var Mk,Mn,SK,si=I(()=>{"use strict";oe();K();Lt();qi();Ul();Mo();Mk=/^[a-f0-9]{64}$/u,Mn=Li,SK=3*Mn});import zi from"node:path";import{realpathSync as WF}from"node:fs";Ji();Ui();import{execFileSync as hx}from"child_process";import mx from"fs";import di from"path";import{AsyncLocalStorage as Tm}from"node:async_hooks";ta();var pi=new Tm,jm=new Tm;function $m(e){return pi.getStore()?e():pi.run(new Map,e)}function vx(e){let t=pi.getStore();for(let r of e)t?.set(xr(r.root),e);return e}function ia(e,t){return Zn(()=>hx("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function na(e,t){return xr(e)===xr(t)}function xr(e){let t=di.resolve(e);try{let r=mx.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function we(e){try{let t=jm.getStore()?.get(xr(e)),r=pi.getStore()?.get(t??xr(e));if(r){let c=aa(t??e,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=di.resolve(ia(e,["rev-parse","--show-toplevel"])),n=pi.getStore()?.get(xr(i))??Om(e),a=aa(i,n);if(pi.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=ia(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!na(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function us(e){try{let t=pi.getStore()?.get(jm.getStore()?.get(xr(e))??xr(e));return t?t.map(r=>({...r})):(ia(e,["rev-parse","--is-inside-work-tree"]),Om(e))}catch{return[]}}function Om(e){let t=gx(ia(e,["worktree","list","--porcelain","-z"]));return vx(t),t.map(r=>({...r}))}function gx(e){let t=e.split("\0"),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:di.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}function Cr(e){return us(e).map(t=>t.root)}function aa(e,t){let r=t.find(a=>na(di.resolve(a.root),di.resolve(e)));if(!r)return null;let i=di.resolve(t[0].root),n=di.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!na(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function nr(e,t){try{let r=ia(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}de();var Lf=ir(Bt(),1);import{promises as tb}from"fs";import Kr from"path";at();oe();Ni();Qe();Re();K();Ct();Rn();import{createHash as m$}from"crypto";import v$ from"path";var dt=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"});Re();K();import{constants as pl,promises as _t}from"node:fs";import At from"node:path";import{TextDecoder as u$}from"node:util";import o$ from"path";un();Fr();var Yj=ir(Bt(),1);un();Fr();cr();cr();ln();Rp();un();cr();var yW=4*1024*1024;import{AsyncLocalStorage as Xj}from"node:async_hooks";var Qj=new Xj;function Zj(){let e=Qj.getStore();return e?.active?e:null}function e$(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function jN(e,t){return(...r)=>{let i=Zj();if(i===null)return t(...r);let n=e$(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.get(n)?.value===o&&i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}ln();var xW=jN("hookWritePolicy",async e=>(await Sp(e))?.hook??{allow_paths:[]});Va();import{randomUUID as t$}from"node:crypto";import{promises as ll}from"node:fs";import ON from"node:path";var ul="comet.selection.v2",HN=16*1024;function dl(e){return ON.join(e,".comet","current-change.json")}function r$(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $N(e){return e===null||typeof e=="string"}function DN(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!r$(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&&!$N(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:ul,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==ul)throw new Error(`current change selection schema must be ${ul}`);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(!$N(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 Tf(e){let t;try{let i=dl(e),{bytes:n}=await Si(i,HN,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...DN(t)}}async function jf(e,t){let r=DN(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=dl(e),n=`${i}.${t$()}.tmp`;await ll.mkdir(ON.dirname(i),{recursive:!0});try{await ll.writeFile(n,`${JSON.stringify(r.selection,null,2)}
|
|
184
|
+
`,"utf8"),await ll.rename(n,i)}catch(a){throw await ll.rm(n,{force:!0}),a}}Ep();Ba();var BN=(e,t)=>{let r=e[t];return r==null?null:String(r)};function fo(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function po(e,t){let r=fo(e,t);if(o$.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function s$(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(r))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function FN(e){if(!e.run_id)return null;let t=fo(e,"run_id"),r=fo(e,"skill"),i=fo(e,"skill_version"),n=fo(e,"skill_hash"),a=po(e,"pending_ref"),o=po(e,"trajectory_ref"),s=po(e,"context_ref"),c=po(e,"artifacts_ref"),l=po(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:r,skillVersion:i,skillHash:n,orchestration:e.orchestration,currentStep:BN(e,"current_step"),iteration:u,pending:BN(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:s$(e)}}var Az=Number.MAX_SAFE_INTEGER;var c$=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function l$(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)},r=FN(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function $f(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,r=Object.keys(t).find(i=>!c$.has(i));if(r)throw new Error(`Invalid Run state: unknown field ${r}`);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 l$(t)}oe();Lt();var Pn={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};function hl(e,t){let r=At.relative(e,t);return r===""||!At.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${At.sep}`)}function d$(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function fl(e,t){return G({...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 p$(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ml(e,t,r){let i=dt[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=At.resolve(e),a=At.resolve(n,...i.slice(8).split("/"));if(!hl(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function LN(e){let t=await _t.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await _t.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function f$(e,t){let r=At.resolve(e),i=At.resolve(t);if(!hl(r,i))throw new Error("Native Run path is outside its change");let n=[await LN(r)],a=r;for(let o of At.relative(r,i).split(At.sep).filter(Boolean)){a=At.join(a,o);let s;try{s=await LN(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!hl(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function qN(e){for(let t of e){let r=await _t.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!p$(t,r)||await _t.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function h$(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function vl(e,t,r,i,n){let a=await f$(e,At.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await _t.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${i} must be a regular file`);if(o.size>r)throw new Error(`${i} exceeds ${r} bytes`);let s=d$(o),c=await _t.realpath(t);if(!hl(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?pl.O_RDONLY:pl.O_RDONLY|pl.O_NOFOLLOW|pl.O_NONBLOCK,u;try{u=await _t.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,p,f]=await Promise.all([u.stat(),_t.lstat(t),_t.realpath(t)]);if(await qN(a),!d.isFile()||!p.isFile()||p.isSymbolicLink()||f!==c||!fl(s,d)||!fl(s,p))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let m=await h$(u,r,i);await n?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([u.stat(),_t.lstat(t),_t.realpath(t)]);if(await qN(a),!v.isFile()||v.isSymbolicLink()||g!==c||!fl(s,h)||!fl(s,v))throw new Error(`${i} changed while reading`);let b;try{b=new u$("utf-8",{fatal:!0}).decode(m)}catch(k){throw new Error(`${i} is not valid UTF-8`,{cause:k})}return{text:b,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function MN(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function Of(e){return $f(e)}async function _n(e,t){let r=ml(e,"stateRef"),i=await vl(e,r,Pn.runStateBytes,"Native Run state",t);return i?$f(MN(i.text,"Native Run state")):null}async function Ai(e,t,r){let i=ml(e,"trajectoryRef",t),n=await vl(e,i,Pn.trajectoryBytes,"Native Run trajectory",r);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>Pn.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Pn.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 VN(e,t,r){return(await vl(e,ml(e,"trajectoryRef",t),Pn.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function gl(e,t,r){let i=await vl(e,ml(e,"checkpointRef",t),Pn.checkpointBytes,"Native Run checkpoint",r);return i?MN(i.text,"Native Run checkpoint"):null}var g$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Hf(e){return m$("sha256").update(e).digest("hex")}function w$(e,t){if(!g$.test(t))throw new Error(`Invalid Native change name: ${t}`);return v$.join(Y(e,t),"trajectory.jsonl")}function y$(e){let t=e.split(/\n/u),r=0;for(let i=0;i<t.length;i+=1){let n=t[i].endsWith("\r")?t[i].slice(0,-1):t[i];if(n.length!==0){r=i+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:i+1,message:a.message}}}}return{status:"valid",count:r}}function N$(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let r=/position (\d+)/iu.exec(e.message)?.[1];return r!==void 0&&Number(r)>=Math.max(0,t.length-1)}function b$(e,t){let r=t.lastIndexOf(10),i=t.subarray(0,r+1),n=y$(i.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(r===t.length-1)return{status:"clean",file:e};let a=t.subarray(r+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(`
|
|
185
|
+
`)])}catch(d){if(!N$(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=i}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Hf(t),targetHash:Hf(l),tailHash:Hf(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function k$(e,t){let r=w$(e,t);await V(Ne(e,r),r);let i=Y(e,t),n=await VN(i,dt.trajectoryRef);return n===null?{status:"clean",file:r}:b$(r,Buffer.from(n))}async function WN(e,t){let r=await k$(e,t);return"inspection"in r?r.inspection:r}import{createHash as S$}from"node:crypto";import{promises as wl}from"node:fs";import hr from"node:path";oe();at();Re();K();var ho=/^[a-f0-9]{64}$/u,zN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,E$=16*1024,Bf=process.platform,x$=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function An(e){return x$.has(e)}function KN(e,t){let r=hr.relative(e,t);return hr.isAbsolute(r)||r===".."||r.startsWith(`..${hr.sep}`)?null:r.replaceAll("\\","/")||"."}function YN(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function XN(e,t){if(e.length===0||YN(e)||e.includes("\\")||hr.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=hr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Ff(e,t){return S$("sha256").update(`${e}
|
|
186
|
+
${t}`).digest("hex")}async function GN(e,t){let r=await wl.realpath(t),i=await wl.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Bf==="win32"?hr.normalize(r).toLowerCase():r;return Ff(e,`${n}
|
|
183
187
|
${i.dev}
|
|
184
188
|
${i.ino}
|
|
185
|
-
${i.birthtimeMs}`)}async function
|
|
189
|
+
${i.birthtimeMs}`)}async function JN(e,t){let r=await wl.realpath(t),i=await wl.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Bf==="win32"?hr.normalize(r).toLowerCase():r;return Ff(e,n)}function C$(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 Df(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||YN(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function QN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Df(e.changeBranch,"Native workspace change branch"),Df(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 R$(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!zN.test(t.baseCommit)||typeof t.targetCommit!="string"||!zN.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Df(t.targetBranch,"Native workspace Git target branch")}function yl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!ho.test(String(t.projectRootId))||!ho.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");C$(t.capturedAt),XN(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&&!ho.test(String(t.projectRootPathId))||a&&!ho.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!ho.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&R$(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(QN(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 P$(e,t){return hr.join(Y(e,t),"workspace.json")}function _$(e,t){let r=P$(e,t),i=Ne(e,r),n=KN(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:XN(n,"Native workspace file ref")}}async function A$(e,t){try{let r=_$(e,t),i=await re({root:r.root,ref:r.ref,maxBytes:E$});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function mo(e,t){let r=we(e.projectRoot),i={projectRoot:hr.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await mr(e,t);if(n===null)return{...i,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...i,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await In({paths:e,identity:n});return{...i,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...i,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function I$(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=KN(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=we(e.paths.projectRoot),i=r.isGitWorktree?nr(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:nr(e.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([GN("comet.native.workspace-project-root.v2",e.paths.projectRoot),GN("comet.native.workspace-native-root.v2",e.paths.nativeRoot),JN("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),JN("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&&QN(e.binding);let p={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Ff("comet.native.workspace-session.v2",`${s}
|
|
186
190
|
${c}
|
|
187
|
-
${e.sessionId}`)}:{}},f=e.binding?{schema:"comet.native.workspace.v3",...p,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...p};return
|
|
188
|
-
`).trim())};for(let
|
|
189
|
-
`).trim()}function
|
|
190
|
-
`))}function I$(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(ib))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(ib))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=nb(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:ab(e.markdown)},markdown:e.markdown}}function T$(e,t){return ob(e.id,t.id)}function ob(e,t){return e<t?-1:e>t?1:0}function sb(e){let t=nb(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(I$).sort((d,p)=>ob(d.snapshot.capability,p.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.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=Xp(e.briefMarkdown,t,yo.maxAcceptanceCriteria);for(let{snapshot:d,markdown:p}of r)p===null||d.source===null||(a.push(...Qp(p,d.source,yo.maxAcceptanceCriteria-a.length)),a.push(...Sy(p,d.source,yo.maxAcceptanceCriteria-a.length)));if(a.sort(T$),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>yo.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${yo.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:ab(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=j(A$,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(_$,u)}}var j$={maxSpecs:64};async function In(e){if(e.specChanges.length>j$.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await re({root:e.changeDir,ref:e.briefRef,maxBytes:null}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await re({root:e.changeDir,ref:n.source,maxBytes:null});r+=a.size,i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:sb({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}Qe();Re();import{promises as z$}from"node:fs";import Jf from"node:path";pt();import{promises as B$}from"node:fs";oe();io();import cb from"node:path";function No(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function bo(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Le(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function Tn(e,t){return e===null?null:Le(e,t)}function jn(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function F$(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 L$(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function $n(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Vf(e,t){if(e===null)return null;let r=Le(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function q$(e,t){let r=Le(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Wf(e,t){let r=Le(e,t);if(!cb.isAbsolute(r))throw new Error(`${t} must be absolute`);return cb.resolve(r)}function M$(e,t){let r=`Native local checks[${t}]`,i=No(e,r);if(bo(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((u,d)=>Le(u,`${r}.argv[${d}]`,!0)),a=$n(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Vf(i.startedAt,`${r}.startedAt`),s=Vf(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=jn(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=No(i.activeProcess,`${r}.activeProcess`),d=$n(u.status,["starting","running"],`${r}.activeProcess.status`);if(bo(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:jn(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:Le(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:Le(i.id,`${r}.id`),name:Le(i.name,`${r}.name`),operationId:Le(i.operationId,`${r}.operationId`),status:a,repeatable:L$(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:jn(i.executionCount,`${r}.executionCount`),argv:n,cwd:Wf(i.cwd,`${r}.cwd`),exitCode:F$(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Le(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:$n(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:Le(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function V$(e){let t="Native local execution state",r=No(e,t);if(bo(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Vc)throw new Error(`Native local execution schema must be ${Vc}`);let i=No(r.workspace,"Native local workspace");bo(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=No(r.execution,"Native local execution");bo(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Vf(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Le(o.operationId,"Native local execution.operationId"),stage:$n(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:$n(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Tn(o.executionId,"Native local execution.executionId"),status:$n(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:jn(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:q$(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:jn(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:Le(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(M$);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:Vc,change:Le(r.change,"Native local change"),basedOnStateVersion:jn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:Tn(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:Tn(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:Tn(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:Tn(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Wf(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Wf(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Tn(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:Le(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}async function Sl(e){let t;try{t=await B$.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return V$(r)}function zf(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}function Gf(e,t){if(zf(e,t)!==void 0)return t.execution.verifierStartedAt!=null||t.execution.requestCheckRounds>0?"confirmed":"unconfirmed"}xt();K();var lb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ub="comet-state.yaml",db="state.json";function Ai(e,t){if(!lb.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Jf.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}function El(e,t){return Jf.join(Ai(e,t),ub)}function Yr(e,t){return Jf.join(Et(e,t),db)}async function ko(e,t){try{let r=await z$.readFile(El(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function ft(e,t){return Vr(El(e,t))}async function Uf(e){let t=await ft(e.paths,e.name),r=Yr(e.paths,e.name);try{let i=await Sl(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}function Qf(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ji=Qf();function yb(e){ji=e}var Ii={exec:()=>null};function On(e){let t=[];return r=>{let i=Math.max(0,Math.min(3,r-1)),n=t[i];return n||(n=e(i),t[i]=n),n}}function M(e,t=""){let r=typeof e=="string"?e:e.source,i={replace:(n,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(_e.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,t)};return i}var G$=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),_e={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:On(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:On(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:On(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:On(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:On(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:On(e=>new RegExp(`^ {0,${e}}>`))},J$=/^(?:[ \t]*(?:\n|$))+/,U$=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,K$=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,xo=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Y$=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Zf=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Nb=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,bb=M(Nb).replace(/bull/g,Zf).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),X$=M(Nb).replace(/bull/g,Zf).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),eh=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Q$=/^[^\n]+/,th=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Z$=M(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",th).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),e0=M(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Zf).getRegex(),_l="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",rh=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,t0=M("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",rh).replace("tag",_l).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),kb=e=>M(eh).replace("hr",xo).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_l).getRegex(),r0=kb(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),i0=kb(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),n0=M(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",i0).getRegex(),ih={blockquote:n0,code:U$,def:Z$,fences:K$,heading:Y$,hr:xo,html:t0,lheading:bb,list:e0,newline:J$,paragraph:r0,table:Ii,text:Q$},pb=M("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",xo).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_l).getRegex(),a0={...ih,lheading:X$,table:pb,paragraph:M(eh).replace("hr",xo).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",pb).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_l).getRegex()},o0={...ih,html:M(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",rh).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ii,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:M(eh).replace("hr",xo).replace("heading",` *#{1,6} *[^
|
|
191
|
-
|
|
191
|
+
${e.sessionId}`)}:{}},f=e.binding?{schema:"comet.native.workspace.v3",...p,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...p};return yl(f),f}async function mr(e,t){let r=await A$(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(yl(r),r)}async function Nl(e){yl(e.identity);let t=await I$({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),Bf==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function In(e){if(yl(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 Nl(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=we(e.paths.projectRoot);return e.identity.changeBranch===null?r.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}:r.isGitWorktree?r.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 ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.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 ZN(e,t){let r=await mr(e,t);if(r===null)return null;let i=await In({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}Qa();qc();qc();var bl=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},vo=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},kl=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},A2=fc("en");function ke(e,t){Ei(t);let r=Kr.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Sl(e,t){let r=Y(e,t),i=Kr.join(r,"schema-migration.json");await V(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await tb.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function rb(e,t){let r=Y(e,t),i=Kr.join(r,"checkpoint-journal.json");await V(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await tb.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function ib(e,t=Kr.dirname(e)){let r=Kr.relative(t,e).split(Kr.sep).join("/"),i=await re({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Lf.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function qf(e,t){let r=Kr.join(ke(e,t),zt);await V(e.nativeRoot,r);let i=Lc(await ib(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Sl(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await $$(e,i.state),i)}async function nb(e,t){let r=Kr.join(ke(e,t),zt);await V(e.nativeRoot,r);let i=Lc(await ib(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function $$(e,t){if(await cl(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Yt(e,t){let r=await qf(e,t);if(r.status==="migration-required")throw new mn(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new dr(r.schema,r.minimumRuntimeVersion);return await ZN(e,t),r.state}Qe();import{promises as mF}from"fs";Ni();import{promises as Mf}from"fs";import ob from"path";at();Ut();K();var Vf=["outcome","scope","nonGoals","acceptanceExamples"],ab=[...Vf,"constraints","decisions","openQuestions","verificationExpectations"],O$=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],H$=new Set(["nonGoals","decisions","openQuestions"]),go=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change},sb={maxFileBytes:sp};function cb(e){let t=new Map,r=null,i=[],n={marker:null,length:0},a=()=>{r!==null&&t.set(r,i.join(`
|
|
192
|
+
`).trim())};for(let o of e.split(/\r?\n/u)){let c=yo(o,n)===null&&n.marker===null?/^# ([^#].*)$/u.exec(o):null;c?(a(),r=c[1].trim(),i=[]):r!==null&&i.push(o)}return a(),t}async function D$(e,t){let r=ob.resolve(e,...t.split(/[\\/]/u));if(!q(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await Mf.realpath(e),n=await Mf.realpath(r);if(!q(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Mf.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function wo(e){return{valid:e.length===0,findings:e}}function lb(e){let t=[],r=0;for(;r<e.length;){let i=e.indexOf("<!--",r);if(i<0){t.push(e.slice(r));break}t.push(e.slice(r,i));let n=e.indexOf("-->",i+4);if(n<0){t.push(e.slice(i));break}r=n+3}return t.join("")}function Wf(e){return lb(e).trim()}function El(e){let t=Wf(e).split(/\r?\n/u),r=[],i={marker:null,length:0};for(let n of t)yo(n,i)===null&&(i.marker===null&&/^\s*#{1,6}\s*$/u.test(n)||i.marker===null&&/^\s*#{1,6}\s+/u.test(n)||i.marker===null&&/^\s*(?:[-*+]\s*|\d+[.)]\s*)$/u.test(n)||r.push(n));return r.join(`
|
|
193
|
+
`).trim()}function B$(e){let t=El(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim().toLocaleLowerCase("en-US");return/^(?:none|n\/a|not applicable|no(?:ne)?(?:\s+at\s+this\s+time)?|no\s+(?:additional\s+)?(?:non-goals?|decisions?|open\s+questions?|questions?)|无|无相关事项|没有(?:额外)?(?:非目标|决定|待解决问题)|不适用|暂无)[.!。;;::,,、 -]*$/iu.test(t)}function ub(e){let t=El(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/\s+/gu," ").trim();if(t.length===0)return!1;let r=t.replace(/[*_`]/gu,"").replace(/^\s*>+\s?/gmu,"").replace(/\s+/gu," ").trim();if(/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!。;;::,,、 -]*$/iu.test(r))return!0;let i=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:(?:todo|tbd|fixme)(?:\s*[::-]\s*.+)?|fill(?:\s+this\s+in)?(?:\s*[::-]\s*.+)?|placeholder(?:\s*[::-]\s*.+)?|待填写\S*|待补充\S*|<[^>]+>|\{\{[^}]+\}\})[.!。;;::,,、 -]*$/iu.test(i)}function db(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r={marker:null,length:0};for(let i of e.split(/\r?\n/u)){if(yo(i,r)!==null||r.marker!==null)continue;let n=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(n)||n.includes("|")&&n.split("|").some(o=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(o)))return!0;let a=n.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(a){let o=a[1]?.toLocaleLowerCase("en-US")??"";if(t.has(o)||/[./_-]/u.test(o))return!0}}return!1}function yo(e,t){let r=/^ {0,3}(`{3,}|~{3,})/u.exec(e);if(r===null)return null;let i=r[1]??"",n=i[0];return t.marker===null?(t.marker=n,t.length=i.length,"opened"):n===t.marker&&i.length>=t.length&&e.trim()===i?(t.marker=null,t.length=0,"closed"):null}function F$(e){let t=Wf(e).split(/\r?\n/u),r={marker:null,length:0},i=-1;for(let n=0;n<t.length;n+=1){let a=t[n]??"";if(yo(a,r)!==null||r.marker!==null)continue;let o=/^##\s+(.+)$/u.exec(a);if(o!==null){if(i===-1){jw(o[1]??"")&&(i=n+1);continue}return t.slice(i,n).join(`
|
|
194
|
+
`)}}return i===-1?null:t.slice(i).join(`
|
|
195
|
+
`)}function L$(e){let t=new Map,r=null,i=[],n={marker:null,length:0},a=()=>{r!==null&&t.set(r,i.join(`
|
|
196
|
+
`).trim())};for(let o of Wf(e).split(/\r?\n/u)){if(yo(o,n)!==null){r!==null&&i.push(o);continue}let s=n.marker===null?/^###\s+(.+)$/u.exec(o):null;s!==null?(a(),r=$w(s[1]??""),i=[]):r!==null&&i.push(o)}return a(),t}function q$(e,t){let r=[],i=F$(e);if(i===null)return r.push({code:"brief-structure-missing",message:'Brief scope must include a "## Directory structure"/「## 目录结构」 section with the subsections Created/新建, Modified/修改, Deleted/删除, and Not created/明确不建',path:t}),r;let n=L$(i),a=[];for(let o of gp){let s=n.get(o);(s===void 0||El(s).length===0||ub(s))&&a.push(Tw(o))}return a.length>0&&r.push({code:"brief-structure-subsection-missing",message:`Brief directory structure subsections are missing or empty: ${a.join(", ")}. Keep every heading and write "None"/「无」 when there is no content`,path:t}),r}async function xl(e,t,r={}){let i=[],n;try{n=(await re({root:e,ref:t,maxBytes:sb.maxFileBytes})).text}catch(s){return wo([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,c]of cb(n))a.set(pc(s)??s,c);for(let s of r.compact?Vf:ab)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?ab.filter(s=>!r.compact||a.has(s)):Vf;for(let s of o){let c=a.get(s)??"";El(c).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):ub(c)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!H$.has(s)&&B$(c)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return r.strict&&r.structure&&i.push(...q$(a.get("scope")??"",t)),db(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),wo(i)}async function zf(e,t){let r=[],i;try{i=(await re({root:e,ref:t,maxBytes:sb.maxFileBytes})).text}catch(a){return wo([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of cb(i))n.set(Iw(a)??a,o);for(let a of O$)n.has(a)?(n.get(a)??"").length===0&&r.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):r.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return wo(r)}function No(e,t){return ob.join(e.specsDir,t,"spec.md")}async function pb(e,t){let r=[],i=ke(e,t.name);for(let n of t.spec_changes){let a=No(e,n.capability),o=null;try{await V(e.nativeRoot,a),o=await Sf(a)}catch(s){if(s.code!=="ENOENT"){r.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&r.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&r.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&r.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await D$(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return wo(r)}ro();de();at();ro();de();import fb from"node:path";var M$="comet.native.contract.v1",V$="comet.native.acceptance-set.v1",hb=/^[a-f0-9]{64}$/u,bo={maxAcceptanceCriteria:to.maxCriteria};function mb(e,t){let r=fb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||fb.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function vb(e){return j("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
197
|
+
`))}function W$(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(hb))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(hb))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=mb(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:vb(e.markdown)},markdown:e.markdown}}function z$(e,t){return gb(e.id,t.id)}function gb(e,t){return e<t?-1:e>t?1:0}function wb(e){let t=mb(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(W$).sort((d,p)=>gb(d.snapshot.capability,p.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.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=tf(e.briefMarkdown,t,bo.maxAcceptanceCriteria);for(let{snapshot:d,markdown:p}of r)p===null||d.source===null||(a.push(...rf(p,d.source,bo.maxAcceptanceCriteria-a.length)),a.push(...jy(p,d.source,bo.maxAcceptanceCriteria-a.length)));if(a.sort(z$),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>bo.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${bo.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:vb(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=j(V$,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(M$,u)}}var G$={maxSpecs:64};async function Tn(e){if(e.specChanges.length>G$.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await re({root:e.changeDir,ref:e.briefRef,maxBytes:null}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await re({root:e.changeDir,ref:n.source,maxBytes:null});r+=a.size,i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:wb({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}Qe();Re();import{promises as n0}from"node:fs";import Xf from"node:path";pt();import{promises as X$}from"node:fs";oe();no();import yb from"node:path";function ko(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function So(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Le(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function jn(e,t){return e===null?null:Le(e,t)}function $n(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function Q$(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 Z$(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function On(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Jf(e,t){if(e===null)return null;let r=Le(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function e0(e,t){let r=Le(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Uf(e,t){let r=Le(e,t);if(!yb.isAbsolute(r))throw new Error(`${t} must be absolute`);return yb.resolve(r)}function t0(e,t){let r=`Native local checks[${t}]`,i=ko(e,r);if(So(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((u,d)=>Le(u,`${r}.argv[${d}]`,!0)),a=On(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Jf(i.startedAt,`${r}.startedAt`),s=Jf(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=$n(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=ko(i.activeProcess,`${r}.activeProcess`),d=On(u.status,["starting","running"],`${r}.activeProcess.status`);if(So(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:$n(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:Le(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:Le(i.id,`${r}.id`),name:Le(i.name,`${r}.name`),operationId:Le(i.operationId,`${r}.operationId`),status:a,repeatable:Z$(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:$n(i.executionCount,`${r}.executionCount`),argv:n,cwd:Uf(i.cwd,`${r}.cwd`),exitCode:Q$(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Le(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:On(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:Le(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function r0(e){let t="Native local execution state",r=ko(e,t);if(So(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==zc)throw new Error(`Native local execution schema must be ${zc}`);let i=ko(r.workspace,"Native local workspace");So(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=ko(r.execution,"Native local execution");So(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Jf(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Le(o.operationId,"Native local execution.operationId"),stage:On(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:On(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:jn(o.executionId,"Native local execution.executionId"),status:On(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:$n(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:e0(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:$n(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:Le(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(t0);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:zc,change:Le(r.change,"Native local change"),basedOnStateVersion:$n(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:jn(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:jn(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:jn(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:jn(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Uf(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Uf(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:jn(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:Le(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}async function Cl(e){let t;try{t=await X$.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return r0(r)}function Kf(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}function Yf(e,t){if(Kf(e,t)!==void 0)return t.execution.verifierStartedAt!=null||t.execution.requestCheckRounds>0?"confirmed":"unconfirmed"}xt();K();var Nb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bb="comet-state.yaml",kb="state.json";function Ii(e,t){if(!Nb.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Xf.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}function Rl(e,t){return Xf.join(Ii(e,t),bb)}function Yr(e,t){return Xf.join(Et(e,t),kb)}async function Eo(e,t){try{let r=await n0.readFile(Rl(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function ft(e,t){return Vr(Rl(e,t))}async function Qf(e){let t=await ft(e.paths,e.name),r=Yr(e.paths,e.name);try{let i=await Cl(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}function rh(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var $i=rh();function Ab(e){$i=e}var Ti={exec:()=>null};function Hn(e){let t=[];return r=>{let i=Math.max(0,Math.min(3,r-1)),n=t[i];return n||(n=e(i),t[i]=n),n}}function M(e,t=""){let r=typeof e=="string"?e:e.source,i={replace:(n,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(_e.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,t)};return i}var a0=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),_e={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Hn(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Hn(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Hn(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Hn(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Hn(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Hn(e=>new RegExp(`^ {0,${e}}>`))},o0=/^(?:[ \t]*(?:\n|$))+/,s0=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,c0=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ro=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,l0=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ih=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ib=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Tb=M(Ib).replace(/bull/g,ih).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),u0=M(Ib).replace(/bull/g,ih).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),nh=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,d0=/^[^\n]+/,ah=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,p0=M(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ah).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),f0=M(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,ih).getRegex(),Tl="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",oh=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,h0=M("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",oh).replace("tag",Tl).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),jb=e=>M(nh).replace("hr",Ro).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Tl).getRegex(),m0=jb(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),v0=jb(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),g0=M(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",v0).getRegex(),sh={blockquote:g0,code:s0,def:p0,fences:c0,heading:l0,hr:Ro,html:h0,lheading:Tb,list:f0,newline:o0,paragraph:m0,table:Ti,text:d0},Sb=M("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ro).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Tl).getRegex(),w0={...sh,lheading:u0,table:Sb,paragraph:M(nh).replace("hr",Ro).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Sb).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Tl).getRegex()},y0={...sh,html:M(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",oh).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ti,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:M(nh).replace("hr",Ro).replace("heading",` *#{1,6} *[^
|
|
198
|
+
]`).replace("lheading",Tb).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},N0=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,b0=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,$b=/^( {2,}|\\)\n(?!\s*$)/,k0=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,vr=/[\p{P}\p{S}]/u,Dn=/[\s\p{P}\p{S}]/u,Po=/[^\s\p{P}\p{S}]/u,S0=M(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Dn).getRegex(),E0=/[\p{Pi}\p{Ps}"']/u,Ob=/(?!~)[\p{P}\p{S}]/u,x0=/(?!~)[\s\p{P}\p{S}]/u,C0=/(?:[^\s\p{P}\p{S}]|~)/u,R0=M(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",a0?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Hb=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,P0=M(Hb,"u").replace(/punct/g,vr).getRegex(),_0=M(Hb,"u").replace(/punct/g,Ob).getRegex(),A0=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,I0=M(A0,"u").replace(/openQuote/g,E0).replace(/punct/g,vr).getRegex(),Db="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",T0=M(Db,"gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Dn).replace(/punct/g,vr).getRegex(),j0=M(Db,"gu").replace(/notPunctSpace/g,C0).replace(/punctSpace/g,x0).replace(/punct/g,Ob).getRegex(),$0="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",O0=M($0,"gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Dn).replace(/punct/g,vr).getRegex(),H0=M("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Dn).replace(/punct/g,vr).getRegex(),D0="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",B0=M(D0,"gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Dn).replace(/punct/g,vr).getRegex(),F0=M(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,vr).getRegex(),L0="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",q0=M(L0,"gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Dn).replace(/punct/g,vr).getRegex(),M0=M(/\\(punct)/,"gu").replace(/punct/g,vr).getRegex(),V0=M(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),W0=M(oh).replace("(?:-->|$)","-->").getRegex(),z0=M("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",W0).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),_l=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,G0=M(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",_l).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Bb=M(/^!?\[(label)\]\[(ref)\]/).replace("label",_l).replace("ref",ah).getRegex(),Fb=M(/^!?\[(ref)\](?:\[\])?/).replace("ref",ah).getRegex(),J0=M("reflink|nolink(?!\\()","g").replace("reflink",Bb).replace("nolink",Fb).getRegex(),Eb=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ch={_backpedal:Ti,anyPunctuation:M0,autolink:V0,blockSkip:R0,br:$b,code:b0,del:Ti,delLDelim:Ti,delRDelim:Ti,emStrongLDelim:P0,emStrongRDelimAst:T0,emStrongRDelimUnd:H0,escape:N0,link:G0,nolink:Fb,punctuation:S0,reflink:Bb,reflinkSearch:J0,tag:z0,text:k0,url:Ti},U0={...ch,emStrongLDelim:I0,emStrongRDelimAst:O0,emStrongRDelimUnd:B0,link:M(/^!?\[(label)\]\((.*?)\)/).replace("label",_l).getRegex(),reflink:M(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",_l).getRegex()},Zf={...ch,emStrongRDelimAst:j0,emStrongLDelim:_0,delLDelim:F0,delRDelim:q0,url:M(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Eb).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:M(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Eb).getRegex()},K0={...Zf,br:M($b).replace("{2,}","*").getRegex(),text:M(Zf.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Pl={normal:sh,gfm:w0,pedantic:y0},xo={normal:ch,gfm:Zf,breaks:K0,pedantic:U0},Y0={"&":"&","<":"<",">":">",'"':""","'":"'"},xb=e=>Y0[e];function Xt(e,t){if(t){if(_e.escapeTest.test(e))return e.replace(_e.escapeReplace,xb)}else if(_e.escapeTestNoEncode.test(e))return e.replace(_e.escapeReplaceNoEncode,xb);return e}function Cb(e){try{e=encodeURI(e).replace(_e.percentDecode,"%")}catch{return null}return e}function Rb(e,t){let r=e.replace(_e.findPipe,(a,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),i=r.split(_e.splitPipe),n=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),t)if(i.length>t)i.splice(t);else for(;i.length<t;)i.push("");for(;n<i.length;n++)i[n]=i[n].trim().replace(_e.slashPipe,"|");return i}function Xr(e,t,r){let i=e.length;if(i===0)return"";let n=0;for(;n<i;){let a=e.charAt(i-n-1);if(a===t&&!r)n++;else if(a!==t&&r)n++;else break}return e.slice(0,i-n)}function Pb(e){let t=e.split(`
|
|
192
199
|
`),r=t.length-1;for(;r>=0&&_e.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
|
|
193
|
-
`)}function
|
|
200
|
+
`)}function X0(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let i=0;i<e.length;i++)if(e[i]==="\\")i++;else if(e[i]===t[0])r++;else if(e[i]===t[1]&&(r--,r<0))return i;return r>0?-2:-1}function Q0(e,t=0){let r=t,i="";for(let n of e)if(n===" "){let a=4-r%4;i+=" ".repeat(a),r+=a}else i+=n,r++;return i}function _b(e,t,r,i,n){let a=t.href,o=t.title||null,s=e[1].replace(n.other.outputLinkReplace,"$1"),c=e[0].charAt(0)==="!";i.state.inLink=!0;let l=i.state.linkEmitted,u=i.state.inRawBlock;i.state.linkEmitted=!1;let d=i.inlineTokens(s),p=i.state.linkEmitted;if(i.state.linkEmitted=l,i.state.inLink=!1,!c){if(p){i.state.inRawBlock=u;return}i.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:a,title:o,text:s,tokens:d}}function Z0(e,t,r){let i=e.match(r.other.indentCodeCompensation);if(i===null)return t;let n=i[1];return t.split(`
|
|
194
201
|
`).map(a=>{let o=a.match(r.other.beginningSpace);if(o===null)return a;let[s]=o;return s.length>=n.length?a.slice(n.length):a}).join(`
|
|
195
|
-
`)}var
|
|
202
|
+
`)}var Al=class{options;rules;lexer;constructor(e){this.options=e||$i}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=this.options.pedantic?t[0]:Pb(t[0]),i=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:i}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],i=Z0(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:i}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let i=Xr(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:Xr(t[0],`
|
|
196
203
|
`),depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Xr(t[0],`
|
|
197
204
|
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=Xr(t[0],`
|
|
198
205
|
`).split(`
|
|
@@ -206,19 +213,19 @@ ${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
206
213
|
${m}`,n=n.substring(0,n.length-f.text.length)+v.text;break}else if(p?.type==="list"){let f=p,m=f.raw+`
|
|
207
214
|
`+r.join(`
|
|
208
215
|
`),h=this.list(m);a[a.length-1]=h,i=i.substring(0,i.length-p.raw.length)+h.raw,n=n.substring(0,n.length-f.raw.length)+h.raw,r=m.substring(a.at(-1).raw.length).split(`
|
|
209
|
-
`);continue}}return{type:"blockquote",raw:i,tokens:a,text:n}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),i=r.length>1,n={type:"list",raw:"",ordered:i,start:i?+r.slice(0,-1):"",loose:!1,items:[]};r=i?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=i?r:"[*+-]");let a=this.rules.other.listItemRegex(r),o=!1;for(;e;){let c=!1,l="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let d=
|
|
216
|
+
`);continue}}return{type:"blockquote",raw:i,tokens:a,text:n}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),i=r.length>1,n={type:"list",raw:"",ordered:i,start:i?+r.slice(0,-1):"",loose:!1,items:[]};r=i?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=i?r:"[*+-]");let a=this.rules.other.listItemRegex(r),o=!1;for(;e;){let c=!1,l="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let d=Q0(t[2].split(`
|
|
210
217
|
`,1)[0],t[1].length),p=e.split(`
|
|
211
218
|
`,1)[0],f=!d.trim(),m=0;if(this.options.pedantic?(m=2,u=d.trimStart()):f?m=t[1].length+1:(m=d.search(this.rules.other.nonSpaceChar),m=m>4?1:m,u=d.slice(m),m+=t[1].length),f&&this.rules.other.blankLine.test(p)&&(l+=p+`
|
|
212
219
|
`,e=e.substring(p.length+1),c=!0),!c){let h=this.rules.other.nextBulletRegex(m),v=this.rules.other.hrRegex(m),g=this.rules.other.fencesBeginRegex(m),b=this.rules.other.headingBeginRegex(m),k=this.rules.other.htmlBeginRegex(m),N=this.rules.other.blockquoteBeginRegex(m);for(;e;){let x=e.split(`
|
|
213
220
|
`,1)[0],w;if(p=x,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),w=p):w=p.replace(this.rules.other.tabCharGlobal," "),g.test(p)||b.test(p)||k.test(p)||N.test(p)||h.test(p)||v.test(p))break;if(w.search(this.rules.other.nonSpaceChar)>=m||!p.trim())u+=`
|
|
214
221
|
`+w.slice(m);else{if(f||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||g.test(d)||b.test(d)||v.test(d))break;u+=`
|
|
215
222
|
`+p}f=!p.trim(),l+=x+`
|
|
216
|
-
`,e=e.substring(x.length+1),d=w.slice(m)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(o=!0)),n.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),n.raw+=l}let s=n.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let c of n.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!n.loose){let l=c.tokens.filter(d=>d.type==="space"),u=l.length>0&&l.some(d=>this.rules.other.anyLine.test(d.raw));n.loose=u}for(let c of n.items){let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=d.checked,n.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=d.raw+c.tokens[0].raw,c.tokens[0].text=d.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(d)):c.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):c.tokens.unshift(d)}}else c.task&&(c.task=!1)}if(n.loose)for(let c of n.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return n}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=
|
|
217
|
-
`),href:i,title:n}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=
|
|
223
|
+
`,e=e.substring(x.length+1),d=w.slice(m)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(o=!0)),n.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),n.raw+=l}let s=n.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let c of n.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!n.loose){let l=c.tokens.filter(d=>d.type==="space"),u=l.length>0&&l.some(d=>this.rules.other.anyLine.test(d.raw));n.loose=u}for(let c of n.items){let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=d.checked,n.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=d.raw+c.tokens[0].raw,c.tokens[0].text=d.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(d)):c.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):c.tokens.unshift(d)}}else c.task&&(c.task=!1)}if(n.loose)for(let c of n.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return n}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=Pb(t[0]);return{type:"html",block:!0,raw:r,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:r}}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:Xr(t[0],`
|
|
224
|
+
`),href:i,title:n}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=Rb(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
218
225
|
`):[],a={type:"table",raw:Xr(t[0],`
|
|
219
|
-
`),header:[],align:[],rows:[]};if(r.length===i.length){for(let o of i)this.rules.other.tableAlignRight.test(o)?a.align.push("right"):this.rules.other.tableAlignCenter.test(o)?a.align.push("center"):this.rules.other.tableAlignLeft.test(o)?a.align.push("left"):a.align.push(null);for(let o=0;o<r.length;o++)a.header.push({text:r[o],tokens:this.lexer.inline(r[o]),header:!0,align:a.align[o]});for(let o of n)a.rows.push(
|
|
226
|
+
`),header:[],align:[],rows:[]};if(r.length===i.length){for(let o of i)this.rules.other.tableAlignRight.test(o)?a.align.push("right"):this.rules.other.tableAlignCenter.test(o)?a.align.push("center"):this.rules.other.tableAlignLeft.test(o)?a.align.push("left"):a.align.push(null);for(let o=0;o<r.length;o++)a.header.push({text:r[o],tokens:this.lexer.inline(r[o]),header:!0,align:a.align[o]});for(let o of n)a.rows.push(Rb(o,a.header.length).map((s,c)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[c]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:Xr(t[0],`
|
|
220
227
|
`),depth:t[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let r=t[1].charAt(t[1].length-1)===`
|
|
221
|
-
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let a=Xr(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=
|
|
228
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let a=Xr(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=X0(t[2],"()");if(a===-2)return;if(a>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let i=t[2],n="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(i);a&&(i=a[1],n=a[3])}else n=t[3]?t[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?i=i.slice(1):i=i.slice(1,-1)),_b(t,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let i=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=t[i.toLowerCase()];if(!n){let a=r[0].charAt(0);return{type:"text",raw:a,text:a}}return _b(r,n,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let i=this.rules.inline.emStrongLDelim.exec(e);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,c=0,l=i[0][0],u=r===l,d=l==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+n);(i=d.exec(t))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a)continue;if(o=[...a].length,i[3]||i[4]){s+=o;continue}else if(i[5]||i[6]){if(n%3&&!((n+o)%3)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let p=[...i[0]][0].length,f=e.slice(0,n+i.index+p+o);if(Math.min(n,o)%2){let h=f.slice(1,-1);return{type:"em",raw:f,text:h,tokens:this.lexer.inlineTokens(h)}}let m=f.slice(2,-2);return{type:"strong",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(r),n=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return i&&n&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,r=""){let i=this.rules.inline.delLDelim.exec(e);if(i&&(!i[1]||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(i=c.exec(t))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a||(o=[...a].length,o!==n))continue;if(i[3]||i[4]){s+=o;continue}if(s-=o,s>0)continue;o=Math.min(o,o+s);let l=[...i[0]][0].length,u=e.slice(0,n+i.index+l+o),d=u.slice(n,-n);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,i;return t[2]==="@"?(r=t[1],i="mailto:"+r):(r=t[1],i=r),{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,i;if(t[2]==="@")r=t[0],i="mailto:"+r;else{let n;do n=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(n!==t[0]);r=t[0],t[1]==="www."?i="http://"+t[0]:i=t[0]}return{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},ht=class eh{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||$i,this.options.tokenizer=this.options.tokenizer||new Al,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:_e,block:Pl.normal,inline:xo.normal};this.options.pedantic?(r.block=Pl.pedantic,r.inline=xo.pedantic):this.options.gfm&&(r.block=Pl.gfm,this.options.breaks?r.inline=xo.breaks:r.inline=xo.gfm),this.tokenizer.rules=r}static get rules(){return{block:Pl,inline:xo}}static lex(t,r){return new eh(r).lex(t)}static lexInline(t,r){return new eh(r).inlineTokens(t)}lex(t){t=t.replace(_e.carriageReturn,`
|
|
222
229
|
`),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let i=this.inlineQueue[r];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[],i=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(_e.tabCharGlobal," ").replace(_e.spaceLine,""));let n=1/0;for(;t;){if(t.length<n)n=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let a;if(this.options.extensions?.block?.some(s=>(a=s.call({lexer:this},t,r))?(t=t.substring(a.raw.length),r.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let s=r.at(-1);a.raw.length===1&&s!==void 0?s.raw+=`
|
|
223
230
|
`:r.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
224
231
|
`)?"":`
|
|
@@ -232,7 +239,7 @@ ${m}`,n=n.substring(0,n.length-f.text.length)+v.text;break}else if(p?.type==="li
|
|
|
232
239
|
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a),i=o.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
233
240
|
`)?"":`
|
|
234
241
|
`)+a.raw,s.text+=`
|
|
235
|
-
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let i of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(i[0])&&t.charAt(i.index-1)!=="!")return!0;for(let i of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let n=i[0],a=n.lastIndexOf("[");if(!(n.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,n.slice(a+1,-1)))&&!(a>1&&this.linkInText(n.slice(1,a-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let i=t;if(this.tokens.links&&t.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,c=l=>{let u=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,l.slice(u+1,-1)))return l;if(u>1&&l.charAt(0)!=="!"){let d=l.slice(1,u-1);if(this.linkInText(d))return"["+d.replace(s,c)+"]["+"a".repeat(l.length-u-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};i=i.replace(s,c)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(s,c,l)=>{let u=l?l.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,a="",o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let s;if(this.options.extensions?.inline?.some(l=>(s=l.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let l=r.at(-1);s.type==="text"&&l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(t)){t=t.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(t))){t=t.substring(s.raw.length),r.push(s);continue}let c=t;if(this.options.extensions?.startInline){let l=1/0,u=t.slice(1),d;this.options.extensions.startInline.forEach(p=>{d=p.call({lexer:this},u),typeof d=="number"&&d>=0&&(l=Math.min(l,d))}),l<1/0&&l>=0&&(c=t.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),n=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},
|
|
242
|
+
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let i of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(i[0])&&t.charAt(i.index-1)!=="!")return!0;for(let i of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let n=i[0],a=n.lastIndexOf("[");if(!(n.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,n.slice(a+1,-1)))&&!(a>1&&this.linkInText(n.slice(1,a-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let i=t;if(this.tokens.links&&t.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,c=l=>{let u=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,l.slice(u+1,-1)))return l;if(u>1&&l.charAt(0)!=="!"){let d=l.slice(1,u-1);if(this.linkInText(d))return"["+d.replace(s,c)+"]["+"a".repeat(l.length-u-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};i=i.replace(s,c)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(s,c,l)=>{let u=l?l.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,a="",o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let s;if(this.options.extensions?.inline?.some(l=>(s=l.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let l=r.at(-1);s.type==="text"&&l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(t)){t=t.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(t))){t=t.substring(s.raw.length),r.push(s);continue}let c=t;if(this.options.extensions?.startInline){let l=1/0,u=t.slice(1),d;this.options.extensions.startInline.forEach(p=>{d=p.call({lexer:this},u),typeof d=="number"&&d>=0&&(l=Math.min(l,d))}),l<1/0&&l>=0&&(c=t.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),n=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},Il=class{options;parser;constructor(e){this.options=e||$i}space(e){return""}code({text:e,lang:t,escaped:r}){let i=(t||"").match(_e.notSpaceStart)?.[0],n=e.replace(_e.endingNewline,"")+`
|
|
236
243
|
`;return i?'<pre><code class="language-'+Xt(i)+'">'+(r?n:Xt(n,!0))+`</code></pre>
|
|
237
244
|
`:"<pre><code>"+(r?n:Xt(n,!0))+`</code></pre>
|
|
238
245
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
@@ -250,27 +257,27 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
250
257
|
`}tablerow({text:e}){return`<tr>
|
|
251
258
|
${e}</tr>
|
|
252
259
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
|
|
253
|
-
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Xt(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let i=this.parser.parseInline(r),n=
|
|
254
|
-
Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+Xt(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},Ti=new q0;function X(e,t){return Ti.parse(e,t)}X.options=X.setOptions=function(e){return Ti.setOptions(e),X.defaults=Ti.defaults,yb(X.defaults),X};X.getDefaults=Qf;X.defaults=ji;function M0(...e){return Ti.use(...e),X.defaults=Ti.defaults,yb(X.defaults),X}X.use=M0;X.walkTokens=function(e,t){return Ti.walkTokens(e,t)};X.parseInline=Ti.parseInline;X.Parser=It;X.parser=It.parse;X.Renderer=Pl;X.TextRenderer=ah;X.Lexer=ht;X.lexer=ht.lex;X.Tokenizer=Rl;X.Hooks=Eo;X.parse=X;var Q2=X.options,Z2=X.setOptions,eG=X.walkTokens,tG=X.parseInline;var rG=It.parse,iG=ht.lex;oe();at();de();var Gb=ir(Bt(),1);import{promises as EO}from"node:fs";import Tt from"node:path";pt();at();de();Qe();K();xt();Tl();Tl();Oi();ti();pt();Ic();oe();de();Dl();Re();K();qb();Oi();ti();Bl();pt();Qe();Bl();Ua();K();var Fl=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function ph(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`}import bO from"node:path";pt();Qe();Re();Oi();ti();async function Ll(e){let t=ph(e.parent),r=nr(e.paths.projectRoot,t);if(!r)return null;let i=nr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Cr(e.paths.projectRoot).map(o=>bO.resolve(o)).find(o=>we(o).currentBranch===t);if(!n)return null;let a=Ol({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return ch(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function fh(e,t){let r=Tt.normalize(Tt.resolve(e)),i=Tt.normalize(Tt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function xO(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function CO(e){let t=xO(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function hh(e){try{let t=await re({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return CO(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function mh(e){return j("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function RO(e){let t=Cr(e.projectRoot);t.some(i=>fh(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Tt.resolve(n)))]){let n=await xe(i);n&&r.push({projectRoot:i,paths:await Vt(i,n.native.artifact_root),parent:fh(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function PO(e,t){let r=Tt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Vr(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _O(e,t){let r;try{r=await EO.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Tt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Vr(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function AO(e,t,r){let i=Tt.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Tt.sep}`))return null;let n=i.split(Tt.sep).join("/");try{let a=(0,Gb.parseDocument)(Je(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ze(a.toJS({mapAsMap:!1}))}catch{return null}}function IO(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function zb(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Io(e){let t=Tt.join(e.paths.changesDir,e.state.name),r=await hh(t),i=null,n;try{n=await Qt({changeDir:t,validation:Zr(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await et(e.paths,e.state.name,{diagnostics:!0});if(g){let b=Hl(g);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(k=>({...k,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=mh({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Qr){let g=await et(e.paths,e.state.name,{diagnostics:!0});if(!g){let N=e.state.workspace.change_branch??e.state.workspace.target_branch;if(N){let x=await Ll({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});x&&(g=x,await ei(e.paths,x))}}if(g){let N=Hl(g);return e.state.children_contract_hash!==a||n.drift?{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(x=>({...x,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&N.confirmed}}let b=new Map(n.contract.children.map(N=>[N.name,N])),k=n.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:s&&N.depends_on.every(x=>n.contract.children.filter(({name:w})=>w!==N.name).every(({name:w})=>w!==x))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let N of k){if(N.status!=="ready")continue;b.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:k,readyChildren:k.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let c=await RO(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let b=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let k of await _O(g,l)){let N={...k,source:g,committedState:AO(g,k.file,b)};u.set(k.state.name,[...u.get(k.state.name)??[],N])}for(let k of l){let N=await PO(g,k);N&&d.set(k,[...d.get(k)??[],{source:g,state:N}])}}let p=new Map;for(let g of n.contract.children){let b=(u.get(g.name)??[]).find(({source:x,committedState:w})=>x.parent&&w?.name===g.name&&zb(w,o));if(b){p.set(g.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let k=u.get(g.name)?.[0];if(k){p.set(g.name,{kind:"blocked",phase:k.state.phase,projectRoot:k.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let N=d.get(g.name)??[];N.length>1?p.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):N[0]&&p.set(g.name,IO(N[0].state,N[0].source,o))}let f=new Map(n.contract.children.map(g=>[g.name,g])),m=new Map,h=g=>{let b=m.get(g);if(b)return b;let k=f.get(g),x=k.depends_on.map(h).every(({status:O})=>O==="done"),w=p.get(g),S=w?.kind==="active"&&x?k.depends_on.filter(O=>!(u.get(O)??[]).some(({source:T,committedState:Q})=>fh(T.projectRoot,w.projectRoot)&&Q?.name===O&&zb(Q,o))):[],E,y=w?.message??null;w?.kind==="done"?(E=x?"done":"blocked",x||(y=`Native child ${g} was merged before its dependencies`)):w?.kind==="active"?(E=x&&S.length===0?"active":"blocked",x?S.length>0&&(y=`Native child ${g} does not include merged dependencies: ${S.join(", ")}`):y=`Native child ${g} started before its dependencies merged`):w?.kind==="blocked"?E="blocked":(E=s&&x?"ready":"pending",s||(y="Parent Shape confirmation is required"));let C={name:g,summary:k.summary,dependsOn:[...k.depends_on],covers:[...k.covers],status:E,phase:w?.phase??null,projectRoot:w?.projectRoot??null,message:y};return m.set(g,C),C},v=n.contract.children.map(({name:g})=>h(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:v,readyChildren:v.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:v.every(({status:g})=>g==="done")}}Mc();xt();Ri();Ro();jl();Re();Zp();Vp();xt();Ri();oe();yi();Ro();K();yi();si();Qe();var $k=ir(Bt(),1);cr();var pK=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" "));var wK=256*1024;xt();Ri();ti();var XH=dc("en",{compact:!0});Qe();Re();Oi();ti();xt();Ri();pt();Ic();de();import Wn from"node:path";pt();cr();oe();var j6=8*1024*1024;Dl();Re();Ri();K();function eD(e,t){let r=Wn.relative(Wn.resolve(e),Wn.resolve(t));if(Wn.isAbsolute(r)||r===".."||r.startsWith(`..${Wn.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(Wn.sep).join("/");return Lb(e,i),i}function Bk(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:eD(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}var rY=1024*1024*1024;Re();jl();Ro();ti();Re();ti();Re();ff();var J9=16*1024;async function Fk(e){let t=await Pf(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Si(t.selection.change),t.selection)}async function Lk(e,t){return Ce(e,`select change ${t}`,async()=>{Si(t),await ko(e,t)?await ft(e,t):await Yt(e,t),await _f(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}K();async function qk(e,t){let r=[],i=Y(e,t.name),n=Mr(i,dt.stateRef),a;try{a=await Pn(i)}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")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;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&&r.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")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Mr(i,a.trajectoryRef),s=await $N(e,t.name);if(s.status==="repairable")return r.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}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await _i(i,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 r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=Mr(i,a.checkpointRef);try{let u=await ml(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}Cn();import bD from"path";import{isDeepStrictEqual as Mh}from"util";oe();Ut();Ua();Re();K();Ct();Hi();de();de();var zn={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var tD=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function rD(e,t){return e<t?-1:e>t?1:0}function iD(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!tD.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(rD)}function Oh(e=[]){return iD(e,"Native repair failed check IDs",zn.maxFailedCheckIds,!0)}function Mk(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function nD(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Mk(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Mk(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Hh(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(nD(i,a))break;r+=1,i=a}return r}zl();Li();function Dh(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 Vk="repairStagnation",rt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},oD=/^[a-f0-9]{64}$/u;var sD=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),cD=["data","runId","sequence","timestamp","type"],Wk=["disposition","overrideSummaryHash","signatureHash"],lD=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],zk=12;function Fh(e,t){return e<t?-1:e>t?1:0}function Gk(e,t,r){let i=Object.keys(e).sort(Fh);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function Kl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function Jo(e,t){if(typeof e!="string"||!oD.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function uD(e){if(!Array.isArray(e)||e.length>zn.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(Fh)}function Jk(e){if(typeof e!="string"||e.length===0||e.length>rt.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Bh(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>rt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>rt.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(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>rt.maxTextCharacters&&(!n||e.length>rt.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>rt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>rt.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>Bh(s,t+1,r,`${i}[${c}]`));return}let a=Kl(e,i),o=Object.keys(a);if(o.length>rt.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>rt.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>rt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Bh(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function dD(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 pD(e,t,r){let i=Kl(e,`Native repair trajectory event ${t+1}`);if(Gk(i,cD,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(dD(i.timestamp),typeof i.type!="string"||!sD.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(Jk(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Bh(i.data,0,n,"Native trajectory event data"),Kl(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Lh(e){let t=Kl(e,"Native repair trajectory projection"),r=Object.keys(t).sort(Fh),i=r.length===Wk.length&&r.every((l,u)=>l===Wk[u]);i||Gk(t,lD,"Native repair trajectory projection");let n=Jo(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:Jo(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(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Jo(t.contractHash,"Native repair trajectory contract hash"),s=uD(t.failedAcceptanceIds),c=Oh(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 fD(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 hD(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??zk;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Hh({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<zn.warningAtConsecutiveFailures?"continue":a<zn.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function mD(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??zk;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.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 Uk(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>rt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Jk(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 r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=pD(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>rt.maxTotalDataNodes||c>rt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let p=d.data,f=Object.hasOwn(p,"repairScopeHash")?Jo(p.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(p,"implementationScopeHash")?Jo(p.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(p,Vk)){if(i?.contractHash===null&&d.type==="state_transitioned"&&p.previousPhase==="build"&&p.nextPhase==="verify"&&(f!==null&&n!==null&&f!==n||f===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=null,n=f,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=Lh(p[Vk]);if(fD(p,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(r.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&f!==null&&n!==null&&f!==n&&(r.length=0,o=0),f!==null&&(n=f),hD(m,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(i?.contractHash===null&&f!==null&&n!==null&&f!==n)throw new Error("Native repair override cannot cross implementation scope progress");mD(m,r,i);let h=r.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(i=m,r.length>zn.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function Kk(e){return Uk(e).history}function Yk(e){let t=Uk(e).latestProjection;return t?{...t}:null}Ut();var Gn={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:[]},qh=ee("comet-native-runtime:v3:scope-reopen"),vD=[{skillVersion:"3",skillHash:ee("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ee("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ee("comet-native-runtime:v1")}];function Xk(e){return e.skillVersion===Gn.definition.metadata.version&&e.skillHash===qh||vD.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}Ut();Ut();function Qk(e){return ee(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}))}Xa();var iS=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],kD=new Set(iS),nS=new Set([...iS,"minimum_runtime_version","revision"]),SD=new Set([...nS,"operation"]),Vh=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),ED=new Set([...Vh,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Wh=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Gh(e,t){return bD.join(Y(e,t),"transition.json")}function Xl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Jh(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function Yl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function zh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!ED.has(u)),a=[...Vh].find(u=>!Object.hasOwn(r,u)),o=Vh.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Dh(r.summary,"Native transition journal event summary"),mt(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.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(r.noCodeReason!==null&&(Dh(r.noCodeReason,"Native transition journal event no-code reason"),mt(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?Lh(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function xD(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return zh({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return zh(e,t)}function Uh(e,t,r=!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 i=r?xD(e.eventData,e.evidenceHash):zh(e.eventData,e.evidenceHash),n=If(e.nextRun),a=e.previousRun===null?null:If(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function Zk(e,t,r=!1){if(e.skill!==Gn.definition.metadata.name||(r?!Xk(e):e.skillVersion!==Gn.definition.metadata.version||e.skillHash!==qh)||e.orchestration!==Gn.definition.orchestration.mode||e.pendingRef!==dt.pendingRef||e.trajectoryRef!==dt.trajectoryRef||e.contextRef!==dt.contextRef||e.artifactsRef!==dt.artifactsRef||e.checkpointRef!==dt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function eS(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 tS(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 Kh(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(Zk(o,"next Run",i||a!==null),tS(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(Zk(a,"previous Run",!0),tS(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(!Mh(eS(a),eS(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function CD(e,t,r){return ee(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function aS(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function rS(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Yh(e,t,r,i,n=!1){let a=r.eventData,o=rS(e),s=rS(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(i==="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&&Mh(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(i==="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&&Mh(e.spec_changes,t.spec_changes),l=Qk({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||r.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(i==="spec-rebase"){let c=CD(e.name,a.summary,t.spec_changes),l=ee(`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&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.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 RD(e,t){let r=Xl(e);if(Jh(r,SD),r.schema!==pn)throw new Error(`Expected Native transition schema ${pn}`);let i=Yl(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${pn} minimum_runtime_version must be ${3}`);let n=Yl(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Uh(r,t),o=Gt(r.previousState),s=Gt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Yh(o,s,a,r.operation),Kh(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:pn,minimum_runtime_version:3,revision:n,operation:r.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 PD(e,t){let r=Xl(e);if(Jh(r,kD),r.schema!==Ya)throw new Error(`Expected Native transition schema ${Ya}`);let i=Uh(r,t,!0),n=Ei(r.previousState),a=Ei(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Yh(n,a,i,aS(n,a,i.eventData),!0),Kh(n,a,i,!0),{schema:Ya,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function _D(e,t){let r=Xl(e);if(Jh(r,nS),r.schema!==fn)throw new Error(`Expected Native transition schema ${fn}`);if(Yl(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${fn} minimum_runtime_version must be 2`);let n=Yl(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Uh(r,t,!0),o=xi(r.previousState),s=xi(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Yh(o,s,a,aS(o,s,a.eventData),!0),Kh(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:fn,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 AD(e,t){let r=Xl(e);if(r.schema===pn)return{status:"current",journal:RD(r,t)};if(r.schema===Ya)return{status:"migration-required",journal:PD(r,t)};if(r.schema===fn)return{status:"migration-required",journal:_D(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function ID(e,t){let r=Gh(e,t),i=Ne(e,r);await V(i,r);try{let n=await Gr({root:i,file:r,maxBytes:null,label:`Native transition journal ${t}`});return AD(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function oS(e,t){let r=await ID(e,t);if(!r)return null;if(r.status==="migration-required")throw new Wh(t);return r.journal}var TD=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function jD(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function $D(e){return e?e.map(jD).join(" "):null}function OD(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function vt(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function HD(e){return e.map(t=>vt(t,[],null))}function DD(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[vt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(vt("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(vt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),vt("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(vt("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(vt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),vt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Ie(e,t){let r=t.commandArgs===void 0?OD(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?$D(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??HD(t.requiredInputs??[])}}function Ql(e){let r=(e.findings??[]).filter(d=>!_n(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||TD.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return Ie(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Ie(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[vt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Ie(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Ie(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Ie(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Ie(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[vt("summary",["--summary"],"<summary>")]});if(n)return Ie(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 Ie(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[vt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Ie(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Ie(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Ie(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Ie(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"),Ie(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[vt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Ie(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Ie(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=DD(e.state);return Ie(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Uo from"path";K();var sS=8,BD={"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 FD(e){let t=BD[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"}:_n(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 LD(e,t,r){if(!r.path)return null;let i;if(Uo.isAbsolute(r.path)?i=Uo.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=Uo.resolve(ke(e,t.name),...r.path.split(/[\\/]/u)):i=Uo.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!q(e.projectRoot,i))return null;let n=Uo.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function qD(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Xh(e){return e.findings.map(t=>{let r=FD(t.code);return{code:t.code,message:t.message,severity:r.severity,path:LD(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:qD(r.retry,e.state,t.code),repairCommand:r.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,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function Qh(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,sS),truncated:t.length>sS}}oe();import Jn from"path";Ut();K();Ct();Ha();Hi();var Ko={maxArtifacts:128},Un=/^[a-f0-9]{64}$/u;function Zl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function eu(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function ci(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function cS(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Zh(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function MD(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Jn.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=Jn.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function lS(e,t){return Jn.join(Y(e,t),"checkpoints","progress.json")}function Yo(e,t){return Jn.join(Y(e,t),"checkpoint-journal.json")}function uS(e,t,r){if(!Un.test(r))throw new Error("Native checkpoint manifest hash is invalid");return Jn.join(Y(e,t),"checkpoints","manifests",`${r}.json`)}function VD(e){if(!Un.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function em(e,t,r){let i=await Gr({root:e,file:t,maxBytes:null,label:r});return JSON.parse(i.bytes.toString("utf8"))}function WD(e,t){let r=Zl(e,`checkpoint manifest artifact ${t}`);eu(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=MD(ci(r.path,`checkpoint artifact ${t} path`,4096)),n=Ft(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!Un.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:Zh(r.size,`checkpoint artifact ${t} size`)}}function tm(e,t){let r=Zl(e,"Native checkpoint manifest");if(eu(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>Ko.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(WD),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Zh(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function dS(e){return ee(JSON.stringify(tm(e,e.change)))}function pS(e,t){let r=Zl(e,"Native progress checkpoint");if(eu(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=cS(r.previousRevision,"Native checkpoint previousRevision"),a=cS(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ci(r.manifestHash,"Native checkpoint manifestHash",64);if(!Un.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=VD(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ci(r.inputHash,"Native checkpoint inputHash",64);if(!Un.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ci(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Zh(r.artifactCount,"Native checkpoint artifactCount");if(u>Ko.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ci(r.summary,"Native checkpoint summary"),p=ci(r.nextAction,"Native checkpoint nextAction");if(mt(d)!==d||mt(p)!==p)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ci(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:p,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function zD(e,t){let r=Zl(e,"Native checkpoint journal");if(eu(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=Gt(r.previousState),n=Gt(r.nextState),a=pS(r.checkpoint,t),o=tm(r.manifest,t),s=ci(r.inputHash,"Native checkpoint journal inputHash",64),c=ee(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Un.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==dS(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:i,nextState:n,checkpoint:a,manifest:o}}async function GD(e,t,r){let i=Jn.resolve(e.projectRoot,...t.split("/"));if(!q(e.projectRoot,i)||q(e.nativeRoot,i)||q(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=rp(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await hf({root:e.projectRoot,file:i,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function JD(e,t){let r=lS(e,t),i=Ne(e,r);await V(i,r);try{return pS(await em(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function UD(e,t,r){let i=uS(e,t,r),n=Ne(e,i);await V(n,i);let a=await em(n,i,"Native checkpoint manifest"),o=tm(a,t);if(fS(e,o),dS(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function rm(e,t){let r=Yo(e,t),i=Ne(e,r);await V(i,r);try{let n=zD(await em(i,r,"Native checkpoint journal"),t);return fS(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function fS(e,t){for(let r of t.artifacts){let i=rp(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function hS(e){let t;try{t=await JD(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:lS(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await UD(e.paths,e.name,t.manifestHash);let a=ee(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 GD(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:uS(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}var mS=240,vS=8,tu=50;function gS(e){let t=Array.from(e);return t.length<=mS?e:`${t.slice(0,mS-1).join("")}…`}function KD(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function YD(e){let t=[...new Set(e.map(KD))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,vS),reasonCount:e.length,codesTruncated:t.length>vS};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,tu),reasonsTruncated:e.length>tu}}}async function wS(e){let t=null;try{let s=await rm(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Yo(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:Yo(e.paths,e.state.name)}}let r=await hS({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=YD(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Ko.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:gS(r.checkpoint.summary),nextAction:gS(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Ko.maxArtifacts}}import{promises as KB}from"node:fs";import DS from"node:path";de();import yS from"node:path";var XD="comet.native.archive-preflight.v1",QD="comet.native.archive-preflight.v1",ZD="comet.native.archive-operation.v1",eB=/^[a-f0-9]{64}$/u,NS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tB=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function ru(e,t){return e<t?-1:e>t?1:0}function rB(e,t){if(typeof e!="string"||!eB.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kr(e,t){return e===null?null:rB(e,t)}function iB(e,t){let r=yS.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||yS.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function nB(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function aB(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,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.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 oB(e,t){if(!NS.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 r=kr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=kr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=kr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===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:r,actualBaseHash:i,proposedHash:n}}function sB(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:kr(e.contractHash,"Native archive contract hash"),acceptanceHash:kr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:kr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:kr(e.reportHash,"Native archive report hash"),envelopeHash:kr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:kr(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(r=>r===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 cB(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!tB.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(ru);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function lB(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 r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(ru)}function bS(e){if(!NS.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(oB).sort((l,u)=>ru(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 r=t.map(l=>({...l,operationHash:j(ZD,l)})),i=sB(e.evidence),n=aB(e.workspace),a=[...new Set([...cB(e.findingCodes??[]),...lB({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(ru),o=nB(e.revision),s=iB(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:r,evidence:i,workspace:n,findingCodes:a};return{schema:XD,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:j(QD,c)}}at();de();import{createHash as uB}from"node:crypto";import kS from"node:path";var dB="comet.native.conflict-radar.v1",Ke=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}),pB="comet.native.conflict-radar.v1",fB="comet.native.conflict-radar-signals.v1",hB=/^[a-f0-9]{64}$/u,xS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mB=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),vB=new Set(["capability","operation","baseHash"]),gB=new Set(["path","kind"]);function Kn(e,t){return e<t?-1:e>t?1:0}function im(e){return Buffer.byteLength(e,"utf8")}function nm(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function am(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(im(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function wB(e,t){let r=am(e,t,Ke.maxArtifactPathBytes),i=kS.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||kS.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function CS(e,t){if(typeof e!="string"||!hB.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yB(e,t){let r=nm(e,vB,t),i=am(r.capability,`${t} capability`,Ke.maxCapabilityBytes);if(!xS.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:CS(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function NB(e,t){let r=nm(e,gB,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:wB(r.path,`${t} path`),kind:r.kind}}function bB(e,t){let r=nm(e,mB,`Conflict radar change ${t}`),i=am(r.name,`Conflict radar change ${t} name`,Ke.maxNameBytes);if(!xS.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>Ke.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>Ke.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>yB(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>Kn(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>NB(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>Kn(c.path,l.path)||Kn(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:CS(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function kB(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Ke.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(bB).sort((n,a)=>Kn(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)>Ke.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Ke.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function SB(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function EB(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function xB(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function CB(e,t){let r=[],i=uB("sha256").update(`${fB}
|
|
255
|
-
[`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(aa(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<Ke.maxSignalsPerRelationship&&r.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(SB(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=EB(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:xB(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function SS(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function RB(e,t){return SS(e.classification)-SS(t.classification)||Kn(e.left,t.left)||Kn(e.right,t.right)}function ES(e,t,r,i){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:dB,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function RS(e){let t=kB(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(CB(t[s],t[c]));r.sort(RB);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(pB,{changes:t,relationships:i}),a=r.slice(0,Ke.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=ES(t,r,a,n);for(;a.length>0&&im(JSON.stringify(o))>Ke.maxSerializedBytes;)a=a.slice(0,-1),o=ES(t,r,a,n);if(im(JSON.stringify(o))>Ke.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}si();Ct();var PB=4096;async function _B(e,t=Ke.maxChanges){try{let r=await so({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function PS(e,t){let r=await Yt(e,t),[i,n]=await Promise.all([r.implementation_scope?Jl(e,t,r.implementation_scope):null,mr(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function iu(e,t,r={}){let n=(await _B(e,PB)).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 PS(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await PS(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=RS([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"]:[]]}}Qe();K();to();at();si();Cn();Li();zl();import{execFile as LB}from"node:child_process";Gi();ea();dh();import{promisify as qB}from"node:util";Re();oe();_h();K();Lt();import{constants as om,promises as gt}from"node:fs";import Yn from"node:path";var IB=/^[a-f0-9]{64}$/u,TB=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u;function jB(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function nu(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function $B(e,t){let r=Yn.resolve(e),i=Yn.resolve(t);if(!q(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...Yn.relative(r,i).split(Yn.sep).filter(Boolean)]){o&&(a=Yn.join(a,o));let s=await gt.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await gt.realpath(a);if(n.length>0&&!q(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 AS(e){for(let t of e){let r=await gt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!jB(t,r)||await gt.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function OB(e){if(!IB.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function HB(e){let t=TB.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function DB(e,t,r){return Mr(Y(e,t),OB(r))}async function BB(e,t,r){let i=await $B(r,Yn.dirname(e)),n=await gt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");let[a,o]=await Promise.all([gt.realpath(t),gt.realpath(e)]);if(!q(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":om.O_RDONLY|om.O_NOFOLLOW|om.O_NONBLOCK,c=await gt.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(),gt.lstat(e),gt.realpath(e)]);if(await AS(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!nu(n,l)||!nu(l,u))throw new Error("Native check receipt changed while opening");let p=[],f=0,m=Buffer.allocUnsafe(16*1024);for(;;){let b=await c.read(m,0,m.length,null);if(b.bytesRead===0)break;f+=b.bytesRead,p.push(Buffer.from(m.subarray(0,b.bytesRead)))}let[h,v,g]=await Promise.all([c.stat(),gt.lstat(e),gt.realpath(e)]);if(await AS(i),!v.isFile()||v.isSymbolicLink()||g!==o||!q(a,g)||!nu(l,h)||!nu(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(p,f).toString("utf8"))}finally{await c.close()}}async function IS(e,t,r){let i=HB(r),n=Y(e,t),a=DB(e,t,i),o=Ne(e,a);await V(o,a);let s=Ck(await BB(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}si();Re();Hi();var Xo=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Cn();Lo();Li();var a5=64*1024;var o5=3600*1e3;var s5=qB(LB);var MB=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function TS(e,t){let r=[];for(let i of MB){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}async function jS(e){if(e.receipt.kind!=="static-inspection")return null;let t=await IS(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}Lo();var li=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};function VB(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 WB(e){let t=VB(e.bundle.baseline),r=await Rf(e.paths,t,{origin:"explicit",now:e.now});return Sh({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function OS(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await qo(e.paths,e.state.name,e.state.implementation_scope),r=await In({changeDir:ke(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await WB({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function HS(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await OS(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function zB(e){let t=await re({root:ke(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:xy(t.text)}}function GB(e){let{receipt:t,implementationScope:r}=e,i=[],n=kh({baseline:r.baseline,current:r.current,declaredArtifacts:r.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!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function JB(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:Th(e.implementationScope.scope.declaredArtifacts)}}async function $S(e){let t=await Mo(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=TS(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new li([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await jS({paths:e.paths,state:e.state,receipt:t});if(n){let a=GB({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 UB(e){let t=JB({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await $S({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof li)return r.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 i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await $S({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof li)return r.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(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new li(r)}function sm(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function cm(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:sm(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([OS(e),Vn(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:sm(e.state.verification_result,"stale"),envelope:null};let i=await zB({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await UB({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:sm(e.state.verification_result,"invalid"),envelope:null}}}function YB(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function BS(e){try{return await KB.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function XB(e,t){try{return(await re({root:e,ref:t,maxBytes:null})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function QB(e,t,r){let i=wo(e,r.capability);if(!q(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=DS.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await XB(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await re({root:ke(e,t),ref:r.source,maxBytes:null})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function ZB(e,t){return BS(Gh(e,t))}async function lm(e){let t=e.now??new Date,r=await Yt(e.paths,e.name),i=await mr(e.paths,e.name),n=await xe(e.paths.projectRoot),a=YB(r.name,t),o=DS.resolve(e.paths.nativeRoot,...a.split("/"));if(!q(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,p,f]=await Promise.all([Promise.all(r.spec_changes.map(m=>QB(e.paths,r.name,m))),cm({paths:e.paths,state:r,now:t}),iu(e.paths,r.name),bl(e.paths,r.name),GN(e.paths,r.name),ZB(e.paths,r.name),BS(o)]);return bS({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||p,targetRef:a,targetExists:f,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}K();si();Lo();Li();async function eF(e,t){let r=Y(e,t.name),i=await Pn(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await ml(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await _i(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function tF(e,t){let r=await eF(e,t);return{committed:r,latest:Yk(r),history:Kk(r)}}async function FS(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await tF(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}si();Ct();K();function Qo(e,t){try{return za(e,t)}catch{return}}var Zo=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function iF(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function nF(e){return(await Fk(e))?.change??null}function aF(e,t,r=!1,i){return Ql({state:e,archiveReady:t,evidenceRetreat:r}).command}async function oF(e,t){let r=ke(e,t.name),i=[...(await kl(r,t.brief)).findings,...(await tb(e,t)).findings,...await qk(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await ol(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await bN(e,n);a.complete||i.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){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await In({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.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){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await oS(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await qf(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function um(e,t,r){let i=await nF(e)===t,n=await Rp(e,t),a=await ho(e,t),o;try{let y=await Df(e,t);if(y.status==="migration-required"&&y.state)return{name:t,artifacts:Qo(e,t),phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:i,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:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,artifacts:Qo(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,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:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};o=y.state}catch(y){return{name:t,artifacts:Qo(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,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:y.message}}if(n.status!=="available"){let y={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=Xh({paths:e,state:o,findings:[y]}),O=Ql({state:o,findings:C});return{name:o.name,artifacts:Qo(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[y.code],reasonCount:1,codesTruncated:!1},findingSummary:Qh(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...r?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:y.message}:{}}}let s=await wS({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await FS(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let y=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:y,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(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let y=await In({changeDir:ke(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 Q=await Vn(e,o.name,o.verification_evidence);for(let Te of Q.acceptanceTrace.entries)C.set(Te.acceptanceId,Te.status==="failed"?"failed":Te.status==="missing"?"missing":"satisfied")}let O=ky({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),T=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...T?{nextPageCommand:iF(T),nextPageArgs:T}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await iu(e,o.name,{tolerateInvalidSiblings:!0});d.push(...y.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 p=[];try{let y=await mr(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let C=await An({paths:e,identity:y});C.state==="drifted"&&C.code&&p.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await wl({paths:e,identity:y});p.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{p.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let f=[],m=!1;if(o.phase==="verify"){let y=await HS({paths:e,state:o});m=y.freshness!=="fresh",f.push(...y.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,v=[];if(o.phase==="archive")try{h=await lm({paths:e,name:o.name}),v.push(...h.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await oF(e,o),...s.findings,...d,...p,...f,...l,...v].filter((y,C,O)=>O.findIndex(T=>T.code===y.code&&T.path===y.path)===C),b=Xh({paths:e,state:o,findings:g}),k=b.filter(y=>!_n(y.code)),N=o.phase==="archive"&&h?.ready===!0&&k.length===0,x=m||o.phase==="archive"&&(h?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),w=b.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"||y.requiredAction==="return-to-bound-working-directory"||y.requiredAction==="repair-workspace-binding"),S=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",E=b.find(y=>y.severity==="error");return{name:o.name,artifacts:Qo(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:w||S?null:aF(o,N,x,r?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:Qh(b),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Ql({state:o,findings:b,archiveReady:N,evidenceRetreat:x,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:b.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:tu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:b.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...E?{error:E.message}:{}}}async function LS(e){let t;try{t=await mf({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await rF.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>Zo.maxChanges))throw new Error(`Native status exceeds ${Zo.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}K();var pm=ir(Bt(),1);pt();de();at();xt();import{promises as sF}from"node:fs";import dm from"node:path";var au=class extends Error{};async function su(e,t){let r=await re({root:e.nativeRoot,ref:dm.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,pm.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new au("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:ze(i)}}async function MS(e,t,r){let i;try{i=await sF.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return[];throw a}if(i.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let n=[];for(let a of i){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(a.name)?.[1];if(r!==void 0&&o!==void 0&&o!==r)continue;let s=dm.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await su(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof au)continue;let l=a.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(l,`Native archive ${a.name} is unreadable: ${c.message}`)}}return n}function ou(e){return j("comet.native.status-record.v1",e)}function qS(e){let t=dm.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=Je(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=ze((0,pm.parse)(Je(e.projectRoot,["show",`${r}:${t}`])));return ou(i)===ou(e.state)?r:null}catch{return null}}function VS(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=qS(e),i=qS(t);if(!r||!i)return!1;try{return Je(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function WS(e,t){return e.state.archived&&t.state.archived&&ou(e.state)===ou(t.state)}import ZS from"node:path";import{promises as zS}from"node:fs";import cF from"node:path";de();var lF=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),uF=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),dF=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),pF=new Set(["status","summary"]);function cu(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function lu(e,t,r,i=new Set){let n=new Set(Object.keys(e)),a=[...t].filter(s=>!n.has(s)&&!i.has(s)),o=[...n].filter(s=>!t.has(s));return a.length===0&&o.length===0?null:`${r} fields must be exact (missing: ${a.join(", ")||"none"}; unexpected: ${o.join(", ")||"none"})`}function fF(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Mi(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function hF(e,t,r,i){let n=cu(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=lu(n,lF,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=cu(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=lu(o,uF,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=cu(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=lu(c,pF,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let p=cu(d,`Native Supervisor child ${u}`);if(!p)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:f,contractHash:m,...h}=p,v=lu(h,dF,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],b=g.covers.length>0?g.covers.map(N=>({id:N,source:r.acceptance_index?.[N]?.source??"brief.md",text:r.acceptance_index?.[N]?.text??N})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(b)||m!==void 0&&m!==j("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(p.name!==g.name||p.summary!==g.summary||!fF(p.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let k=g.depends_on.length===0?"ready":"pending";if(p.status!==k)return`Native Supervisor child ${g.name} has progressed beyond its initial ${k} status`;if(p.baseCommit!==null||p.candidateCommit!==null||p.verifiedCommit!==null||p.integrationCommit!==null||p.verification!==null||p.blocker!==null||p.projectRoot!==null||p.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if((p.builderFailureCount??0)!==0)return`Native Supervisor child ${g.name} contains Builder failure progress`;if(!Array.isArray(p.checks)||p.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function GS(e){let t=Ao(e.paths,e.state.name),r;try{let c=await zS.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Mi(t,"","Native Supervisor overlay is not a regular file");r=await zS.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Mi(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Mi(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=cF.join(e.paths.changesDir,e.state.name),a;try{a=await Qt({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Mi(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await et(e.paths,e.state.name)}catch(c){return Mi(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Mi(t,r,"Native Supervisor overlay disappeared during inspection");let s=hF(i,e.state,a.contract,o);return s?Mi(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}io();Oi();function Se(e,t,r){return e.language==="zh-CN"?r:t}function mF(e,t,r,i){let n=a=>({required:!1,message:null,suggestedReply:null,agentInstruction:a});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return t?{required:!0,message:Se(e,"Shape is ready. Confirm the complete plan and choose A) Multi-session coordination (recommended), or B) Single-session progression in one reply.","Shape 已整理完成。请确认完整方案,并在同一次回复中选择 A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Se(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:Se(e,"First present the target, scope, key decisions, acceptance criteria, non-goals, child responsibilities and dependencies, and both coordination choices. Execute the matching confirm-shape alternative only when the user explicitly accepts this complete Shape and chooses its mode. Choosing a mode alone, additions, or corrections are not full confirmation; retain that choice and ask only for the missing decision. Do not run --confirmed before full confirmation.","先展示目标、范围、关键决定、验收标准、非目标、各 Child 的职责与依赖,以及两种推进方式。只有用户明确同意当前完整 Shape 并选择推进方式后,才执行对应的 confirm-shape 选项。仅选择推进方式、补充或修改要求都不算完整确认;保留已选方式,只补问缺少的决定。完整确认前不要运行 --confirmed。")}:e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return n(Se(e,"Complete the Shape documents and child plan, resolve blocking questions, then execute prepare-shape-confirmation. Its persisted response combines complete Shape confirmation and coordination choice in one user decision. If the user already chose only a mode, include that --coordination-mode when preparing and ask only for complete Shape confirmation afterward.","完成 Shape 文档和 Child 计划,解决阻塞问题后执行 prepare-shape-confirmation。持久化后的响应会让用户一次确认完整 Shape 并选择推进方式。如果用户已经仅选择了推进方式,准备时附上对应的 --coordination-mode,随后只确认完整 Shape。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return n(Se(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"){let a=i==="confirmed"?Se(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):Se(e,"Check whether the host accepted the startup call and locate the task for the current verifierExecutionRef. If the call has not been made, start the dispatched task once; if the host accepted it, check that same task and let the Verifier submit its startup receipt. A missing receipt alone does not prove failure. If local startup state is unavailable, recover the host task context before deciding whether startup is needed.","先核实宿主是否接受了启动调用,并找到当前 verifierExecutionRef 对应的任务。尚未调用时启动已派发的任务一次;宿主已接受时检查同一个任务,由 Verifier 提交启动回执。仅缺少回执不能证明执行失败。本地启动记录不可用时,先恢复宿主任务上下文,再判断是否需要启动。");return n(`${a} ${Se(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`)}if(e.status==="blocked"&&e.blockers.some(({resolution_action:a})=>a==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}: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 o=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",s=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",c=o?"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:s,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:c,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."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:Se(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements."+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" If accepting, also choose: keep the workspace, merge locally, push the branch, or push and create a PR. You may accept the result and defer the finish choice.":""),"当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" 接受时可一起选择:保留工作区、本地合并、推送分支,或推送并创建 PR;也可以先接受结果,稍后再选择收尾方式。":"")),suggestedReply:Se(e,"Accept the result","接受结果"),agentInstruction:Se(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let a=r?.children.some(({status:l})=>l==="blocked")??!1,o=r?.children.some(({status:l})=>l==="needs-reverify")??!1,s=r?.children.some(({status:l})=>l==="ready"||l==="active")??!1,c=r?.children.some(({status:l,builderFailureCount:u})=>l==="blocked"&&(u??0)>=$l)??!1;return a&&!o&&!s&&!c?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:n(Se(e,"Implement the complete confirmed brief and Spec scope, then review every acceptance ID with its implementation and evidence before handoff. Fill acceptance_review from this audit; derive remaining work from it. Do not submit a partial candidate just to obtain verification feedback. Run focused checks; a separate pre-review is optional. If review is useful, retain the same Reviewer for focused repair follow-ups. Submit the completed candidate for one complete independent verification and release completed helper tasks.","完成已确认的 brief 和 Spec 全部范围,交接前逐项核对所有验收 ID 的实现和证据,填写 acceptance_review,并由这份自查生成剩余工作。不得提交未完成的候选来试探验收反馈。开发期运行相关检查,额外预审为可选项;确需审查时,保留同一个 Reviewer 复核修复及受影响范围。全部完成后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return n(Se(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 vF(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会完成预检,检查通过后按所选方式归档;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 的完整命令,Runtime 会在归档前检查状态和证据;选择 E 时停止,不运行 Archive 命令。按用户的明确选择执行 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run preflight and archive with the selected finish when the checks pass; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative; Runtime checks state and evidence before archiving. For E, stop without running an Archive command. Use the finish explicitly selected by the user."}}function gF(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed","--finish",i,"--expected-state-version",String(e.state_version)],requiredInputs:[],inputOptions:[],description:Se(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Se(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function YS(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Vi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function JS(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function wF(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function US(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function yF(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function NF(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function rr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:YS({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Vi("summary","--summary"),wF(e.name,e.flag)]}}function KS(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:Se(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function bF(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function uu(e){return[rr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),rr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function kF(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:t[n],template:i}}):[r])}function es(e,t,r={}){let i=yF(t)&&e.coordination_mode===void 0,n=mF(e,i,t,r.verifierStartup),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation",...i?["coordination-choice"]:[]],inputOptions:[Vi("summary","--summary")],commandAlternatives:i?Cy.map(s=>{let c=rr({name:`confirm-shape-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...c,commandArgs:[...c.commandArgs,"--coordination-mode",s],requiredInputs:[...c.requiredInputs,"coordination-choice"],inputOptions:[...c.inputOptions,US("coordination-mode","--coordination-mode",[s])]}}):[rr({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Vi("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=rr({name:`accept-result-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...c,commandArgs:[...c.commandArgs,"--finish",s]}}):[],rr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...uu({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Vi("summary","--summary")],commandAlternatives:[rr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),rr({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Vi("summary","--summary")],commandAlternatives:[rr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...uu({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Vi("summary","--summary")],commandAlternatives:uu({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:uu({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?YS({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:"continue",action:"prepare-shape-confirmation",commandArgs:NF({change:e.name,stateVersion:e.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:m})=>m),acceptance_review:e.acceptance.map(({id:m})=>({id:m,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[JS()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=$l)??null,p=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:t.supervisorStateVersion},description:Se(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},f=c&&!l&&!u&&p===null;return{...a,disposition:f?"blocked":"continue",action:"advance-children",commandArgs:f?null:p!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:f?[]:p!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:f?[]:p!==null?[p]:[Vi("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:s})=>s),acceptance_review:e.acceptance.map(({id:s})=>{let c=e.builder_handoff?.acceptance_review?.find(l=>l.id===s);return c?{...c,evidence:[...c.evidence],...e.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=JS();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Se(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:kF([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"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:r.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:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=KS(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>bF(d))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:KS(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[US("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...gF(e)],userCommunication:vF(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[rr({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import XS from"node:path";function QS(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function fm(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:QS(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:QS(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>XS.relative(t.projectRoot,XS.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}K();function eE(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function tE(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function rE(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{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(i=>({kind:"supervisor-child",value:xF(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:CF(i,r)}))]:[]]}function iE(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function SF(e,t){let r=t?.execution;if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running")return;let i=r.verifierStartedAt??null,n=Gf(e,t??null);if(n===void 0)return;let a=n==="confirmed";return{attempt:e.loop.attempt,registeredAt:r.startedAt,confirmedAt:i,confirmation:a?"confirmed":"unconfirmed",...a?{}:{waitingMinutes:Math.max(0,Math.round((Date.now()-Date.parse(r.startedAt))/6e4))}}}function du(e,t,r=we(e.projectRoot)){let i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:ZS.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function hm(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=fm(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...es(t),status:"blocked",disposition:"blocked",action:"archive",requiresUserDecision:!1,commandArgs:i?.result?.recoveryArgs??["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],inputOptions:[],userCommunication:{required:!0,message:o,suggestedReply:null,agentInstruction:"Report the Git blocker and resolve it within the recorded delivery authorization, then retry the recorded Native workspace finish command. Ask the user only when new information or authorization is required; keep delivery pending until it succeeds."},runnerAction:{...es(t).runnerAction,kind:"none"}}:es(t),c=e.details?rE(t,null,[]):[],l=tE(e.cursor,t.state_version,0),u=c.slice(l,l+32),d=l+u.length<c.length?eE(t.state_version,0,l+u.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:za(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:ZS.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:iE(t),unresolvedAcceptanceIds:n.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:a?[...n.blockers,{owner:"runtime",reason:o,acceptance_ids:[],resolution_action:"wait-external"}]:n.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:s,...e.details?{details:{stateVersion:t.state_version,items:u,nextCursor:d,nextPageArgs:d?["comet","native","status",t.name,"--details","--cursor",d,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function EF(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function pu(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function xF(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:pu(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function CF(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:pu(e.summary,t)??""}}async function nE(e){let t=await Uf(e),r=fm(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Io({paths:e.paths,state:t.state}),a=await GS({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await et(e.paths,e.name,{diagnostics:!0}),s=o?{...du(e.paths,t.state,e.gitContext),projectRoot:"."}:du(e.paths,t.state,e.gitContext),c=es(t.state,n,{verifierExecutionRef:zf(t.state,t.local),verifierStartup:Gf(t.state,t.localStatus==="available"?t.local:null),...t.local?{verificationCheckPlans:Bk(t.local,t.local.workspace.projectRoot)}:{}}),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?EF(e.paths,o):[],d=o?(()=>{let m=new Map(n?.children.map(w=>[w.name,w.status])??[]),h=w=>m.get(w.name)??w.status,v=o.children.filter(w=>h(w)==="pending"||h(w)==="ready").length,g=o.children.filter(w=>h(w)==="active"||h(w)==="verified").length,b=o.children.filter(w=>h(w)==="integrated"||h(w)==="archived").length,k=o.children.filter(w=>h(w)==="blocked"||h(w)==="needs-reverify").length,N=o.children.filter(w=>h(w)==="active"||h(w)==="blocked"||h(w)==="needs-reverify").slice(0,16).map(w=>({name:w.name,summary:w.summary,projectRoot:w.task?.projectRoot??w.projectRoot?"<worktree>":null,reason:pu(w.blocker,u)})),x=o.children.flatMap(({blocker:w})=>{let S=pu(w,u);return S?[S]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:g,integrated:b,blocked:k,active:N,agents:{working:o.children.filter(({task:w})=>w!==null).length,completed:b},risks:x,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&b===o.children.length?"parent-verification":v>0?"dispatch-ready-child":k>0?"resolve-blocker":"continue-supervisor"}})():null,p=e.details?(()=>{let m=o?.stateVersion??0,h=rE(t.state,o,u),v=tE(e.cursor,t.state.state_version,m),g=h.slice(v,v+32),b=v+g.length<h.length?eE(t.state.state_version,m,v+g.length):null;return{items:g,nextCursor:b,supervisorStateVersion:m}})():null,f=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,artifacts:za(e.paths,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:iE(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:(()=>{let m=SF(t.state,t.localStatus==="available"?t.local:null);return{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null,...m?{verifierStartup:m}:{}}})(),...n?{childSummary:n.children.reduce((m,h)=>({...m,[h.status]:(m[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:p.supervisorStateVersion}:{},items:p.items,nextCursor:p.nextCursor,nextPageArgs:p.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",p.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}import{accessSync as eX,constants as tX,promises as mm}from"node:fs";import Xn from"node:path";oe();Ji();pt();Bl();Ji();var aE="comet.native.workspace-finish.v1",sE="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",cE=new RegExp(`^${sE}$`,"u"),PF=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,ts=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function oE(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function _F(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==aE||typeof t.name!="string"||!cE.test(t.name)||typeof t.transactionId!="string"||!PF.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Xn.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}if(t.plan!==void 0){let r=t.plan;if(!r||typeof r!="object"||!["keep","merge","push","pull-request"].includes(r.finish)||!["current","branch","worktree"].includes(r.isolation)||![r.changeRoot,r.primaryRoot].every(i=>typeof i=="string"&&Xn.isAbsolute(i))||![r.changeBranch,r.targetBranch].every(i=>typeof i=="string"&&i.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!Xn.isAbsolute(r.targetRoot))||r.remote!==null&&typeof r.remote!="string"||typeof r.commitMessage!="string"||r.mergeMessage!==null&&typeof r.mergeMessage!="string")throw new Error("Native workspace finish journal plan is invalid");oE(r.commitMessage,"commit-message"),r.mergeMessage!==null&&oE(r.mergeMessage,"merge-message")}if(t.createdAt!==void 0&&(typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))))throw new Error("Native workspace finish journal creation identity is invalid");if(t.commit!==void 0){let r=t.commit;if(!r||!ts.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(i=>typeof i=="string"&&i.length>0&&!Xn.posix.isAbsolute(i)&&!Xn.win32.isAbsolute(i)&&!i.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(i=>typeof i=="string")||r.sha!==null&&!ts.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!ts.test(r.target)||!ts.test(r.source)||r.sha!==null&&!ts.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:aE,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt,...t.createdAt===void 0?{}:{createdAt:t.createdAt},...t.plan===void 0?{}:{plan:t.plan},...t.commit===void 0?{}:{commit:t.commit},...t.merge===void 0?{}:{merge:t.merge}}}function AF(e,t){if(!cE.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Xn.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function vm(e,t,r={}){let i=AF(e,t);try{let n=await mm.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=_F(JSON.parse(await mm.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}async function lE(e,t={}){let r;try{r=await mm.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.isFile()&&!n.isSymbolicLink()||n.isDirectory())continue;let a=new RegExp(`^workspace-finish-(${sE})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await vm(e,a[1],t);o&&i.push(o)}return i}function fu(e,t){let r=Wi.normalize(gm(e)),i=Wi.normalize(gm(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function gm(e){let t=Wi.resolve(e);try{return IF.native(t)}catch{return t}}async function uE(e,t){let r=[];for(let i of await LS(e))t!==void 0&&i!==t||r.push({name:i,kind:await ko(e,i)?"portable":"legacy"});return r}async function TF(e,t){let r=Wi.resolve(e),i=cs(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>fu(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>Wi.resolve(l)).sort()){let l=fu(c,r)?r:c,u=gm(l),d=process.platform==="win32"?u.toLowerCase():u;if(s.has(d))continue;s.add(d);let p=await xe(l);if(!p)continue;let f=await Vt(l,p.native.artifact_root);o.push({projectRoot:l,config:p,paths:f,gitContext:na(l,i)??we(l),changes:await uE(f,t)})}if(o.length===0){let c=await xe(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await Vt(e,c.native.artifact_root);o.push({projectRoot:Wi.resolve(e),config:c,paths:l,gitContext:na(e,i)??we(e),changes:await uE(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await MS(c.paths,(u,d)=>c.archiveErrors.push({name:u,message:d}),t),t!==void 0&&(c.archives=c.archives.filter(({state:u})=>u.name===t),c.archiveErrors=c.archiveErrors.filter(({name:u})=>u===t));let l=(u,d)=>c.finishJournalErrors.push({name:u,message:d});c.finishJournals=t?[await vm(c.paths,t,{onError:l})].filter(u=>u!==null):await lE(c.paths,{onError:l})}return o}function dE(e,t){return e.workspace.bindingState==="aligned"?0:fu(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function jF(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournals??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournalErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:d,kind:p})=>{let f=d.finishJournalErrors?.find(({name:m})=>m===n);if(p==="portable")try{let m=await ft(d.paths,n);return{source:d,name:n,kind:p,workspace:du(d.paths,m,d.gitContext),portableStatus:null,inspectionError:f?.message??null,finishJournal:d.finishJournals?.find(({name:h})=>h===n)??null}}catch(m){return{source:d,name:n,kind:p,workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:"The portable state could not be inspected."},portableStatus:null,inspectionError:m instanceof Error?m.message:String(m)}}return{source:d,name:n,kind:p,workspace:a.length>1?await ho(d.paths,n):{projectRoot:d.projectRoot,currentBranch:d.gitContext.currentBranch,isSecondaryWorktree:d.gitContext.isSecondaryWorktree,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:null,finish:null},portableStatus:null,inspectionError:f?.message??null}})),s=t.flatMap(d=>(d.archives??[]).filter(({state:p})=>p.name===n).map(p=>{let f=hm({paths:d.paths,...p,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null});return{source:d,name:n,kind:"portable",workspace:f.workspace,portableStatus:f,inspectionError:d.finishJournalErrors?.find(({name:m})=>m===n)?.message??null,record:p,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null}})),c=t.flatMap(d=>(d.archiveErrors??[]).filter(p=>p.name===n).map(p=>({source:d,error:p})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}let l=t.flatMap(d=>(d.finishJournalErrors??[]).filter(p=>p.name===n).map(p=>({source:d,error:p})))[0];if(l&&o.length===0&&s.length===0){i.push({source:l.source,name:n,kind:"portable",portableStatus:null,inspectionError:l.error.message,workspace:{projectRoot:l.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:l.error.message}});continue}if(o.length===0&&s.length===0){let d=t.find(f=>f.finishJournals?.some(({name:m})=>m===n)),p=d?.finishJournals?.find(({name:f})=>f===n);if(d&&p){i.push({source:d,name:n,kind:"portable",portableStatus:null,inspectionError:p.result?.message??"Native workspace finish journal has no matching active or archived change record.",workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:p.result?.message??"Native workspace finish record is orphaned."},finishJournal:p});continue}}if(s.length>0){for(let p of o)if(p.kind==="portable")try{p.record=await su(p.source.paths,Wi.join(p.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let d=s.find(p=>[...o,...s.filter(f=>!WS(p.record,f.record))].every(f=>f.record&&VS(p.record,f.record)));if(d){i.push(d);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((d,p)=>dE(d,e)-dE(p,e)||d.source.projectRoot.localeCompare(p.source.projectRoot));let u=o.filter(d=>d.workspace.bindingState==="aligned");u.length>1?i.push(...u):u.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(u[0]??o[0])}if(i.length>Zo.maxChanges)throw new Error(`Native status discovery exceeds ${Zo.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}async function $F(e,t,r){let i=await ho(e.source.paths,e.name),n=null;try{n=await UN(e.source.paths,e.name)}catch{}return n?.state?{schema:"comet.native.status.v2",name:e.name,phase:n.state.phase,status:"blocked",migrationRequired:!0,legacySchema:n.schema,workspace:i,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:n.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],message:"This change uses a legacy schema; the first mutating command performs the deterministic migration. Run the listed next command with a migration summary.",runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:um(e.source.paths,e.name,{details:t,...r?{acceptanceCursor:r}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function pE(e,t,r,i){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:[],message:`Run the repair command in the workspace holding this change: ${e.source.paths.projectRoot}`,runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(r)throw new Error("Portable Native status includes the complete acceptance list");if(!t&&e.portableStatus)return e.portableStatus;if(e.record?.state.archived)return hm({paths:e.source.paths,...e.record,finishJournal:e.finishJournal??null,details:t,cursor:i});try{return await nE({paths:e.source.paths,name:e.name,details:t,gitContext:e.source.gitContext,...i?{cursor:i}:{}})}catch(n){if(i)throw n;return pE({...e,inspectionError:n instanceof Error?n.message:String(n)},!1)}}return $F(e,t,r)}async function fE(e){let{sources:t,candidates:r}=await OF(e.projectRoot,e.name);if(r.length===0){let i=t.find(n=>fu(n.projectRoot,e.projectRoot))??t[0];return e.onSelectedRoot?.(i.projectRoot),um(i.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:i.config.native.clarification_mode,maxVerifyFailures:i.config.native.max_verify_failures})}return e.onSelectedRoot?.(r[0].source.projectRoot),pE(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function OF(e,t){let r=await TF(e,t),i=(await jF(e,r)).filter(n=>n.name===t);if(i.length>1)throw new Error(`Native change ${t} has multiple aligned workspace bindings: ${i.map(n=>n.source.projectRoot).join(", ")}`);return{sources:r,candidates:i}}Ma();import rs from"path";import{realpathSync as ZF}from"fs";function hE(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(e),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var Sr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function mE(e){return e?e.command?`${Sr.next} ${e.command}`:e.ask_user?`${Sr.next} ${e.ask_user}`:null:null}function vE(e,t){let r=[e.summary],i=mE(e.next);return i&&r.push(i),e.user_message&&r.push("",Sr.relay,e.user_message),t!==void 0&&r.push("",Sr.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
260
|
+
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Xt(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let i=this.parser.parseInline(r),n=Cb(e);if(n===null)return i;e=n;let a='<a href="'+e+'"';return t&&(a+=' title="'+Xt(t)+'"'),a+=">"+i+"</a>",a}image({href:e,title:t,text:r,tokens:i}){i&&(r=this.parser.parseInline(i,this.parser.textRenderer));let n=Cb(e);if(n===null)return Xt(r);e=n;let a=`<img src="${e}" alt="${Xt(r)}"`;return t&&(a+=` title="${Xt(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Xt(e.text)}},lh=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},It=class th{options;renderer;textRenderer;constructor(t){this.options=t||$i,this.options.renderer=this.options.renderer||new Il,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new lh}static parse(t,r){return new th(r).parse(t)}static parseInline(t,r){return new th(r).parseInline(t)}parse(t){this.renderer.parser=this;let r="";for(let i=0;i<t.length;i++){let n=t[i];if(this.options.extensions?.renderers?.[n.type]){let o=n,s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){r+=s||"";continue}}let a=n;switch(a.type){case"space":{r+=this.renderer.space(a);break}case"hr":{r+=this.renderer.hr(a);break}case"heading":{r+=this.renderer.heading(a);break}case"code":{r+=this.renderer.code(a);break}case"table":{r+=this.renderer.table(a);break}case"blockquote":{r+=this.renderer.blockquote(a);break}case"list":{r+=this.renderer.list(a);break}case"checkbox":{r+=this.renderer.checkbox(a);break}case"html":{r+=this.renderer.html(a);break}case"def":{r+=this.renderer.def(a);break}case"paragraph":{r+=this.renderer.paragraph(a);break}case"text":{r+=this.renderer.text(a);break}default:{let o='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return r}parseInline(t,r=this.renderer){this.renderer.parser=this;let i="";for(let n=0;n<t.length;n++){let a=t[n];if(this.options.extensions?.renderers?.[a.type]){let s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(a.type)){i+=s||"";continue}}let o=a;switch(o.type){case"escape":{i+=r.text(o);break}case"html":{i+=r.html(o);break}case"link":{i+=r.link(o);break}case"image":{i+=r.image(o);break}case"checkbox":{i+=r.checkbox(o);break}case"strong":{i+=r.strong(o);break}case"em":{i+=r.em(o);break}case"codespan":{i+=r.codespan(o);break}case"br":{i+=r.br(o);break}case"del":{i+=r.del(o);break}case"text":{i+=r.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return i}},Co=class{options;block;constructor(e){this.options=e||$i}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?ht.lex:ht.lexInline}provideParser(e=this.block){return e?It.parse:It.parseInline}},eO=class{defaults=rh();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=It;Renderer=Il;TextRenderer=lh;Lexer=ht;Tokenizer=Al;Hooks=Co;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let i of e)switch(r=r.concat(t.call(this,i)),i.type){case"table":{let n=i;for(let a of n.header)r=r.concat(this.walkTokens(a.tokens,t));for(let a of n.rows)for(let o of a)r=r.concat(this.walkTokens(o.tokens,t));break}case"list":{let n=i;r=r.concat(this.walkTokens(n.items,t));break}default:{let n=i;this.defaults.extensions?.childTokens?.[n.type]?this.defaults.extensions.childTokens[n.type].forEach(a=>{let o=n[a].flat(1/0);r=r.concat(this.walkTokens(o,t))}):n.tokens&&(r=r.concat(this.walkTokens(n.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{let i={...r};if(i.async=this.defaults.async||i.async||!1,r.extensions&&(r.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if("renderer"in n){let a=t.renderers[n.name];a?t.renderers[n.name]=function(...o){let s=n.renderer.apply(this,o);return s===!1&&(s=a.apply(this,o)),s}:t.renderers[n.name]=n.renderer}if("tokenizer"in n){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=t[n.level];a?a.unshift(n.tokenizer):t[n.level]=[n.tokenizer],n.start&&(n.level==="block"?t.startBlock?t.startBlock.push(n.start):t.startBlock=[n.start]:n.level==="inline"&&(t.startInline?t.startInline.push(n.start):t.startInline=[n.start]))}"childTokens"in n&&n.childTokens&&(t.childTokens[n.name]=n.childTokens)}),i.extensions=t),r.renderer){let n=this.defaults.renderer||new Il(this.defaults);for(let a in r.renderer){if(!(a in n))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=r.renderer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u||""}}i.renderer=n}if(r.tokenizer){let n=this.defaults.tokenizer||new Al(this.defaults);for(let a in r.tokenizer){if(!(a in n))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=r.tokenizer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.tokenizer=n}if(r.hooks){let n=this.defaults.hooks||new Co;for(let a in r.hooks){if(!(a in n))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=r.hooks[o],c=n[o];Co.passThroughHooks.has(a)?n[o]=l=>{if(this.defaults.async&&Co.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(n,l);return c.call(n,d)})();let u=s.call(n,l);return c.call(n,u)}:n[o]=(...l)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(n,l);return d===!1&&(d=await c.apply(n,l)),d})();let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.hooks=n}if(r.walkTokens){let n=this.defaults.walkTokens,a=r.walkTokens;i.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),n&&(s=s.concat(n.call(this,o))),s}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ht.lex(e,t??this.defaults)}parser(e,t){return It.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let i={...r},n={...this.defaults,...i},a=this.onError(!!n.silent,!!n.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(n.hooks&&(n.hooks.options=n,n.hooks.block=e),n.async)return(async()=>{let o=n.hooks?await n.hooks.preprocess(t):t,s=await(n.hooks?await n.hooks.provideLexer(e):e?ht.lex:ht.lexInline)(o,n),c=n.hooks?await n.hooks.processAllTokens(s):s;n.walkTokens&&await Promise.all(this.walkTokens(c,n.walkTokens));let l=await(n.hooks?await n.hooks.provideParser(e):e?It.parse:It.parseInline)(c,n);return n.hooks?await n.hooks.postprocess(l):l})().catch(a);try{n.hooks&&(t=n.hooks.preprocess(t));let o=(n.hooks?n.hooks.provideLexer(e):e?ht.lex:ht.lexInline)(t,n);n.hooks&&(o=n.hooks.processAllTokens(o)),n.walkTokens&&this.walkTokens(o,n.walkTokens);let s=(n.hooks?n.hooks.provideParser(e):e?It.parse:It.parseInline)(o,n);return n.hooks&&(s=n.hooks.postprocess(s)),s}catch(o){return a(o)}}}onError(e,t){return r=>{if(r.message+=`
|
|
261
|
+
Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+Xt(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},ji=new eO;function X(e,t){return ji.parse(e,t)}X.options=X.setOptions=function(e){return ji.setOptions(e),X.defaults=ji.defaults,Ab(X.defaults),X};X.getDefaults=rh;X.defaults=$i;function tO(...e){return ji.use(...e),X.defaults=ji.defaults,Ab(X.defaults),X}X.use=tO;X.walkTokens=function(e,t){return ji.walkTokens(e,t)};X.parseInline=ji.parseInline;X.Parser=It;X.parser=It.parse;X.Renderer=Il;X.TextRenderer=lh;X.Lexer=ht;X.lexer=ht.lex;X.Tokenizer=Al;X.Hooks=Co;X.parse=X;var dG=X.options,pG=X.setOptions,fG=X.walkTokens,hG=X.parseInline;var mG=It.parse,vG=ht.lex;oe();at();de();var ik=ir(Bt(),1);import{promises as DO}from"node:fs";import Tt from"node:path";pt();at();de();Qe();K();xt();Ol();Ol();Hi();ti();pt();jc();oe();de();Ll();Re();K();Qb();Hi();ti();ql();pt();Qe();ql();Ka();K();var Ml=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function vh(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`}import $O from"node:path";pt();Qe();Re();Hi();ti();async function Vl(e){let t=vh(e.parent),r=nr(e.paths.projectRoot,t);if(!r)return null;let i=nr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Cr(e.paths.projectRoot).map(o=>$O.resolve(o)).find(o=>we(o).currentBranch===t);if(!n)return null;let a=Bl({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return ph(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function gh(e,t){let r=Tt.normalize(Tt.resolve(e)),i=Tt.normalize(Tt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function BO(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function FO(e){let t=BO(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function wh(e){try{let t=await re({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return FO(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function yh(e){return j("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function LO(e){let t=Cr(e.projectRoot);t.some(i=>gh(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Tt.resolve(n)))]){let n=await xe(i);n&&r.push({projectRoot:i,paths:await Vt(i,n.native.artifact_root),parent:gh(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function qO(e,t){let r=Tt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Vr(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function MO(e,t){let r;try{r=await DO.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Tt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Vr(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function VO(e,t,r){let i=Tt.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Tt.sep}`))return null;let n=i.split(Tt.sep).join("/");try{let a=(0,ik.parseDocument)(Je(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ze(a.toJS({mapAsMap:!1}))}catch{return null}}function WO(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function rk(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function jo(e){let t=Tt.join(e.paths.changesDir,e.state.name),r=await wh(t),i=null,n;try{n=await Qt({changeDir:t,validation:Zr(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await et(e.paths,e.state.name,{diagnostics:!0});if(g){let b=Fl(g);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(k=>({...k,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=yh({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Qr){let g=await et(e.paths,e.state.name,{diagnostics:!0});if(!g){let N=e.state.workspace.change_branch??e.state.workspace.target_branch;if(N){let x=await Vl({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});x&&(g=x,await ei(e.paths,x))}}if(g){let N=Fl(g);return e.state.children_contract_hash!==a||n.drift?{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(x=>({...x,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&N.confirmed}}let b=new Map(n.contract.children.map(N=>[N.name,N])),k=n.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:s&&N.depends_on.every(x=>n.contract.children.filter(({name:w})=>w!==N.name).every(({name:w})=>w!==x))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let N of k){if(N.status!=="ready")continue;b.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:k,readyChildren:k.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let c=await LO(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let b=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let k of await MO(g,l)){let N={...k,source:g,committedState:VO(g,k.file,b)};u.set(k.state.name,[...u.get(k.state.name)??[],N])}for(let k of l){let N=await qO(g,k);N&&d.set(k,[...d.get(k)??[],{source:g,state:N}])}}let p=new Map;for(let g of n.contract.children){let b=(u.get(g.name)??[]).find(({source:x,committedState:w})=>x.parent&&w?.name===g.name&&rk(w,o));if(b){p.set(g.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let k=u.get(g.name)?.[0];if(k){p.set(g.name,{kind:"blocked",phase:k.state.phase,projectRoot:k.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let N=d.get(g.name)??[];N.length>1?p.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):N[0]&&p.set(g.name,WO(N[0].state,N[0].source,o))}let f=new Map(n.contract.children.map(g=>[g.name,g])),m=new Map,h=g=>{let b=m.get(g);if(b)return b;let k=f.get(g),x=k.depends_on.map(h).every(({status:O})=>O==="done"),w=p.get(g),S=w?.kind==="active"&&x?k.depends_on.filter(O=>!(u.get(O)??[]).some(({source:T,committedState:Q})=>gh(T.projectRoot,w.projectRoot)&&Q?.name===O&&rk(Q,o))):[],E,y=w?.message??null;w?.kind==="done"?(E=x?"done":"blocked",x||(y=`Native child ${g} was merged before its dependencies`)):w?.kind==="active"?(E=x&&S.length===0?"active":"blocked",x?S.length>0&&(y=`Native child ${g} does not include merged dependencies: ${S.join(", ")}`):y=`Native child ${g} started before its dependencies merged`):w?.kind==="blocked"?E="blocked":(E=s&&x?"ready":"pending",s||(y="Parent Shape confirmation is required"));let C={name:g,summary:k.summary,dependsOn:[...k.depends_on],covers:[...k.covers],status:E,phase:w?.phase??null,projectRoot:w?.projectRoot??null,message:y};return m.set(g,C),C},v=n.contract.children.map(({name:g})=>h(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:v,readyChildren:v.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:v.every(({status:g})=>g==="done")}}Wc();xt();Pi();_o();Hl();Re();nf();Jp();xt();Pi();oe();Ni();_o();K();Ni();si();Qe();var zk=ir(Bt(),1);cr();var xK=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" "));var IK=256*1024;xt();Pi();ti();var uD=fc("en",{compact:!0});Qe();Re();Hi();ti();xt();Pi();pt();jc();de();import zn from"node:path";pt();cr();oe();var G6=8*1024*1024;Ll();Re();Pi();K();function fD(e,t){let r=zn.relative(zn.resolve(e),zn.resolve(t));if(zn.isAbsolute(r)||r===".."||r.startsWith(`..${zn.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(zn.sep).join("/");return Xb(e,i),i}function Kk(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:fD(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}var mY=1024*1024*1024;Re();Hl();_o();ti();Re();ti();Re();gf();var o4=16*1024;async function Yk(e){let t=await Tf(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Ei(t.selection.change),t.selection)}async function Xk(e,t){return Ce(e,`select change ${t}`,async()=>{Ei(t),await Eo(e,t)?await ft(e,t):await Yt(e,t),await jf(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}K();async function Qk(e,t){let r=[],i=Y(e,t.name),n=Mr(i,dt.stateRef),a;try{a=await _n(i)}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")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;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&&r.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")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Mr(i,a.trajectoryRef),s=await WN(e,t.name);if(s.status==="repairable")return r.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}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await Ai(i,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 r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=Mr(i,a.checkpointRef);try{let u=await gl(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}Rn();import $D from"path";import{isDeepStrictEqual as Gh}from"util";oe();Ut();Ka();Re();K();Ct();Di();de();de();var Gn={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var hD=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function mD(e,t){return e<t?-1:e>t?1:0}function vD(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!hD.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(mD)}function Fh(e=[]){return vD(e,"Native repair failed check IDs",Gn.maxFailedCheckIds,!0)}function Zk(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function gD(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Zk(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Zk(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Lh(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(gD(i,a))break;r+=1,i=a}return r}Ul();qi();function qh(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 eS="repairStagnation",rt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},yD=/^[a-f0-9]{64}$/u;var ND=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),bD=["data","runId","sequence","timestamp","type"],tS=["disposition","overrideSummaryHash","signatureHash"],kD=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],rS=12;function Vh(e,t){return e<t?-1:e>t?1:0}function iS(e,t,r){let i=Object.keys(e).sort(Vh);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function Ql(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function Ko(e,t){if(typeof e!="string"||!yD.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function SD(e){if(!Array.isArray(e)||e.length>Gn.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(Vh)}function nS(e){if(typeof e!="string"||e.length===0||e.length>rt.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Mh(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>rt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>rt.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(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>rt.maxTextCharacters&&(!n||e.length>rt.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>rt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>rt.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>Mh(s,t+1,r,`${i}[${c}]`));return}let a=Ql(e,i),o=Object.keys(a);if(o.length>rt.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>rt.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>rt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Mh(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function ED(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 xD(e,t,r){let i=Ql(e,`Native repair trajectory event ${t+1}`);if(iS(i,bD,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(ED(i.timestamp),typeof i.type!="string"||!ND.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(nS(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Mh(i.data,0,n,"Native trajectory event data"),Ql(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Wh(e){let t=Ql(e,"Native repair trajectory projection"),r=Object.keys(t).sort(Vh),i=r.length===tS.length&&r.every((l,u)=>l===tS[u]);i||iS(t,kD,"Native repair trajectory projection");let n=Ko(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:Ko(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(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Ko(t.contractHash,"Native repair trajectory contract hash"),s=SD(t.failedAcceptanceIds),c=Fh(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 CD(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 RD(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??rS;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Lh({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<Gn.warningAtConsecutiveFailures?"continue":a<Gn.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function PD(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??rS;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.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 aS(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>rt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=nS(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 r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=xD(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>rt.maxTotalDataNodes||c>rt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let p=d.data,f=Object.hasOwn(p,"repairScopeHash")?Ko(p.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(p,"implementationScopeHash")?Ko(p.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(p,eS)){if(i?.contractHash===null&&d.type==="state_transitioned"&&p.previousPhase==="build"&&p.nextPhase==="verify"&&(f!==null&&n!==null&&f!==n||f===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=null,n=f,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=Wh(p[eS]);if(CD(p,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(r.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&f!==null&&n!==null&&f!==n&&(r.length=0,o=0),f!==null&&(n=f),RD(m,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(i?.contractHash===null&&f!==null&&n!==null&&f!==n)throw new Error("Native repair override cannot cross implementation scope progress");PD(m,r,i);let h=r.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(i=m,r.length>Gn.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function oS(e){return aS(e).history}function sS(e){let t=aS(e).latestProjection;return t?{...t}:null}Ut();var Jn={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:[]},zh=ee("comet-native-runtime:v3:scope-reopen"),_D=[{skillVersion:"3",skillHash:ee("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ee("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ee("comet-native-runtime:v1")}];function cS(e){return e.skillVersion===Jn.definition.metadata.version&&e.skillHash===zh||_D.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}Ut();Ut();function lS(e){return ee(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}))}Qa();var hS=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],OD=new Set(hS),mS=new Set([...hS,"minimum_runtime_version","revision"]),HD=new Set([...mS,"operation"]),Jh=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),DD=new Set([...Jh,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Uh=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Yh(e,t){return $D.join(Y(e,t),"transition.json")}function eu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Xh(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function Zl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Kh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!DD.has(u)),a=[...Jh].find(u=>!Object.hasOwn(r,u)),o=Jh.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(qh(r.summary,"Native transition journal event summary"),mt(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.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(r.noCodeReason!==null&&(qh(r.noCodeReason,"Native transition journal event no-code reason"),mt(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?Wh(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function BD(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return Kh({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Kh(e,t)}function Qh(e,t,r=!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 i=r?BD(e.eventData,e.evidenceHash):Kh(e.eventData,e.evidenceHash),n=Of(e.nextRun),a=e.previousRun===null?null:Of(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function uS(e,t,r=!1){if(e.skill!==Jn.definition.metadata.name||(r?!cS(e):e.skillVersion!==Jn.definition.metadata.version||e.skillHash!==zh)||e.orchestration!==Jn.definition.orchestration.mode||e.pendingRef!==dt.pendingRef||e.trajectoryRef!==dt.trajectoryRef||e.contextRef!==dt.contextRef||e.artifactsRef!==dt.artifactsRef||e.checkpointRef!==dt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function dS(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 pS(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 Zh(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(uS(o,"next Run",i||a!==null),pS(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(uS(a,"previous Run",!0),pS(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(!Gh(dS(a),dS(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function FD(e,t,r){return ee(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function vS(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function fS(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function em(e,t,r,i,n=!1){let a=r.eventData,o=fS(e),s=fS(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(i==="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&&Gh(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(i==="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&&Gh(e.spec_changes,t.spec_changes),l=lS({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||r.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(i==="spec-rebase"){let c=FD(e.name,a.summary,t.spec_changes),l=ee(`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&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.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 LD(e,t){let r=eu(e);if(Xh(r,HD),r.schema!==fn)throw new Error(`Expected Native transition schema ${fn}`);let i=Zl(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${fn} minimum_runtime_version must be ${3}`);let n=Zl(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Qh(r,t),o=Gt(r.previousState),s=Gt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(em(o,s,a,r.operation),Zh(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:fn,minimum_runtime_version:3,revision:n,operation:r.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 qD(e,t){let r=eu(e);if(Xh(r,OD),r.schema!==Xa)throw new Error(`Expected Native transition schema ${Xa}`);let i=Qh(r,t,!0),n=xi(r.previousState),a=xi(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return em(n,a,i,vS(n,a,i.eventData),!0),Zh(n,a,i,!0),{schema:Xa,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function MD(e,t){let r=eu(e);if(Xh(r,mS),r.schema!==hn)throw new Error(`Expected Native transition schema ${hn}`);if(Zl(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${hn} minimum_runtime_version must be 2`);let n=Zl(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Qh(r,t,!0),o=Ci(r.previousState),s=Ci(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(em(o,s,a,vS(o,s,a.eventData),!0),Zh(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:hn,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 VD(e,t){let r=eu(e);if(r.schema===fn)return{status:"current",journal:LD(r,t)};if(r.schema===Xa)return{status:"migration-required",journal:qD(r,t)};if(r.schema===hn)return{status:"migration-required",journal:MD(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function WD(e,t){let r=Yh(e,t),i=Ne(e,r);await V(i,r);try{let n=await Gr({root:i,file:r,maxBytes:null,label:`Native transition journal ${t}`});return VD(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function gS(e,t){let r=await WD(e,t);if(!r)return null;if(r.status==="migration-required")throw new Uh(t);return r.journal}var zD=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function GD(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function JD(e){return e?e.map(GD).join(" "):null}function UD(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function vt(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function KD(e){return e.map(t=>vt(t,[],null))}function YD(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[vt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(vt("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(vt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),vt("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(vt("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(vt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),vt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Ie(e,t){let r=t.commandArgs===void 0?UD(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?JD(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??KD(t.requiredInputs??[])}}function tu(e){let r=(e.findings??[]).filter(d=>!An(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||zD.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return Ie(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Ie(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[vt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Ie(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Ie(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Ie(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Ie(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[vt("summary",["--summary"],"<summary>")]});if(n)return Ie(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 Ie(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[vt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Ie(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Ie(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Ie(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Ie(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"),Ie(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[vt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Ie(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Ie(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=YD(e.state);return Ie(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Yo from"path";K();var wS=8,XD={"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 QD(e){let t=XD[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"}:An(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 ZD(e,t,r){if(!r.path)return null;let i;if(Yo.isAbsolute(r.path)?i=Yo.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=Yo.resolve(ke(e,t.name),...r.path.split(/[\\/]/u)):i=Yo.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!q(e.projectRoot,i))return null;let n=Yo.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function eB(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function tm(e){return e.findings.map(t=>{let r=QD(t.code);return{code:t.code,message:t.message,severity:r.severity,path:ZD(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:eB(r.retry,e.state,t.code),repairCommand:r.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,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function rm(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,wS),truncated:t.length>wS}}oe();import Un from"path";Ut();K();Ct();Da();Di();var Xo={maxArtifacts:128},Kn=/^[a-f0-9]{64}$/u;function ru(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function iu(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function ci(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function yS(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function im(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function tB(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Un.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=Un.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function NS(e,t){return Un.join(Y(e,t),"checkpoints","progress.json")}function Qo(e,t){return Un.join(Y(e,t),"checkpoint-journal.json")}function bS(e,t,r){if(!Kn.test(r))throw new Error("Native checkpoint manifest hash is invalid");return Un.join(Y(e,t),"checkpoints","manifests",`${r}.json`)}function rB(e){if(!Kn.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function nm(e,t,r){let i=await Gr({root:e,file:t,maxBytes:null,label:r});return JSON.parse(i.bytes.toString("utf8"))}function iB(e,t){let r=ru(e,`checkpoint manifest artifact ${t}`);iu(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=tB(ci(r.path,`checkpoint artifact ${t} path`,4096)),n=Ft(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!Kn.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:im(r.size,`checkpoint artifact ${t} size`)}}function am(e,t){let r=ru(e,"Native checkpoint manifest");if(iu(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>Xo.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(iB),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=im(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function kS(e){return ee(JSON.stringify(am(e,e.change)))}function SS(e,t){let r=ru(e,"Native progress checkpoint");if(iu(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=yS(r.previousRevision,"Native checkpoint previousRevision"),a=yS(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ci(r.manifestHash,"Native checkpoint manifestHash",64);if(!Kn.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=rB(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ci(r.inputHash,"Native checkpoint inputHash",64);if(!Kn.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ci(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=im(r.artifactCount,"Native checkpoint artifactCount");if(u>Xo.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ci(r.summary,"Native checkpoint summary"),p=ci(r.nextAction,"Native checkpoint nextAction");if(mt(d)!==d||mt(p)!==p)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ci(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:p,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function nB(e,t){let r=ru(e,"Native checkpoint journal");if(iu(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=Gt(r.previousState),n=Gt(r.nextState),a=SS(r.checkpoint,t),o=am(r.manifest,t),s=ci(r.inputHash,"Native checkpoint journal inputHash",64),c=ee(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Kn.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==kS(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:i,nextState:n,checkpoint:a,manifest:o}}async function aB(e,t,r){let i=Un.resolve(e.projectRoot,...t.split("/"));if(!q(e.projectRoot,i)||q(e.nativeRoot,i)||q(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=ap(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await wf({root:e.projectRoot,file:i,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function oB(e,t){let r=NS(e,t),i=Ne(e,r);await V(i,r);try{return SS(await nm(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function sB(e,t,r){let i=bS(e,t,r),n=Ne(e,i);await V(n,i);let a=await nm(n,i,"Native checkpoint manifest"),o=am(a,t);if(ES(e,o),kS(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function om(e,t){let r=Qo(e,t),i=Ne(e,r);await V(i,r);try{let n=nB(await nm(i,r,"Native checkpoint journal"),t);return ES(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function ES(e,t){for(let r of t.artifacts){let i=ap(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function xS(e){let t;try{t=await oB(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:NS(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await sB(e.paths,e.name,t.manifestHash);let a=ee(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 aB(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:bS(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}var CS=240,RS=8,nu=50;function PS(e){let t=Array.from(e);return t.length<=CS?e:`${t.slice(0,CS-1).join("")}…`}function cB(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function lB(e){let t=[...new Set(e.map(cB))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,RS),reasonCount:e.length,codesTruncated:t.length>RS};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,nu),reasonsTruncated:e.length>nu}}}async function _S(e){let t=null;try{let s=await om(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Qo(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:Qo(e.paths,e.state.name)}}let r=await xS({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=lB(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Xo.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:PS(r.checkpoint.summary),nextAction:PS(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Xo.maxArtifacts}}import{promises as cF}from"node:fs";import US from"node:path";de();import AS from"node:path";var uB="comet.native.archive-preflight.v1",dB="comet.native.archive-preflight.v1",pB="comet.native.archive-operation.v1",fB=/^[a-f0-9]{64}$/u,IS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hB=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function au(e,t){return e<t?-1:e>t?1:0}function mB(e,t){if(typeof e!="string"||!fB.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kr(e,t){return e===null?null:mB(e,t)}function vB(e,t){let r=AS.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||AS.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function gB(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function wB(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,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.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 yB(e,t){if(!IS.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 r=kr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=kr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=kr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===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:r,actualBaseHash:i,proposedHash:n}}function NB(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:kr(e.contractHash,"Native archive contract hash"),acceptanceHash:kr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:kr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:kr(e.reportHash,"Native archive report hash"),envelopeHash:kr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:kr(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(r=>r===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 bB(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!hB.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(au);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function kB(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 r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(au)}function TS(e){if(!IS.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(yB).sort((l,u)=>au(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 r=t.map(l=>({...l,operationHash:j(pB,l)})),i=NB(e.evidence),n=wB(e.workspace),a=[...new Set([...bB(e.findingCodes??[]),...kB({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(au),o=gB(e.revision),s=vB(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:r,evidence:i,workspace:n,findingCodes:a};return{schema:uB,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:j(dB,c)}}at();de();import{createHash as SB}from"node:crypto";import jS from"node:path";var EB="comet.native.conflict-radar.v1",Ke=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}),xB="comet.native.conflict-radar.v1",CB="comet.native.conflict-radar-signals.v1",RB=/^[a-f0-9]{64}$/u,HS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,PB=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),_B=new Set(["capability","operation","baseHash"]),AB=new Set(["path","kind"]);function Yn(e,t){return e<t?-1:e>t?1:0}function sm(e){return Buffer.byteLength(e,"utf8")}function cm(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function lm(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(sm(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function IB(e,t){let r=lm(e,t,Ke.maxArtifactPathBytes),i=jS.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||jS.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function DS(e,t){if(typeof e!="string"||!RB.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function TB(e,t){let r=cm(e,_B,t),i=lm(r.capability,`${t} capability`,Ke.maxCapabilityBytes);if(!HS.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:DS(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function jB(e,t){let r=cm(e,AB,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:IB(r.path,`${t} path`),kind:r.kind}}function $B(e,t){let r=cm(e,PB,`Conflict radar change ${t}`),i=lm(r.name,`Conflict radar change ${t} name`,Ke.maxNameBytes);if(!HS.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>Ke.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>Ke.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>TB(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>Yn(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>jB(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>Yn(c.path,l.path)||Yn(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:DS(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function OB(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Ke.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map($B).sort((n,a)=>Yn(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)>Ke.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Ke.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function HB(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function DB(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function BB(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function FB(e,t){let r=[],i=SB("sha256").update(`${CB}
|
|
262
|
+
[`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(oa(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<Ke.maxSignalsPerRelationship&&r.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(HB(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=DB(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:BB(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function $S(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function LB(e,t){return $S(e.classification)-$S(t.classification)||Yn(e.left,t.left)||Yn(e.right,t.right)}function OS(e,t,r,i){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:EB,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function BS(e){let t=OB(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(FB(t[s],t[c]));r.sort(LB);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(xB,{changes:t,relationships:i}),a=r.slice(0,Ke.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=OS(t,r,a,n);for(;a.length>0&&sm(JSON.stringify(o))>Ke.maxSerializedBytes;)a=a.slice(0,-1),o=OS(t,r,a,n);if(sm(JSON.stringify(o))>Ke.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}si();Ct();var qB=4096;async function MB(e,t=Ke.maxChanges){try{let r=await co({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function FS(e,t){let r=await Yt(e,t),[i,n]=await Promise.all([r.implementation_scope?Yl(e,t,r.implementation_scope):null,mr(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function ou(e,t,r={}){let n=(await MB(e,qB)).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 FS(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await FS(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=BS([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"]:[]]}}Qe();K();ro();at();si();Rn();qi();Ul();import{execFile as ZB}from"node:child_process";Ji();ta();mh();import{promisify as eF}from"node:util";Re();oe();jh();K();Lt();import{constants as um,promises as gt}from"node:fs";import Xn from"node:path";var WB=/^[a-f0-9]{64}$/u,zB=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u;function GB(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function su(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function JB(e,t){let r=Xn.resolve(e),i=Xn.resolve(t);if(!q(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...Xn.relative(r,i).split(Xn.sep).filter(Boolean)]){o&&(a=Xn.join(a,o));let s=await gt.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await gt.realpath(a);if(n.length>0&&!q(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 qS(e){for(let t of e){let r=await gt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!GB(t,r)||await gt.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function UB(e){if(!WB.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function KB(e){let t=zB.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function YB(e,t,r){return Mr(Y(e,t),UB(r))}async function XB(e,t,r){let i=await JB(r,Xn.dirname(e)),n=await gt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");let[a,o]=await Promise.all([gt.realpath(t),gt.realpath(e)]);if(!q(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":um.O_RDONLY|um.O_NOFOLLOW|um.O_NONBLOCK,c=await gt.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(),gt.lstat(e),gt.realpath(e)]);if(await qS(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!su(n,l)||!su(l,u))throw new Error("Native check receipt changed while opening");let p=[],f=0,m=Buffer.allocUnsafe(16*1024);for(;;){let b=await c.read(m,0,m.length,null);if(b.bytesRead===0)break;f+=b.bytesRead,p.push(Buffer.from(m.subarray(0,b.bytesRead)))}let[h,v,g]=await Promise.all([c.stat(),gt.lstat(e),gt.realpath(e)]);if(await qS(i),!v.isFile()||v.isSymbolicLink()||g!==o||!q(a,g)||!su(l,h)||!su(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(p,f).toString("utf8"))}finally{await c.close()}}async function MS(e,t,r){let i=KB(r),n=Y(e,t),a=YB(e,t,i),o=Ne(e,a);await V(o,a);let s=Dk(await XB(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}si();Re();Di();var Zo=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Rn();Mo();qi();var w5=64*1024;var y5=3600*1e3;var N5=eF(ZB);var tF=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function VS(e,t){let r=[];for(let i of tF){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}async function WS(e){if(e.receipt.kind!=="static-inspection")return null;let t=await MS(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}Mo();var li=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};function rF(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 iF(e){let t=rF(e.bundle.baseline),r=await If(e.paths,t,{origin:"explicit",now:e.now});return Rh({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function GS(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Vo(e.paths,e.state.name,e.state.implementation_scope),r=await Tn({changeDir:ke(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await iF({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function JS(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await GS(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function nF(e){let t=await re({root:ke(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Oy(t.text)}}function aF(e){let{receipt:t,implementationScope:r}=e,i=[],n=Ch({baseline:r.baseline,current:r.current,declaredArtifacts:r.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!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function oF(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:Hh(e.implementationScope.scope.declaredArtifacts)}}async function zS(e){let t=await Wo(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=VS(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new li([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await WS({paths:e.paths,state:e.state,receipt:t});if(n){let a=aF({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 sF(e){let t=oF({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await zS({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof li)return r.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 i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await zS({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof li)return r.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(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new li(r)}function dm(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function pm(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:dm(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([GS(e),Wn(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:dm(e.state.verification_result,"stale"),envelope:null};let i=await nF({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await sF({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:dm(e.state.verification_result,"invalid"),envelope:null}}}function lF(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function KS(e){try{return await cF.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function uF(e,t){try{return(await re({root:e,ref:t,maxBytes:null})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function dF(e,t,r){let i=No(e,r.capability);if(!q(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=US.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await uF(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await re({root:ke(e,t),ref:r.source,maxBytes:null})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function pF(e,t){return KS(Yh(e,t))}async function fm(e){let t=e.now??new Date,r=await Yt(e.paths,e.name),i=await mr(e.paths,e.name),n=await xe(e.paths.projectRoot),a=lF(r.name,t),o=US.resolve(e.paths.nativeRoot,...a.split("/"));if(!q(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,p,f]=await Promise.all([Promise.all(r.spec_changes.map(m=>dF(e.paths,r.name,m))),pm({paths:e.paths,state:r,now:t}),ou(e.paths,r.name),Sl(e.paths,r.name),rb(e.paths,r.name),pF(e.paths,r.name),KS(o)]);return TS({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||p,targetRef:a,targetExists:f,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}K();si();Mo();qi();async function fF(e,t){let r=Y(e,t.name),i=await _n(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await gl(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Ai(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function hF(e,t){let r=await fF(e,t);return{committed:r,latest:sS(r),history:oS(r)}}async function YS(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await hF(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}si();Ct();K();function es(e,t){try{return Ga(e,t)}catch{return}}var ts=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function vF(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function gF(e){return(await Yk(e))?.change??null}function wF(e,t,r=!1,i){return tu({state:e,archiveReady:t,evidenceRetreat:r}).command}async function yF(e,t){let r=ke(e,t.name),i=[...(await xl(r,t.brief)).findings,...(await pb(e,t)).findings,...await Qk(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await cl(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await IN(e,n);a.complete||i.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){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await Tn({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.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){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await gS(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await zf(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function hm(e,t,r){let i=await gF(e)===t,n=await Ip(e,t),a=await mo(e,t),o;try{let y=await qf(e,t);if(y.status==="migration-required"&&y.state)return{name:t,artifacts:es(e,t),phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:i,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:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,artifacts:es(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,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:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};o=y.state}catch(y){return{name:t,artifacts:es(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,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:y.message}}if(n.status!=="available"){let y={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=tm({paths:e,state:o,findings:[y]}),O=tu({state:o,findings:C});return{name:o.name,artifacts:es(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[y.code],reasonCount:1,codesTruncated:!1},findingSummary:rm(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...r?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:y.message}:{}}}let s=await _S({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await YS(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let y=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:y,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(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let y=await Tn({changeDir:ke(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 Q=await Wn(e,o.name,o.verification_evidence);for(let Te of Q.acceptanceTrace.entries)C.set(Te.acceptanceId,Te.status==="failed"?"failed":Te.status==="missing"?"missing":"satisfied")}let O=Ty({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),T=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...T?{nextPageCommand:vF(T),nextPageArgs:T}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await ou(e,o.name,{tolerateInvalidSiblings:!0});d.push(...y.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 p=[];try{let y=await mr(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let C=await In({paths:e,identity:y});C.state==="drifted"&&C.code&&p.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await Nl({paths:e,identity:y});p.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{p.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let f=[],m=!1;if(o.phase==="verify"){let y=await JS({paths:e,state:o});m=y.freshness!=="fresh",f.push(...y.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,v=[];if(o.phase==="archive")try{h=await fm({paths:e,name:o.name}),v.push(...h.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await yF(e,o),...s.findings,...d,...p,...f,...l,...v].filter((y,C,O)=>O.findIndex(T=>T.code===y.code&&T.path===y.path)===C),b=tm({paths:e,state:o,findings:g}),k=b.filter(y=>!An(y.code)),N=o.phase==="archive"&&h?.ready===!0&&k.length===0,x=m||o.phase==="archive"&&(h?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),w=b.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"||y.requiredAction==="return-to-bound-working-directory"||y.requiredAction==="repair-workspace-binding"),S=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",E=b.find(y=>y.severity==="error");return{name:o.name,artifacts:es(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:w||S?null:wF(o,N,x,r?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:rm(b),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:tu({state:o,findings:b,archiveReady:N,evidenceRetreat:x,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:b.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:nu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:b.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...E?{error:E.message}:{}}}async function XS(e){let t;try{t=await yf({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await mF.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>ts.maxChanges))throw new Error(`Native status exceeds ${ts.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}K();var vm=ir(Bt(),1);pt();de();at();xt();import{promises as NF}from"node:fs";import mm from"node:path";var cu=class extends Error{};async function uu(e,t){let r=await re({root:e.nativeRoot,ref:mm.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,vm.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new cu("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:ze(i)}}async function ZS(e,t,r){let i;try{i=await NF.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return[];throw a}if(i.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let n=[];for(let a of i){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(a.name)?.[1];if(r!==void 0&&o!==void 0&&o!==r)continue;let s=mm.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await uu(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof cu)continue;let l=a.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(l,`Native archive ${a.name} is unreadable: ${c.message}`)}}return n}function lu(e){return j("comet.native.status-record.v1",e)}function QS(e){let t=mm.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=Je(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=ze((0,vm.parse)(Je(e.projectRoot,["show",`${r}:${t}`])));return lu(i)===lu(e.state)?r:null}catch{return null}}function eE(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=QS(e),i=QS(t);if(!r||!i)return!1;try{return Je(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function tE(e,t){return e.state.archived&&t.state.archived&&lu(e.state)===lu(t.state)}import uE from"node:path";import{promises as rE}from"node:fs";import bF from"node:path";de();var kF=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),SF=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),EF=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),xF=new Set(["status","summary"]);function du(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function pu(e,t,r,i=new Set){let n=new Set(Object.keys(e)),a=[...t].filter(s=>!n.has(s)&&!i.has(s)),o=[...n].filter(s=>!t.has(s));return a.length===0&&o.length===0?null:`${r} fields must be exact (missing: ${a.join(", ")||"none"}; unexpected: ${o.join(", ")||"none"})`}function CF(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Vi(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function RF(e,t,r,i){let n=du(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=pu(n,kF,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=du(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=pu(o,SF,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=du(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=pu(c,xF,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let p=du(d,`Native Supervisor child ${u}`);if(!p)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:f,contractHash:m,...h}=p,v=pu(h,EF,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],b=g.covers.length>0?g.covers.map(N=>({id:N,source:r.acceptance_index?.[N]?.source??"brief.md",text:r.acceptance_index?.[N]?.text??N})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(b)||m!==void 0&&m!==j("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(p.name!==g.name||p.summary!==g.summary||!CF(p.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let k=g.depends_on.length===0?"ready":"pending";if(p.status!==k)return`Native Supervisor child ${g.name} has progressed beyond its initial ${k} status`;if(p.baseCommit!==null||p.candidateCommit!==null||p.verifiedCommit!==null||p.integrationCommit!==null||p.verification!==null||p.blocker!==null||p.projectRoot!==null||p.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if((p.builderFailureCount??0)!==0)return`Native Supervisor child ${g.name} contains Builder failure progress`;if(!Array.isArray(p.checks)||p.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function iE(e){let t=To(e.paths,e.state.name),r;try{let c=await rE.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Vi(t,"","Native Supervisor overlay is not a regular file");r=await rE.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Vi(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Vi(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=bF.join(e.paths.changesDir,e.state.name),a;try{a=await Qt({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Vi(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await et(e.paths,e.state.name)}catch(c){return Vi(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Vi(t,r,"Native Supervisor overlay disappeared during inspection");let s=RF(i,e.state,a.contract,o);return s?Vi(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}no();Hi();function Se(e,t,r){return e.language==="zh-CN"?r:t}function PF(e,t,r,i){let n=a=>({required:!1,message:null,suggestedReply:null,agentInstruction:a});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return t?{required:!0,message:Se(e,"Shape is ready. Confirm the complete plan and choose A) Multi-session coordination (recommended), or B) Single-session progression in one reply.","Shape 已整理完成。请确认完整方案,并在同一次回复中选择 A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Se(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:Se(e,"First present the target, scope, key decisions, acceptance criteria, non-goals, child responsibilities and dependencies, and both coordination choices. Execute the matching confirm-shape alternative only when the user explicitly accepts this complete Shape and chooses its mode. Choosing a mode alone, additions, or corrections are not full confirmation; retain that choice and ask only for the missing decision. Do not run --confirmed before full confirmation.","先展示目标、范围、关键决定、验收标准、非目标、各 Child 的职责与依赖,以及两种推进方式。只有用户明确同意当前完整 Shape 并选择推进方式后,才执行对应的 confirm-shape 选项。仅选择推进方式、补充或修改要求都不算完整确认;保留已选方式,只补问缺少的决定。完整确认前不要运行 --confirmed。")}:e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return n(Se(e,"Complete the Shape documents and child plan, resolve blocking questions, then execute prepare-shape-confirmation. Its persisted response combines complete Shape confirmation and coordination choice in one user decision. If the user already chose only a mode, include that --coordination-mode when preparing and ask only for complete Shape confirmation afterward.","完成 Shape 文档和 Child 计划,解决阻塞问题后执行 prepare-shape-confirmation。持久化后的响应会让用户一次确认完整 Shape 并选择推进方式。如果用户已经仅选择了推进方式,准备时附上对应的 --coordination-mode,随后只确认完整 Shape。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return n(Se(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"){let a=i==="confirmed"?Se(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):Se(e,"Check whether the host accepted the startup call and locate the task for the current verifierExecutionRef. If the call has not been made, start the dispatched task once; if the host accepted it, check that same task and let the Verifier submit its startup receipt. A missing receipt alone does not prove failure. If local startup state is unavailable, recover the host task context before deciding whether startup is needed.","先核实宿主是否接受了启动调用,并找到当前 verifierExecutionRef 对应的任务。尚未调用时启动已派发的任务一次;宿主已接受时检查同一个任务,由 Verifier 提交启动回执。仅缺少回执不能证明执行失败。本地启动记录不可用时,先恢复宿主任务上下文,再判断是否需要启动。");return n(`${a} ${Se(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`)}if(e.status==="blocked"&&e.blockers.some(({resolution_action:a})=>a==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}: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 o=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",s=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",c=o?"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:s,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:c,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."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:Se(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements."+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" If accepting, also choose: keep the workspace, merge locally, push the branch, or push and create a PR. You may accept the result and defer the finish choice.":""),"当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" 接受时可一起选择:保留工作区、本地合并、推送分支,或推送并创建 PR;也可以先接受结果,稍后再选择收尾方式。":"")),suggestedReply:Se(e,"Accept the result","接受结果"),agentInstruction:Se(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let a=r?.children.some(({status:l})=>l==="blocked")??!1,o=r?.children.some(({status:l})=>l==="needs-reverify")??!1,s=r?.children.some(({status:l})=>l==="ready"||l==="active")??!1,c=r?.children.some(({status:l,builderFailureCount:u})=>l==="blocked"&&(u??0)>=Dl)??!1;return a&&!o&&!s&&!c?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:n(Se(e,"Implement the complete confirmed brief and Spec scope, then review every acceptance ID with its implementation and evidence before handoff. Fill acceptance_review from this audit; derive remaining work from it. Do not submit a partial candidate just to obtain verification feedback. Run focused checks; a separate pre-review is optional. If review is useful, retain the same Reviewer for focused repair follow-ups. Submit the completed candidate for one complete independent verification and release completed helper tasks.","完成已确认的 brief 和 Spec 全部范围,交接前逐项核对所有验收 ID 的实现和证据,填写 acceptance_review,并由这份自查生成剩余工作。不得提交未完成的候选来试探验收反馈。开发期运行相关检查,额外预审为可选项;确需审查时,保留同一个 Reviewer 复核修复及受影响范围。全部完成后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return n(Se(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 _F(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会完成预检,检查通过后按所选方式归档;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 的完整命令,Runtime 会在归档前检查状态和证据;选择 E 时停止,不运行 Archive 命令。按用户的明确选择执行 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run preflight and archive with the selected finish when the checks pass; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative; Runtime checks state and evidence before archiving. For E, stop without running an Archive command. Use the finish explicitly selected by the user."}}function AF(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed","--finish",i,"--expected-state-version",String(e.state_version)],requiredInputs:[],inputOptions:[],description:Se(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Se(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function sE(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Wi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function nE(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function IF(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function aE(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function TF(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function jF(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function rr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:sE({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Wi("summary","--summary"),IF(e.name,e.flag)]}}function oE(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:Se(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function $F(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function fu(e){return[rr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),rr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function OF(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:t[n],template:i}}):[r])}function rs(e,t,r={}){let i=TF(t)&&e.coordination_mode===void 0,n=PF(e,i,t,r.verifierStartup),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation",...i?["coordination-choice"]:[]],inputOptions:[Wi("summary","--summary")],commandAlternatives:i?Hy.map(s=>{let c=rr({name:`confirm-shape-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...c,commandArgs:[...c.commandArgs,"--coordination-mode",s],requiredInputs:[...c.requiredInputs,"coordination-choice"],inputOptions:[...c.inputOptions,aE("coordination-mode","--coordination-mode",[s])]}}):[rr({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Wi("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=rr({name:`accept-result-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...c,commandArgs:[...c.commandArgs,"--finish",s]}}):[],rr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...fu({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Wi("summary","--summary")],commandAlternatives:[rr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),rr({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Wi("summary","--summary")],commandAlternatives:[rr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...fu({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Wi("summary","--summary")],commandAlternatives:fu({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:fu({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?sE({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:"continue",action:"prepare-shape-confirmation",commandArgs:jF({change:e.name,stateVersion:e.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:m})=>m),acceptance_review:e.acceptance.map(({id:m})=>({id:m,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[nE()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=Dl)??null,p=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:t.supervisorStateVersion},description:Se(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},f=c&&!l&&!u&&p===null;return{...a,disposition:f?"blocked":"continue",action:"advance-children",commandArgs:f?null:p!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:f?[]:p!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:f?[]:p!==null?[p]:[Wi("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:s})=>s),acceptance_review:e.acceptance.map(({id:s})=>{let c=e.builder_handoff?.acceptance_review?.find(l=>l.id===s);return c?{...c,evidence:[...c.evidence],...e.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=nE();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Se(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:OF([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"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:r.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:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=oE(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>$F(d))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:oE(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[aE("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...AF(e)],userCommunication:_F(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[rr({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import cE from"node:path";function lE(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function gm(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:lE(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:lE(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>cE.relative(t.projectRoot,cE.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}K();function dE(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function pE(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function fE(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{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(i=>({kind:"supervisor-child",value:BF(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:FF(i,r)}))]:[]]}function hE(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function HF(e,t){let r=t?.execution;if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running")return;let i=r.verifierStartedAt??null,n=Yf(e,t??null);if(n===void 0)return;let a=n==="confirmed";return{attempt:e.loop.attempt,registeredAt:r.startedAt,confirmedAt:i,confirmation:a?"confirmed":"unconfirmed",...a?{}:{waitingMinutes:Math.max(0,Math.round((Date.now()-Date.parse(r.startedAt))/6e4))}}}function hu(e,t,r=we(e.projectRoot)){let i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:uE.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function wm(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=gm(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...rs(t),status:"blocked",disposition:"blocked",action:"archive",requiresUserDecision:!1,commandArgs:i?.result?.recoveryArgs??["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],inputOptions:[],userCommunication:{required:!0,message:o,suggestedReply:null,agentInstruction:"Report the Git blocker and resolve it within the recorded delivery authorization, then retry the recorded Native workspace finish command. Ask the user only when new information or authorization is required; keep delivery pending until it succeeds."},runnerAction:{...rs(t).runnerAction,kind:"none"}}:rs(t),c=e.details?fE(t,null,[]):[],l=pE(e.cursor,t.state_version,0),u=c.slice(l,l+32),d=l+u.length<c.length?dE(t.state_version,0,l+u.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:Ga(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:uE.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:hE(t),unresolvedAcceptanceIds:n.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:a?[...n.blockers,{owner:"runtime",reason:o,acceptance_ids:[],resolution_action:"wait-external"}]:n.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:s,...e.details?{details:{stateVersion:t.state_version,items:u,nextCursor:d,nextPageArgs:d?["comet","native","status",t.name,"--details","--cursor",d,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function DF(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function mu(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function BF(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:mu(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function FF(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:mu(e.summary,t)??""}}async function mE(e){let t=await Qf(e),r=gm(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await jo({paths:e.paths,state:t.state}),a=await iE({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await et(e.paths,e.name,{diagnostics:!0}),s=o?{...hu(e.paths,t.state,e.gitContext),projectRoot:"."}:hu(e.paths,t.state,e.gitContext),c=rs(t.state,n,{verifierExecutionRef:Kf(t.state,t.local),verifierStartup:Yf(t.state,t.localStatus==="available"?t.local:null),...t.local?{verificationCheckPlans:Kk(t.local,t.local.workspace.projectRoot)}:{}}),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?DF(e.paths,o):[],d=o?(()=>{let m=new Map(n?.children.map(w=>[w.name,w.status])??[]),h=w=>m.get(w.name)??w.status,v=o.children.filter(w=>h(w)==="pending"||h(w)==="ready").length,g=o.children.filter(w=>h(w)==="active"||h(w)==="verified").length,b=o.children.filter(w=>h(w)==="integrated"||h(w)==="archived").length,k=o.children.filter(w=>h(w)==="blocked"||h(w)==="needs-reverify").length,N=o.children.filter(w=>h(w)==="active"||h(w)==="blocked"||h(w)==="needs-reverify").slice(0,16).map(w=>({name:w.name,summary:w.summary,projectRoot:w.task?.projectRoot??w.projectRoot?"<worktree>":null,reason:mu(w.blocker,u)})),x=o.children.flatMap(({blocker:w})=>{let S=mu(w,u);return S?[S]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:g,integrated:b,blocked:k,active:N,agents:{working:o.children.filter(({task:w})=>w!==null).length,completed:b},risks:x,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&b===o.children.length?"parent-verification":v>0?"dispatch-ready-child":k>0?"resolve-blocker":"continue-supervisor"}})():null,p=e.details?(()=>{let m=o?.stateVersion??0,h=fE(t.state,o,u),v=pE(e.cursor,t.state.state_version,m),g=h.slice(v,v+32),b=v+g.length<h.length?dE(t.state.state_version,m,v+g.length):null;return{items:g,nextCursor:b,supervisorStateVersion:m}})():null,f=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,artifacts:Ga(e.paths,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:hE(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:(()=>{let m=HF(t.state,t.localStatus==="available"?t.local:null);return{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null,...m?{verifierStartup:m}:{}}})(),...n?{childSummary:n.children.reduce((m,h)=>({...m,[h.status]:(m[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:p.supervisorStateVersion}:{},items:p.items,nextCursor:p.nextCursor,nextPageArgs:p.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",p.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}import{accessSync as fX,constants as hX,promises as ym}from"node:fs";import Qn from"node:path";oe();Ui();pt();ql();Ui();var vE="comet.native.workspace-finish.v1",wE="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",yE=new RegExp(`^${wE}$`,"u"),qF=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,is=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function gE(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function MF(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==vE||typeof t.name!="string"||!yE.test(t.name)||typeof t.transactionId!="string"||!qF.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Qn.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}if(t.plan!==void 0){let r=t.plan;if(!r||typeof r!="object"||!["keep","merge","push","pull-request"].includes(r.finish)||!["current","branch","worktree"].includes(r.isolation)||![r.changeRoot,r.primaryRoot].every(i=>typeof i=="string"&&Qn.isAbsolute(i))||![r.changeBranch,r.targetBranch].every(i=>typeof i=="string"&&i.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!Qn.isAbsolute(r.targetRoot))||r.remote!==null&&typeof r.remote!="string"||typeof r.commitMessage!="string"||r.mergeMessage!==null&&typeof r.mergeMessage!="string")throw new Error("Native workspace finish journal plan is invalid");gE(r.commitMessage,"commit-message"),r.mergeMessage!==null&&gE(r.mergeMessage,"merge-message")}if(t.createdAt!==void 0&&(typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))))throw new Error("Native workspace finish journal creation identity is invalid");if(t.commit!==void 0){let r=t.commit;if(!r||!is.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(i=>typeof i=="string"&&i.length>0&&!Qn.posix.isAbsolute(i)&&!Qn.win32.isAbsolute(i)&&!i.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(i=>typeof i=="string")||r.sha!==null&&!is.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!is.test(r.target)||!is.test(r.source)||r.sha!==null&&!is.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:vE,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt,...t.createdAt===void 0?{}:{createdAt:t.createdAt},...t.plan===void 0?{}:{plan:t.plan},...t.commit===void 0?{}:{commit:t.commit},...t.merge===void 0?{}:{merge:t.merge}}}function VF(e,t){if(!yE.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Qn.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function Nm(e,t,r={}){let i=VF(e,t);try{let n=await ym.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=MF(JSON.parse(await ym.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}async function NE(e,t={}){let r;try{r=await ym.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.isFile()&&!n.isSymbolicLink()||n.isDirectory())continue;let a=new RegExp(`^workspace-finish-(${wE})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await Nm(e,a[1],t);o&&i.push(o)}return i}function vu(e,t){let r=zi.normalize(bm(e)),i=zi.normalize(bm(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function bm(e){let t=zi.resolve(e);try{return WF.native(t)}catch{return t}}async function bE(e,t){let r=[];for(let i of await XS(e))t!==void 0&&i!==t||r.push({name:i,kind:await Eo(e,i)?"portable":"legacy"});return r}async function zF(e,t){let r=zi.resolve(e),i=us(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>vu(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>zi.resolve(l)).sort()){let l=vu(c,r)?r:c,u=bm(l),d=process.platform==="win32"?u.toLowerCase():u;if(s.has(d))continue;s.add(d);let p=await xe(l);if(!p)continue;let f=await Vt(l,p.native.artifact_root);o.push({projectRoot:l,config:p,paths:f,gitContext:aa(l,i)??we(l),changes:await bE(f,t)})}if(o.length===0){let c=await xe(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await Vt(e,c.native.artifact_root);o.push({projectRoot:zi.resolve(e),config:c,paths:l,gitContext:aa(e,i)??we(e),changes:await bE(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await ZS(c.paths,(u,d)=>c.archiveErrors.push({name:u,message:d}),t),t!==void 0&&(c.archives=c.archives.filter(({state:u})=>u.name===t),c.archiveErrors=c.archiveErrors.filter(({name:u})=>u===t));let l=(u,d)=>c.finishJournalErrors.push({name:u,message:d});c.finishJournals=t?[await Nm(c.paths,t,{onError:l})].filter(u=>u!==null):await NE(c.paths,{onError:l})}return o}function kE(e,t){return e.workspace.bindingState==="aligned"?0:vu(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function GF(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournals??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournalErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:d,kind:p})=>{let f=d.finishJournalErrors?.find(({name:m})=>m===n);if(p==="portable")try{let m=await ft(d.paths,n);return{source:d,name:n,kind:p,workspace:hu(d.paths,m,d.gitContext),portableStatus:null,inspectionError:f?.message??null,finishJournal:d.finishJournals?.find(({name:h})=>h===n)??null}}catch(m){return{source:d,name:n,kind:p,workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:"The portable state could not be inspected."},portableStatus:null,inspectionError:m instanceof Error?m.message:String(m)}}return{source:d,name:n,kind:p,workspace:a.length>1?await mo(d.paths,n):{projectRoot:d.projectRoot,currentBranch:d.gitContext.currentBranch,isSecondaryWorktree:d.gitContext.isSecondaryWorktree,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:null,finish:null},portableStatus:null,inspectionError:f?.message??null}})),s=t.flatMap(d=>(d.archives??[]).filter(({state:p})=>p.name===n).map(p=>{let f=wm({paths:d.paths,...p,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null});return{source:d,name:n,kind:"portable",workspace:f.workspace,portableStatus:f,inspectionError:d.finishJournalErrors?.find(({name:m})=>m===n)?.message??null,record:p,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null}})),c=t.flatMap(d=>(d.archiveErrors??[]).filter(p=>p.name===n).map(p=>({source:d,error:p})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}let l=t.flatMap(d=>(d.finishJournalErrors??[]).filter(p=>p.name===n).map(p=>({source:d,error:p})))[0];if(l&&o.length===0&&s.length===0){i.push({source:l.source,name:n,kind:"portable",portableStatus:null,inspectionError:l.error.message,workspace:{projectRoot:l.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:l.error.message}});continue}if(o.length===0&&s.length===0){let d=t.find(f=>f.finishJournals?.some(({name:m})=>m===n)),p=d?.finishJournals?.find(({name:f})=>f===n);if(d&&p){i.push({source:d,name:n,kind:"portable",portableStatus:null,inspectionError:p.result?.message??"Native workspace finish journal has no matching active or archived change record.",workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:p.result?.message??"Native workspace finish record is orphaned."},finishJournal:p});continue}}if(s.length>0){for(let p of o)if(p.kind==="portable")try{p.record=await uu(p.source.paths,zi.join(p.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let d=s.find(p=>[...o,...s.filter(f=>!tE(p.record,f.record))].every(f=>f.record&&eE(p.record,f.record)));if(d){i.push(d);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((d,p)=>kE(d,e)-kE(p,e)||d.source.projectRoot.localeCompare(p.source.projectRoot));let u=o.filter(d=>d.workspace.bindingState==="aligned");u.length>1?i.push(...u):u.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(u[0]??o[0])}if(i.length>ts.maxChanges)throw new Error(`Native status discovery exceeds ${ts.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}async function JF(e,t,r){let i=await mo(e.source.paths,e.name),n=null;try{n=await nb(e.source.paths,e.name)}catch{}return n?.state?{schema:"comet.native.status.v2",name:e.name,phase:n.state.phase,status:"blocked",migrationRequired:!0,legacySchema:n.schema,workspace:i,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:n.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],message:"This change uses a legacy schema; the first mutating command performs the deterministic migration. Run the listed next command with a migration summary.",runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:hm(e.source.paths,e.name,{details:t,...r?{acceptanceCursor:r}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function SE(e,t,r,i){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:[],message:`Run the repair command in the workspace holding this change: ${e.source.paths.projectRoot}`,runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(r)throw new Error("Portable Native status includes the complete acceptance list");if(!t&&e.portableStatus)return e.portableStatus;if(e.record?.state.archived)return wm({paths:e.source.paths,...e.record,finishJournal:e.finishJournal??null,details:t,cursor:i});try{return await mE({paths:e.source.paths,name:e.name,details:t,gitContext:e.source.gitContext,...i?{cursor:i}:{}})}catch(n){if(i)throw n;return SE({...e,inspectionError:n instanceof Error?n.message:String(n)},!1)}}return JF(e,t,r)}async function EE(e){let{sources:t,candidates:r}=await UF(e.projectRoot,e.name);if(r.length===0){let i=t.find(n=>vu(n.projectRoot,e.projectRoot))??t[0];return e.onSelectedRoot?.(i.projectRoot),hm(i.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:i.config.native.clarification_mode,maxVerifyFailures:i.config.native.max_verify_failures})}return e.onSelectedRoot?.(r[0].source.projectRoot),SE(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function UF(e,t){let r=await zF(e,t),i=(await GF(e,r)).filter(n=>n.name===t);if(i.length>1)throw new Error(`Native change ${t} has multiple aligned workspace bindings: ${i.map(n=>n.source.projectRoot).join(", ")}`);return{sources:r,candidates:i}}Va();import ns from"path";import{realpathSync as pL}from"fs";function xE(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(e),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var Sr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function CE(e){return e?e.command?`${Sr.next} ${e.command}`:e.ask_user?`${Sr.next} ${e.ask_user}`:null:null}function RE(e,t){let r=[e.summary],i=CE(e.next);return i&&r.push(i),e.user_message&&r.push("",Sr.relay,e.user_message),t!==void 0&&r.push("",Sr.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
256
263
|
`)}
|
|
257
|
-
`}function
|
|
258
|
-
`)}Ut();Ct();oe();Lt();K();Ct();
|
|
259
|
-
`)}}let r=t.continuation;if(
|
|
264
|
+
`}function PE(e,t,r){let i=[e.summary],n=CE(e.next);return n&&i.push(n),e.user_message&&i.push("",Sr.relay,e.user_message),i.push("",`${Sr.detail} ${t}`),r!==void 0&&i.push("",Sr.details,JSON.stringify(r,null,2)),i.join(`
|
|
265
|
+
`)}Ut();Ct();oe();Lt();K();Ct();tl();oe();Ni();si();var hQ=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Ut();Ka();Re();K();Ct();tl();var gu=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},wu=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};K();Qe();function L(e,t,r){return e==="zh-CN"?r:t}var km={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function _E(e,t){return typeof e=="string"&&km[e]?L(t,km[e].en,km[e].zh):typeof e=="string"?e:""}function Sm(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 XF(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function AE(e,t){let r=[];e.failed>0&&r.push(L(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(L(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(L(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=L(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function IE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Em(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function QF(e,t,r){return e==="done"?L(r,"complete","已完成"):e==="await-user"?L(r,"waiting for a user decision","等待用户决定"):e==="blocked"?L(r,"paused: needs attention","已暂停,需要处理"):t?L(r,"waiting for a user decision","等待用户决定"):L(r,"ready to continue","可继续推进")}function ZF(e,t,r){let i=Em(e),n=[];r&&n.push(r);let a=L(i,`Change ${e.change}`,`需求 ${e.change}`),o=_E(e.phase,i),s=QF(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(AE(t,i));let c=e.userCommunication,l=TE(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function TE(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:L(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:L(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:L(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function eL(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function tL(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=_E(e.phase,t),n=e.status==="await-user"?L(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?L(t,"paused","已暂停"):e.status==="done"?L(t,"complete","已完成"):L(t,"in progress","进行中"),a=Sm(e.acceptance)?`${L(t,", ",",")}${AE(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function rL(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function iL(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 nL(e){if(e.healthy){let i=e.repaired?L("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):L("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=aL(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:L("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:L("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function aL(e){return IE(e)?TE(e,Em(e)):void 0}function jE(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(iL(t))return nL(t);if(eL(t)){let i=rL(t.items);return{summary:[t.total===t.items.length?L(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):L(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>tL(a,i))].join(`
|
|
266
|
+
`)}}let r=t.continuation;if(IE(r)){let i=Em(r),n=ZF(r,oL(t),cL(t,i));return sL(t)==="unconfirmed"?{...n,summary:`${n.summary}${L(i,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:n}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:L(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function oL(e){if(Sm(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Sm(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return XF(r.acceptance)}return null}function sL(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function cL(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return L(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?L(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function $E(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"document-invalid":return{summary:e.message,...typeof r.change=="string"?{next:{command:`comet native next ${r.change} --summary <summary>`}}:{}};case"conflict":return{summary:L("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:L("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:L("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:L("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:L("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:L("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:L("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:L("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:L("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}Vc();Wc();var OE=["--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."],xm=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","In `agent.workspace.cwd`, execute the exact `agent.continuation.commandArgs` returned by Runtime.","Use `agent.continuation.inputOptions` templates for JSON input; do not reconstruct fields from memory."],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 disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","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.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:OE,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] [--task <text>] [--capability <id>] [--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.","--task <text> Search Project Knowledge for an existing capability and save a revocable association draft.","--capability <id> Directly validate and associate an existing capability without retrieval.","--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, canonical artifact paths, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"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 disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
|
|
260
267
|
comet native spec remove <change-name> <capability>
|
|
261
268
|
comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["disassociate <change-name> Revoke a capability association and return to Shape.","remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],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."},"spec disassociate":{usage:"comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability",purpose:"Revoke a capability association through Runtime without hand-editing artifacts.",options:["--expected-state-version <n> State version returned by the latest status response.","--expected-action <action> Must be disassociate-capability."],output:"The updated portable state and continuation with the next Runner action."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"A compact summary and NEXT action by default. Use --json to read canonical artifact paths, the portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Legacy-only verification command; not supported for current portable changes.",output:"For current changes, run comet native status <change-name> --json and follow the continuation to dispatch verification through comet native next."},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 canonical artifact paths and local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
|
|
262
269
|
comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
|
|
263
270
|
comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Choose how a multi-child Supervisor proceeds. Supply it with --confirmed at the persisted Shape boundary to confirm the full plan and mode together, or select it during preparation and confirm the plan afterward.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--finish keep|merge|push|pull-request With --accept-result, record the explicitly chosen isolated-workspace finish in the same guarded decision.","--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, retry-checks, verifier-response, verifier-started, verifier-execution-error, or verifier-unavailable. Builder/dispatch identity fields are rejected; verifier responses must echo the current candidateId and verifierExecutionRef from the Verifier dispatch.","--validate-only Validate the Runner JSON shape and current boundary without writing state or starting a process; requires --runner-input."," Choose one object template from an inputOptions exclusiveGroup and save it as UTF-8 JSON (BOM accepted). Field errors return issues with JSON pointer, missingFields and unknownFields. Execute agent.continuation in agent.workspace.cwd; Supervisor results use task.returnAction."," builder-handoff fields: kind, summary, addressed_acceptance_ids, acceptance_review, checks, verification_checks, known_limits, optional review. acceptance_review must cover every confirmed ID exactly once with id, status, evidence (concrete references or observations), and note. Only implemented-with-evidence with nonempty evidence is ready for handoff; implemented-no-evidence, not-implemented, and known-fail remain in Build. This Builder declaration does not replace independent verification. checks summarize development feedback. verification_checks is an optional Runtime plan executed after the candidate is frozen; a passing plan returns the Verifier dispatch immediately. Completed Runtime checks can carry to a new candidate only when the implementation, confirmed documents, plan, workspace, environment, and saved evidence still match. If review is supplied, its fields are status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," retry-checks fields: kind, check_ids for repeatable interrupted Runtime checks from the current candidate; each check can be retried at most three times."," verifier-response fields: kind, candidateId, verifierExecutionRef, response (request-checks or final-result); copy the two binding fields from the current continuation."," verifier-started fields: kind, candidateId, verifierExecutionRef copied from verifierDispatch; the dispatched Verifier submits it as its first Runtime action so status can distinguish a registered dispatch from a Verifier that actually started. Repeating it is accepted without side effects."," 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)."," supervisor-checks fields: kind, child, runId, checks (non-empty repeatable Runtime check plans), materials [{name,content}], and optional retry_check_ids for interrupted checks from the same candidate, machine and workspace. Returns per-check execution state plus operationId, status and receiptRef. Repeated running plans return the same handle."," supervisor-verifier-result evidence fields: summary, checks (informal notes), acceptance [{id,result,reason}], receiptRef. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once. Runtime receipts determine formal check status; receiptRef may be null for fail or blocked."," supervisor-integrate checks are non-empty Runtime check plans executed after the merge in the integration worktree, not declared statuses."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep] [--commit-message <text>] [--merge-message <text>]
|
|
264
|
-
comet native archive <change-name> [--confirmed] [--serial-first <current-change>] [--commit-message <text>] [--merge-message <text>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--expected-state-version <n> Preserve this continuation-issued guard when confirming a new finish choice; stale choices are rejected before it is recorded.","--commit-message <text> Set the archive commit message; Unicode and multiline text are supported. Git hooks still run.","--merge-message <text> Set the local merge commit message; requires merge finish. Omit it to use Git defaults.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, actual prepared commitMessages (mergeMessage is null when no merge is planned), and the exact next continuation, or the completed Archive transaction and workspace finish result. Messages are retained for retries. After a Git hook rejects a message, provide a corrected message with --confirmed for the unfinished step; completed commits are never rewritten. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function
|
|
271
|
+
comet native archive <change-name> [--confirmed] [--serial-first <current-change>] [--commit-message <text>] [--merge-message <text>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--expected-state-version <n> Preserve this continuation-issued guard when confirming a new finish choice; stale choices are rejected before it is recorded.","--commit-message <text> Set the archive commit message; Unicode and multiline text are supported. Git hooks still run.","--merge-message <text> Set the local merge commit message; requires merge finish. Omit it to use Git defaults.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, actual prepared commitMessages (mergeMessage is null when no merge is planned), and the exact next continuation, or the completed Archive transaction and workspace finish result. Messages are retained for retries. After a Git hook rejects a message, provide a corrected message with --confirmed for the unfinished step; completed commits are never rewritten. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function yu(e,t){return`${e}:
|
|
265
272
|
${t.map(r=>` ${r}`).join(`
|
|
266
|
-
`)}`}function
|
|
267
|
-
${r.output}`),r.examples&&i.push("",
|
|
273
|
+
`)}`}function lL(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return xm[r]||t.length>1&&xm[t[0]]?.subcommands?r:t[0]}function uL(e=[]){let t=lL(e),r=xm[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",yu("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",yu("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...OE];return n&&n.length>0&&i.push("",yu("Options",n)),i.push("",`Output:
|
|
274
|
+
${r.output}`),r.examples&&i.push("",yu("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
268
275
|
`)}
|
|
269
|
-
`}}var
|
|
270
|
-
`}function
|
|
271
|
-
`}:e.error?{exitCode:e.exitCode,stderr:i?
|
|
276
|
+
`}}var dL=uL().usage;var bZ=10*1024*1024,ui=class extends Error{};function Rm(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new ui(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function DE(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new ui(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new ui(`${t} requires a value`);return e.splice(i,2),n}function BE(e){if(e.length>0)throw new ui(`Unexpected argument: ${e[0]}`)}function FE(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new ui(`${t} is required`);return r}function Cm(e,t){let r=ns.normalize(HE(e)),i=ns.normalize(HE(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function HE(e){let t=ns.resolve(e);try{return pL.native(t)}catch{return t}}function fL(e,t){let r=ns.resolve(t,e),i=we(t);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=we(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!Cm(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||Cm(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:Cm(t,i.currentWorktreeRoot)?ns.resolve(t):i.currentWorktreeRoot}async function LE(e,t=process.cwd()){return e?fL(e,t):Cc(t)}function qE(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}async function Pm(e){let t=await Xw({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function ME(e){return JSON.stringify(e,null,2)+`
|
|
277
|
+
`}function VE(e,t,r){return{command:e,exitCode:0,data:t,text:r??ME(t)}}function hL(e,t){if(t instanceof go)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof gn)return{command:e,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:t.missingIds,incompleteIds:t.incompleteIds}},error:{code:"invalid-data",message:t.message}};if(t instanceof io)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof ui)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof gu)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 wu)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof bl)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 vo)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 Ml)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof kl)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 li)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Zo)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function WE(e,t){let r=hL(e,t),i=r.error;if(!i)return r;let n=$E({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function mL(e,t,r=!1){let i=e.envelope??jE(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:xE(e.data,e.executionCwd),...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
278
|
+
`}:e.error?{exitCode:e.exitCode,stderr:i?PE(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:RE(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==ME(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
272
279
|
${Sr.details}
|
|
273
280
|
${JSON.stringify(e.data,null,2)}
|
|
274
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}function
|
|
281
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}function vL(e,t,r=!1){let i=mL(e,t,r),n=!1;if(i.stdout?.trim())try{let a=JSON.parse(i.stdout);n=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{n=!1}return{output:i,structuredDataVisible:n}}function zE(e,t,r=!1){return vL(e,t,r).output}async function GE(e,t){let r=FE(e,"change name");BE(e),await Pm(t);let i=t,n=await EE({projectRoot:t,name:r,onSelectedRoot:a=>{i=a}});return await Xk((await Pm(i)).paths,r),{...VE("select",{selected:r,...n}),executionCwd:i}}async function JE(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Rm(n,"--json"),Rm(n,"--verbose"),c=DE(n,"--project-root");let d=[...n,...a],p=async()=>{let f=await LE(c);return{executionCwd:f,...await t(d,f)}};l=qE(e,d)?await $m(p):await p()}catch(d){l=WE(e,d)}let u=zE(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
275
282
|
`)?"":`
|
|
276
|
-
`)),u.exitCode}process.exitCode=await
|
|
283
|
+
`)),u.exitCode}process.exitCode=await JE("select",GE);
|