@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,149 +1,149 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`)}};
|
|
6
|
-
`)?
|
|
4
|
+
var qE=Object.create;var Zu=Object.defineProperty;var ME=Object.getOwnPropertyDescriptor;var VE=Object.getOwnPropertyNames;var WE=Object.getPrototypeOf,zE=Object.prototype.hasOwnProperty;var Bs=(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 T=(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}},ed=(e,t)=>{for(var r in t)Zu(e,r,{get:t[r],enumerable:!0})},GE=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of VE(t))!zE.call(e,n)&&n!==r&&Zu(e,n,{get:()=>t[n],enumerable:!(i=ME(t,n))||i.enumerable});return e};var hr=(e,t,r)=>(r=e!=null?qE(WE(e)):{},GE(t||!e||!e.__esModule?Zu(r,"default",{value:e,enumerable:!0}):r,e));var U=R(Ie=>{"use strict";var td=Symbol.for("yaml.alias"),ov=Symbol.for("yaml.document"),Ls=Symbol.for("yaml.map"),sv=Symbol.for("yaml.pair"),rd=Symbol.for("yaml.scalar"),Fs=Symbol.for("yaml.seq"),mr=Symbol.for("yaml.node.type"),JE=e=>!!e&&typeof e=="object"&&e[mr]===td,UE=e=>!!e&&typeof e=="object"&&e[mr]===ov,KE=e=>!!e&&typeof e=="object"&&e[mr]===Ls,YE=e=>!!e&&typeof e=="object"&&e[mr]===sv,cv=e=>!!e&&typeof e=="object"&&e[mr]===rd,XE=e=>!!e&&typeof e=="object"&&e[mr]===Fs;function lv(e){if(e&&typeof e=="object")switch(e[mr]){case Ls:case Fs:return!0}return!1}function QE(e){if(e&&typeof e=="object")switch(e[mr]){case td:case Ls:case rd:case Fs:return!0}return!1}var ZE=e=>(cv(e)||lv(e))&&!!e.anchor;Ie.ALIAS=td;Ie.DOC=ov;Ie.MAP=Ls;Ie.NODE_TYPE=mr;Ie.PAIR=sv;Ie.SCALAR=rd;Ie.SEQ=Fs;Ie.hasAnchor=ZE;Ie.isAlias=JE;Ie.isCollection=lv;Ie.isDocument=UE;Ie.isMap=KE;Ie.isNode=QE;Ie.isPair=YE;Ie.isScalar=cv;Ie.isSeq=XE});var ya=R(id=>{"use strict";var Ne=U(),Me=Symbol("break visit"),uv=Symbol("skip children"),Wt=Symbol("remove node");function qs(e,t){let r=dv(t);Ne.isDocument(e)?cn(null,e.contents,r,Object.freeze([e]))===Wt&&(e.contents=null):cn(null,e,r,Object.freeze([]))}qs.BREAK=Me;qs.SKIP=uv;qs.REMOVE=Wt;function cn(e,t,r,i){let n=pv(e,t,r,i);if(Ne.isNode(n)||Ne.isPair(n))return fv(e,i,n),cn(e,n,r,i);if(typeof n!="symbol"){if(Ne.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=cn(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Me)return Me;o===Wt&&(t.items.splice(a,1),a-=1)}}}else if(Ne.isPair(t)){i=Object.freeze(i.concat(t));let a=cn("key",t.key,r,i);if(a===Me)return Me;a===Wt&&(t.key=null);let o=cn("value",t.value,r,i);if(o===Me)return Me;o===Wt&&(t.value=null)}}return n}async function Ms(e,t){let r=dv(t);Ne.isDocument(e)?await ln(null,e.contents,r,Object.freeze([e]))===Wt&&(e.contents=null):await ln(null,e,r,Object.freeze([]))}Ms.BREAK=Me;Ms.SKIP=uv;Ms.REMOVE=Wt;async function ln(e,t,r,i){let n=await pv(e,t,r,i);if(Ne.isNode(n)||Ne.isPair(n))return fv(e,i,n),ln(e,n,r,i);if(typeof n!="symbol"){if(Ne.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await ln(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Me)return Me;o===Wt&&(t.items.splice(a,1),a-=1)}}}else if(Ne.isPair(t)){i=Object.freeze(i.concat(t));let a=await ln("key",t.key,r,i);if(a===Me)return Me;a===Wt&&(t.key=null);let o=await ln("value",t.value,r,i);if(o===Me)return Me;o===Wt&&(t.value=null)}}return n}function dv(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 pv(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(Ne.isMap(t))return r.Map?.(e,t,i);if(Ne.isSeq(t))return r.Seq?.(e,t,i);if(Ne.isPair(t))return r.Pair?.(e,t,i);if(Ne.isScalar(t))return r.Scalar?.(e,t,i);if(Ne.isAlias(t))return r.Alias?.(e,t,i)}function fv(e,t,r){let i=t[t.length-1];if(Ne.isCollection(i))i.items[e]=r;else if(Ne.isPair(i))e==="key"?i.key=r:i.value=r;else if(Ne.isDocument(i))i.contents=r;else{let n=Ne.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}id.visit=qs;id.visitAsync=Ms});var nd=R(mv=>{"use strict";var hv=U(),ex=ya(),tx={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},rx=e=>e.replace(/[!,[\]{}]/g,t=>tx[t]),ba=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+rx(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&&hv.isNode(t.contents)){let a={};ex.visit(t.contents,(o,s)=>{hv.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
|
|
5
|
+
`)}};ba.defaultYaml={explicit:!1,version:"1.2"};ba.defaultTags={"!!":"tag:yaml.org,2002:"};mv.Directives=ba});var Vs=R(Na=>{"use strict";var vv=U(),ix=ya();function nx(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 gv(e){let t=new Set;return ix.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function wv(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function ax(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=gv(e));let o=wv(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(vv.isScalar(o.node)||vv.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}}Na.anchorIsValid=nx;Na.anchorNames=gv;Na.createNodeAnchors=ax;Na.findNewAnchor=wv});var ad=R(yv=>{"use strict";function ka(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=ka(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=ka(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=ka(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=ka(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}yv.applyReviver=ka});var Hr=R(Nv=>{"use strict";var ox=U();function bv(e,t,r){if(Array.isArray(e))return e.map((i,n)=>bv(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!ox.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}Nv.toJS=bv});var Ws=R(Sv=>{"use strict";var sx=ad(),kv=U(),cx=Hr(),od=class{constructor(t){Object.defineProperty(this,kv.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(!kv.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=cx.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?sx.applyReviver(a,{"":s},"",s):s}};Sv.NodeBase=od});var Sa=R(Ev=>{"use strict";var lx=Vs(),ux=ya(),un=U(),dx=Ws(),px=Hr(),sd=class extends dx.NodeBase{constructor(t){super(un.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=[],ux.visit(t,{Node:(a,o)=>{(un.isAlias(o)||un.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||(px.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=zs(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(lx.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 zs(e,t,r){if(un.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(un.isCollection(t)){let i=0;for(let n of t.items){let a=zs(e,n,r);a>i&&(i=a)}return i}else if(un.isPair(t)){let i=zs(e,t.key,r),n=zs(e,t.value,r);return Math.max(i,n)}return 1}Ev.Alias=sd});var we=R(cd=>{"use strict";var fx=U(),hx=Ws(),mx=Hr(),vx=e=>!e||typeof e!="function"&&typeof e!="object",Dr=class extends hx.NodeBase{constructor(t){super(fx.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:mx.toJS(this.value,t,r)}toString(){return String(this.value)}};Dr.BLOCK_FOLDED="BLOCK_FOLDED";Dr.BLOCK_LITERAL="BLOCK_LITERAL";Dr.PLAIN="PLAIN";Dr.QUOTE_DOUBLE="QUOTE_DOUBLE";Dr.QUOTE_SINGLE="QUOTE_SINGLE";cd.Scalar=Dr;cd.isScalarValue=vx});var Ea=R(Rv=>{"use strict";var gx=Sa(),wi=U(),xv=we(),wx="tag:yaml.org,2002:";function yx(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 bx(e,t,r){if(wi.isDocument(e)&&(e=e.contents),wi.isNode(e))return e;if(wi.isPair(e)){let p=r.schema[wi.MAP].createNode?.(r.schema,null,r);return p.items.push(e),p}(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 gx.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=wx+t.slice(2));let l=yx(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let p=new xv.Scalar(e);return c&&(c.node=p),p}l=e instanceof Map?o[wi.MAP]:Symbol.iterator in Object(e)?o[wi.SEQ]:o[wi.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 xv.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Rv.createNode=bx});var Js=R(Gs=>{"use strict";var Nx=Ea(),zt=U(),kx=Ws();function ld(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 Nx.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 Cv=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ud=class extends kx.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=>zt.isNode(i)||zt.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Cv(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(zt.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,ld(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(zt.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&&zt.isScalar(a)?a.value:a:zt.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!zt.isPair(r))return!1;let i=r.value;return i==null||t&&zt.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 zt.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(zt.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,ld(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Gs.Collection=ud;Gs.collectionFromPath=ld;Gs.isEmptyPath=Cv});var xa=R(Us=>{"use strict";var Sx=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function dd(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ex=(e,t,r)=>e.endsWith(`
|
|
6
|
+
`)?dd(r,t):r.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)r===
|
|
10
|
-
`&&
|
|
11
|
-
`&&y!==" "&&(
|
|
12
|
-
${t}${e.slice(0,E)}`:(r===
|
|
13
|
-
${t}${e.slice(y+1,E)}`)}return w}function
|
|
14
|
-
`);i=t,n=t+1,a=e[n]}return i}
|
|
15
|
-
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function
|
|
8
|
+
`+dd(r,t):(e.endsWith(" ")?"":" ")+r;Us.indentComment=dd;Us.lineComment=Ex;Us.stringifyComment=Sx});var _v=R(Ra=>{"use strict";var xx="flow",pd="block",Ks="quoted";function Rx(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={},p=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):p=n-i);let d,f,h=!1,m=-1,v=-1,g=-1;r===pd&&(m=Pv(e,m,t.length),m!==-1&&(p=m+c));for(let N;N=e[m+=1];){if(r===Ks&&N==="\\"){switch(v=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}g=m}if(N===`
|
|
9
|
+
`)r===pd&&(m=Pv(e,m,t.length)),p=m+t.length+c,d=void 0;else{if(N===" "&&f&&f!==" "&&f!==`
|
|
10
|
+
`&&f!==" "){let y=e[m+1];y&&y!==" "&&y!==`
|
|
11
|
+
`&&y!==" "&&(d=m)}if(m>=p)if(d)l.push(d),p=d+c,d=void 0;else if(r===Ks){for(;f===" "||f===" ";)f=N,N=e[m+=1],h=!0;let y=m>g+1?m-2:v-1;if(u[y])return e;l.push(y),u[y]=!0,p=y+c,d=void 0}else h=!0}f=N}if(h&&s&&s(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let N=0;N<l.length;++N){let y=l[N],E=l[N+1]||e.length;y===0?w=`
|
|
12
|
+
${t}${e.slice(0,E)}`:(r===Ks&&u[y]&&(w+=`${e[y]}\\`),w+=`
|
|
13
|
+
${t}${e.slice(y+1,E)}`)}return w}function Pv(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
+
`);i=t,n=t+1,a=e[n]}return i}Ra.FOLD_BLOCK=pd;Ra.FOLD_FLOW=xx;Ra.FOLD_QUOTED=Ks;Ra.foldFlowLines=Rx});var Pa=R(Av=>{"use strict";var Rt=we(),Br=_v(),Xs=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Qs=e=>/^(%|---|\.\.\.)/m.test(e);function Cx(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Ca(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Qs(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)+`
|
|
16
16
|
|
|
17
17
|
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:Br.foldFlowLines(o,a,Br.FOLD_QUOTED,
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
20
|
-
${r}`)+"'";return t.implicitKey?i:Br.foldFlowLines(i,r,Br.FOLD_FLOW,
|
|
18
|
+
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:Br.foldFlowLines(o,a,Br.FOLD_QUOTED,Xs(t,!1))}function fd(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Ca(e,t);let r=t.indent||(Qs(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${r}`)+"'";return t.implicitKey?i:Br.foldFlowLines(i,r,Br.FOLD_FLOW,Xs(t,!1))}function dn(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Ca;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=fd:a&&!n?i=Ca:i=r?fd:Ca}return i(e,t)}var hd;try{hd=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{hd=/\n+(?!\n|$)/g}function Ys({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 dn(r,i);let l=i.indent||(i.forceBlockIndent||Qs(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===Rt.Scalar.BLOCK_FOLDED?!1:t===Rt.Scalar.BLOCK_LITERAL?!0:!Cx(r,c,l.length);if(!r)return u?`|
|
|
24
24
|
`:`>
|
|
25
|
-
`;let d
|
|
26
|
-
`&&E!==" "&&E!==" ")break}let
|
|
27
|
-
`);
|
|
28
|
-
`&&(
|
|
29
|
-
`)g=v;else break}let w=r.substring(0,g<v?g+1:v);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let y=(m?l?"2":"1":"")+
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,x=
|
|
25
|
+
`;let p,d;for(d=r.length;d>0;--d){let E=r[d-1];if(E!==`
|
|
26
|
+
`&&E!==" "&&E!==" ")break}let f=r.substring(d),h=f.indexOf(`
|
|
27
|
+
`);h===-1?p="-":r===f||h!==f.length-1?(p="+",a&&a()):p="",f&&(r=r.slice(0,-f.length),f[f.length-1]===`
|
|
28
|
+
`&&(f=f.slice(0,-1)),f=f.replace(hd,`$&${l}`));let m=!1,v,g=-1;for(v=0;v<r.length;++v){let E=r[v];if(E===" ")m=!0;else if(E===`
|
|
29
|
+
`)g=v;else break}let w=r.substring(0,g<v?g+1:v);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let y=(m?l?"2":"1":"")+p;if(e&&(y+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let E=r.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,x=Xs(i,!0);o!=="folded"&&t!==Rt.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{b=!0});let k=Br.foldFlowLines(`${w}${E}${f}`,l,Br.FOLD_BLOCK,x);if(!b)return`>${y}
|
|
31
31
|
${l}${k}`}return r=r.replace(/\n+/g,`$&${l}`),`|${y}
|
|
32
|
-
${l}${w}${r}${
|
|
33
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let
|
|
37
|
-
${t.indent}${s}`:s}
|
|
38
|
-
${s}:`):(v=`${v}:`,
|
|
32
|
+
${l}${w}${r}${f}`}function Px(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(`
|
|
33
|
+
`)||u&&/[[\]{},]/.test(a))return dn(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
+
`)?dn(a,t):Ys(e,t,r,i);if(!s&&!u&&n!==Rt.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return Ys(e,t,r,i);if(Qs(a)){if(c==="")return t.forceBlockIndent=!0,Ys(e,t,r,i);if(s&&c===l)return dn(a,t)}let p=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(p),{compat:f,tags:h}=t.doc.schema;if(h.some(d)||f?.some(d))return dn(a,t)}return s?p:Br.foldFlowLines(p,c,Br.FOLD_FLOW,Xs(t,!1))}function _x(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!==Rt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Rt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Rt.Scalar.BLOCK_FOLDED:case Rt.Scalar.BLOCK_LITERAL:return n||a?dn(o.value,t):Ys(o,t,r,i);case Rt.Scalar.QUOTE_DOUBLE:return Ca(o.value,t);case Rt.Scalar.QUOTE_SINGLE:return fd(o.value,t);case Rt.Scalar.PLAIN:return Px(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:p}=t.options,d=n&&u||p;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Av.stringifyString=_x});var _a=R(md=>{"use strict";var Ax=Vs(),Lr=U(),Ix=xa(),Tx=Pa();function $x(e,t){let r=Object.assign({blockQuote:!0,commentString:Ix.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 jx(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(Lr.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 Ox(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Lr.isScalar(e)||Lr.isCollection(e))&&e.anchor;a&&Ax.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 Hx(e,t,r,i){if(Lr.isPair(e))return e.toString(t,r,i);if(Lr.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=Lr.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=jx(t.doc.schema.tags,a));let o=Ox(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):Lr.isScalar(a)?Tx.stringifyString(a,t,r,i):a.toString(t,r,i);return o?Lr.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}md.createStringifyContext=$x;md.stringify=Hx});var jv=R($v=>{"use strict";var vr=U(),Iv=we(),Tv=_a(),Aa=xa();function Dx({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:p}}=r,d=vr.isNode(e)&&e.comment||null;if(p){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(vr.isCollection(e)||!vr.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let f=!p&&(!e||d&&t==null&&!r.inFlow||vr.isCollection(e)||(vr.isScalar(e)?e.type===Iv.Scalar.BLOCK_FOLDED||e.type===Iv.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!f&&(p||!a),indent:s+c});let h=!1,m=!1,v=Tv.stringify(e,r,()=>h=!0,()=>m=!0);if(!f&&!r.inFlow&&v.length>1024){if(p)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 h&&i&&i(),v===""?"?":f?`? ${v}`:v}else if(a&&!p||t==null&&f)return v=`? ${v}`,d&&!h?v+=Aa.lineComment(v,r.indent,l(d)):m&&n&&n(),v;h&&(d=null),f?(d&&(v+=Aa.lineComment(v,r.indent,l(d))),v=`? ${v}
|
|
38
|
+
${s}:`):(v=`${v}:`,d&&(v+=Aa.lineComment(v,r.indent,l(d))));let g,w,N;vr.isNode(t)?(g=!!t.spaceBefore,w=t.commentBefore,N=t.comment):(g=!1,w=null,N=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!f&&!d&&vr.isScalar(t)&&(r.indentAtStart=v.length+1),m=!1,!u&&c.length>=2&&!r.inFlow&&!f&&vr.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let y=!1,E=Tv.stringify(t,r,()=>y=!0,()=>m=!0),b=" ";if(d||g||w){if(b=g?`
|
|
39
39
|
`:"",w){let x=l(w);b+=`
|
|
40
|
-
${
|
|
40
|
+
${Aa.indentComment(x,r.indent)}`}E===""&&!r.inFlow?b===`
|
|
41
41
|
`&&N&&(b=`
|
|
42
42
|
|
|
43
43
|
`):b+=`
|
|
44
|
-
${r.indent}`}else if(!
|
|
44
|
+
${r.indent}`}else if(!f&&vr.isCollection(t)){let x=E[0],k=E.indexOf(`
|
|
45
45
|
`),S=k!==-1,C=r.inFlow??t.flow??t.items.length===0;if(S||!C){let P=!1;if(S&&(x==="&"||x==="!")){let _=E.indexOf(" ");x==="&"&&_!==-1&&_<k&&E[_+1]==="!"&&(_=E.indexOf(" ",_+1)),(_===-1||k<_)&&(P=!0)}P||(b=`
|
|
46
46
|
${r.indent}`)}}else(E===""||E[0]===`
|
|
47
|
-
`)&&(b="");return v+=b+E,r.inFlow?y&&i&&i():N&&!y?v+=
|
|
47
|
+
`)&&(b="");return v+=b+E,r.inFlow?y&&i&&i():N&&!y?v+=Aa.lineComment(v,r.indent,l(N)):m&&n&&n(),v}$v.stringifyPair=Dx});var gd=R(vd=>{"use strict";var Ov=Bs("process");function Bx(e,...t){e==="debug"&&console.log(...t)}function Lx(e,t){(e==="debug"||e==="warn")&&(typeof Ov.emitWarning=="function"?Ov.emitWarning(t):console.warn(t))}vd.debug=Bx;vd.warn=Lx});var ic=R(rc=>{"use strict";var tc=U(),Hv=we(),Zs="<<",ec={identify:e=>e===Zs||typeof e=="symbol"&&e.description===Zs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Hv.Scalar(Symbol(Zs)),{addToJSMap:Dv}),stringify:()=>Zs},Fx=(e,t)=>(ec.identify(t)||tc.isScalar(t)&&(!t.type||t.type===Hv.Scalar.PLAIN)&&ec.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===ec.tag&&r.default);function Dv(e,t,r){let i=Bv(e,r);if(tc.isSeq(i))for(let n of i.items)wd(e,t,n);else if(Array.isArray(i))for(let n of i)wd(e,t,n);else wd(e,t,i)}function wd(e,t,r){let i=Bv(e,r);if(!tc.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 Bv(e,t){return e&&tc.isAlias(t)?t.resolve(e.doc,e):t}rc.addMergeToJSMap=Dv;rc.isMergeKey=Fx;rc.merge=ec});var bd=R(qv=>{"use strict";var qx=gd(),Lv=ic(),Mx=_a(),Fv=U(),yd=Hr();function Vx(e,t,{key:r,value:i}){if(Fv.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(Lv.isMergeKey(e,r))Lv.addMergeToJSMap(e,t,i);else{let n=yd.toJS(r,"",e);if(t instanceof Map)t.set(n,yd.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=Wx(r,n,e),o=yd.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 Wx(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Fv.isNode(e)&&r?.doc){let i=Mx.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)+'..."'),qx.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)}qv.addPairToJSMap=Vx});var Fr=R(Nd=>{"use strict";var Mv=Ea(),zx=jv(),Gx=bd(),nc=U();function Jx(e,t,r){let i=Mv.createNode(e,void 0,r),n=Mv.createNode(t,void 0,r);return new ac(i,n)}var ac=class e{constructor(t,r=null){Object.defineProperty(this,nc.NODE_TYPE,{value:nc.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return nc.isNode(r)&&(r=r.clone(t)),nc.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return Gx.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?zx.stringifyPair(this,t,r,i):JSON.stringify(this)}};Nd.Pair=ac;Nd.createPair=Jx});var kd=R(Wv=>{"use strict";var yi=U(),Vv=_a(),oc=xa();function Ux(e,t,r){return(t.inFlow??e.flow?Yx:Kx)(e,t,r)}function Kx({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}),p=!1,d=[];for(let h=0;h<t.length;++h){let m=t[h],v=null;if(yi.isNode(m))!p&&m.spaceBefore&&d.push(""),sc(r,d,m.commentBefore,p),m.comment&&(v=m.comment);else if(yi.isPair(m)){let w=yi.isNode(m.key)?m.key:null;w&&(!p&&w.spaceBefore&&d.push(""),sc(r,d,w.commentBefore,p))}p=!1;let g=Vv.stringify(m,u,()=>v=null,()=>p=!0);v&&(g+=oc.lineComment(g,a,l(v))),p&&v&&(p=!1),d.push(i+g)}let f;if(d.length===0)f=n.start+n.end;else{f=d[0];for(let h=1;h<d.length;++h){let m=d[h];f+=m?`
|
|
48
48
|
${c}${m}`:`
|
|
49
|
-
`}}return e?(
|
|
50
|
-
`+
|
|
51
|
-
`)),
|
|
49
|
+
`}}return e?(f+=`
|
|
50
|
+
`+oc.indentComment(l(e),c),s&&s()):p&&o&&o(),f}function Yx({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,p=[];for(let h=0;h<e.length;++h){let m=e[h],v=null;if(yi.isNode(m))m.spaceBefore&&p.push(""),sc(t,p,m.commentBefore,!1),m.comment&&(v=m.comment);else if(yi.isPair(m)){let w=yi.isNode(m.key)?m.key:null;w&&(w.spaceBefore&&p.push(""),sc(t,p,w.commentBefore,!1),w.comment&&(l=!0));let N=yi.isNode(m.value)?m.value:null;N?(N.comment&&(v=N.comment),N.commentBefore&&(l=!0)):m.value==null&&w?.comment&&(v=w.comment)}v&&(l=!0);let g=Vv.stringify(m,c,()=>v=null);l||(l=p.length>u||g.includes(`
|
|
51
|
+
`)),h<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=p.reduce((w,N)=>w+N.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=oc.lineComment(g,i,s(v))),p.push(g),u=p.length}let{start:d,end:f}=r;if(p.length===0)return d+f;if(!l){let h=p.reduce((m,v)=>m+v.length+2,2);l=t.options.lineWidth>0&&h>t.options.lineWidth}if(l){let h=d;for(let m of p)h+=m?`
|
|
52
52
|
${a}${n}${m}`:`
|
|
53
|
-
`;return`${
|
|
54
|
-
${n}${
|
|
55
|
-
`:" ")}return
|
|
53
|
+
`;return`${h}
|
|
54
|
+
${n}${f}`}else return`${d}${o}${p.join(" ")}${o}${f}`}function sc({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=oc.indentComment(t(i),e);r.push(a.trimStart())}}Wv.stringifyCollection=Ux});var Mr=R(Ed=>{"use strict";var Xx=kd(),Qx=bd(),Zx=Js(),qr=U(),cc=Fr(),eR=we();function Ia(e,t){let r=qr.isScalar(t)?t.value:t;for(let i of e)if(qr.isPair(i)&&(i.key===t||i.key===r||qr.isScalar(i.key)&&i.key.value===r))return i}var Sd=class extends Zx.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(qr.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(cc.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;qr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new cc.Pair(t,t?.value):i=new cc.Pair(t.key,t.value);let n=Ia(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);qr.isScalar(n.value)&&eR.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=Ia(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=Ia(this.items,t)?.value;return(!r&&qr.isScalar(n)?n.value:n)??void 0}has(t){return!!Ia(this.items,t)}set(t,r){this.add(new cc.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)Qx.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!qr.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})),Xx.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Ed.YAMLMap=Sd;Ed.findPair=Ia});var pn=R(Gv=>{"use strict";var tR=U(),zv=Mr(),rR={collection:"map",default:!0,nodeClass:zv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return tR.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>zv.YAMLMap.from(e,t,r)};Gv.map=rR});var Vr=R(Jv=>{"use strict";var iR=Ea(),nR=kd(),aR=Js(),uc=U(),oR=we(),sR=Hr(),xd=class extends aR.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(uc.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=lc(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=lc(t);if(typeof i!="number")return;let n=this.items[i];return!r&&uc.isScalar(n)?n.value:n}has(t){let r=lc(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=lc(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];uc.isScalar(n)&&oR.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(sR.toJS(a,String(n++),r));return i}toString(t,r,i){return t?nR.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(iR.createNode(s,void 0,i))}}return a}};function lc(e){let t=uc.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Jv.YAMLSeq=xd});var fn=R(Kv=>{"use strict";var cR=U(),Uv=Vr(),lR={collection:"seq",default:!0,nodeClass:Uv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return cR.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Uv.YAMLSeq.from(e,t,r)};Kv.seq=lR});var Ta=R(Yv=>{"use strict";var uR=Pa(),dR={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),uR.stringifyString(e,t,r,i)}};Yv.string=dR});var dc=R(Zv=>{"use strict";var Xv=we(),Qv={identify:e=>e==null,createNode:()=>new Xv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Xv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Qv.test.test(e)?e:t.options.nullStr};Zv.nullTag=Qv});var Rd=R(tg=>{"use strict";var pR=we(),eg={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new pR.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&eg.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};tg.boolTag=eg});var hn=R(rg=>{"use strict";function fR({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}rg.stringifyNumber=fR});var Pd=R(pc=>{"use strict";var hR=we(),Cd=hn(),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:Cd.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),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Cd.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)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Cd.stringifyNumber};pc.float=gR;pc.floatExp=vR;pc.floatNaN=mR});var Ad=R(hc=>{"use strict";var ig=hn(),fc=e=>typeof e=="bigint"||Number.isInteger(e),_d=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function ng(e,t,r){let{value:i}=e;return fc(i)&&i>=0?r+i.toString(t):ig.stringifyNumber(e)}var wR={identify:e=>fc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>_d(e,2,8,r),stringify:e=>ng(e,8,"0o")},yR={identify:fc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>_d(e,0,10,r),stringify:ig.stringifyNumber},bR={identify:e=>fc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>_d(e,2,16,r),stringify:e=>ng(e,16,"0x")};hc.int=yR;hc.intHex=bR;hc.intOct=wR});var og=R(ag=>{"use strict";var NR=pn(),kR=dc(),SR=fn(),ER=Ta(),xR=Rd(),Id=Pd(),Td=Ad(),RR=[NR.map,SR.seq,ER.string,kR.nullTag,xR.boolTag,Td.intOct,Td.int,Td.intHex,Id.floatNaN,Id.floatExp,Id.float];ag.schema=RR});var lg=R(cg=>{"use strict";var CR=we(),PR=pn(),_R=fn();function sg(e){return typeof e=="bigint"||Number.isInteger(e)}var mc=({value:e})=>JSON.stringify(e),AR=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:mc},{identify:e=>e==null,createNode:()=>new CR.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:mc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:mc},{identify:sg,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})=>sg(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:mc}],IR={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},TR=[PR.map,_R.seq].concat(AR,IR);cg.schema=TR});var jd=R(ug=>{"use strict";var $a=Bs("buffer"),$d=we(),$R=Pa(),jR={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof $a.Buffer=="function")return $a.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 $a.Buffer=="function")s=o instanceof $a.Buffer?o.toString("base64"):$a.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=$d.Scalar.BLOCK_LITERAL),t!==$d.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 p=0,d=0;p<l;++p,d+=c)u[p]=s.substr(d,c);s=u.join(t===$d.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return $R.stringifyString({comment:e,type:t,value:s},i,n,a)}};ug.binary=jR});var wc=R(gc=>{"use strict";var vc=U(),Od=Fr(),OR=we(),HR=Vr();function dg(e,t){if(vc.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!vc.isPair(i)){if(vc.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new Od.Pair(new OR.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
|
|
56
56
|
${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
|
|
57
|
-
${a.comment}`:i.comment}i=n}e.items[r]=hc.isPair(i)?i:new $d.Pair(i)}}else t("Expected a sequence for this tag");return e}function sg(e,t,r){let{replacer:i}=r,n=new RR.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($d.createPair(s,c,r))}return n}var CR={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:og,createNode:sg};fc.createPairs=sg;fc.pairs=CR;fc.resolvePairs=og});var Hd=R(Od=>{"use strict";var cg=U(),jd=Hr(),$a=Mr(),PR=Vr(),lg=mc(),bi=class e extends PR.YAMLSeq{constructor(){super(),this.add=$a.YAMLMap.prototype.add.bind(this),this.delete=$a.YAMLMap.prototype.delete.bind(this),this.get=$a.YAMLMap.prototype.get.bind(this),this.has=$a.YAMLMap.prototype.has.bind(this),this.set=$a.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(cg.isPair(n)?(a=jd.toJS(n.key,"",r),o=jd.toJS(n.value,a,r)):a=jd.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=lg.createPairs(t,r,i),a=new this;return a.items=n.items,a}};bi.tag="tag:yaml.org,2002:omap";var _R={collection:"seq",identify:e=>e instanceof Map,nodeClass:bi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=lg.resolvePairs(e,t),i=[];for(let{key:n}of r.items)cg.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new bi,r)},createNode:(e,t,r)=>bi.from(e,t,r)};Od.YAMLOMap=bi;Od.omap=_R});var fg=R(Dd=>{"use strict";var ug=we();function dg({value:e,source:t},r){return t&&(e?pg:hg).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var pg={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 ug.Scalar(!0),stringify:dg},hg={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 ug.Scalar(!1),stringify:dg};Dd.falseTag=hg;Dd.trueTag=pg});var mg=R(vc=>{"use strict";var AR=we(),Bd=hn(),IR={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:Bd.stringifyNumber},TR={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():Bd.stringifyNumber(e)}},$R={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 AR.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:Bd.stringifyNumber};vc.float=$R;vc.floatExp=TR;vc.floatNaN=IR});var gg=R(Oa=>{"use strict";var vg=hn(),ja=e=>typeof e=="bigint"||Number.isInteger(e);function gc(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 Ld(e,t,r){let{value:i}=e;if(ja(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return vg.stringifyNumber(e)}var jR={identify:ja,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>gc(e,2,2,r),stringify:e=>Ld(e,2,"0b")},OR={identify:ja,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>gc(e,1,8,r),stringify:e=>Ld(e,8,"0")},HR={identify:ja,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>gc(e,0,10,r),stringify:vg.stringifyNumber},DR={identify:ja,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>gc(e,2,16,r),stringify:e=>Ld(e,16,"0x")};Oa.int=HR;Oa.intBin=jR;Oa.intHex=DR;Oa.intOct=OR});var Fd=R(qd=>{"use strict";var bc=U(),wc=qr(),yc=Mr(),Ni=class e extends yc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;bc.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new wc.Pair(t.key,null):r=new wc.Pair(t,null),yc.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=yc.findPair(this.items,t);return!r&&bc.isPair(i)?bc.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=yc.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new wc.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(wc.createPair(o,null,i));return a}};Ni.tag="tag:yaml.org,2002:set";var BR={collection:"map",identify:e=>e instanceof Set,nodeClass:Ni,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Ni.from(e,t,r),resolve(e,t){if(bc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Ni,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};qd.YAMLSet=Ni;qd.set=BR});var Vd=R(Nc=>{"use strict";var LR=hn();function Md(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 wg(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return LR.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 qR={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})=>Md(e,r),stringify:wg},FR={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=>Md(e,!1),stringify:wg},yg={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(yg.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=Md(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$/,"")??""};Nc.floatTime=FR;Nc.intTime=qR;Nc.timestamp=yg});var kg=R(Ng=>{"use strict";var MR=dn(),VR=cc(),WR=pn(),zR=Ia(),GR=Td(),bg=fg(),Wd=mg(),kc=gg(),JR=ec(),UR=Hd(),KR=mc(),YR=Fd(),zd=Vd(),XR=[MR.map,WR.seq,zR.string,VR.nullTag,bg.trueTag,bg.falseTag,kc.intBin,kc.intOct,kc.int,kc.intHex,Wd.floatNaN,Wd.floatExp,Wd.float,GR.binary,JR.merge,UR.omap,KR.pairs,YR.set,zd.intTime,zd.floatTime,zd.timestamp];Ng.schema=XR});var Tg=R(Ud=>{"use strict";var Rg=dn(),QR=cc(),Cg=pn(),ZR=Ia(),eC=Ed(),Gd=Rd(),Jd=Pd(),tC=tg(),rC=ng(),Pg=Td(),Ha=ec(),_g=Hd(),Ag=mc(),Sg=kg(),Ig=Fd(),Sc=Vd(),Eg=new Map([["core",tC.schema],["failsafe",[Rg.map,Cg.seq,ZR.string]],["json",rC.schema],["yaml11",Sg.schema],["yaml-1.1",Sg.schema]]),xg={binary:Pg.binary,bool:eC.boolTag,float:Gd.float,floatExp:Gd.floatExp,floatNaN:Gd.floatNaN,floatTime:Sc.floatTime,int:Jd.int,intHex:Jd.intHex,intOct:Jd.intOct,intTime:Sc.intTime,map:Rg.map,merge:Ha.merge,null:QR.nullTag,omap:_g.omap,pairs:Ag.pairs,seq:Cg.seq,set:Ig.set,timestamp:Sc.timestamp},iC={"tag:yaml.org,2002:binary":Pg.binary,"tag:yaml.org,2002:merge":Ha.merge,"tag:yaml.org,2002:omap":_g.omap,"tag:yaml.org,2002:pairs":Ag.pairs,"tag:yaml.org,2002:set":Ig.set,"tag:yaml.org,2002:timestamp":Sc.timestamp};function nC(e,t,r){let i=Eg.get(t);if(i&&!e)return r&&!i.includes(Ha.merge)?i.concat(Ha.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Eg.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(Ha.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?xg[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(xg).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},[])}Ud.coreKnownTags=iC;Ud.getTags=nC});var Xd=R($g=>{"use strict";var Kd=U(),aC=dn(),oC=pn(),sC=Ia(),Ec=Tg(),cC=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Yd=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Ec.getTags(t,"compat"):t?Ec.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ec.coreKnownTags:{},this.tags=Ec.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Kd.MAP,{value:aC.map}),Object.defineProperty(this,Kd.SCALAR,{value:sC.string}),Object.defineProperty(this,Kd.SEQ,{value:oC.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?cC:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};$g.Schema=Yd});var Og=R(jg=>{"use strict";var lC=U(),Qd=Pa(),Da=Ea();function uC(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=Qd.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Da.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(lC.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Da.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Qd.stringify(e.contents,n,()=>s=null,c);s&&(l+=Da.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Qd.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
-
`)?(r.push("..."),r.push(
|
|
57
|
+
${a.comment}`:i.comment}i=n}e.items[r]=vc.isPair(i)?i:new Od.Pair(i)}}else t("Expected a sequence for this tag");return e}function pg(e,t,r){let{replacer:i}=r,n=new HR.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(Od.createPair(s,c,r))}return n}var DR={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:dg,createNode:pg};gc.createPairs=pg;gc.pairs=DR;gc.resolvePairs=dg});var Bd=R(Dd=>{"use strict";var fg=U(),Hd=Hr(),ja=Mr(),BR=Vr(),hg=wc(),bi=class e extends BR.YAMLSeq{constructor(){super(),this.add=ja.YAMLMap.prototype.add.bind(this),this.delete=ja.YAMLMap.prototype.delete.bind(this),this.get=ja.YAMLMap.prototype.get.bind(this),this.has=ja.YAMLMap.prototype.has.bind(this),this.set=ja.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(fg.isPair(n)?(a=Hd.toJS(n.key,"",r),o=Hd.toJS(n.value,a,r)):a=Hd.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=hg.createPairs(t,r,i),a=new this;return a.items=n.items,a}};bi.tag="tag:yaml.org,2002:omap";var LR={collection:"seq",identify:e=>e instanceof Map,nodeClass:bi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=hg.resolvePairs(e,t),i=[];for(let{key:n}of r.items)fg.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new bi,r)},createNode:(e,t,r)=>bi.from(e,t,r)};Dd.YAMLOMap=bi;Dd.omap=LR});var yg=R(Ld=>{"use strict";var mg=we();function vg({value:e,source:t},r){return t&&(e?gg:wg).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var gg={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 mg.Scalar(!0),stringify:vg},wg={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 mg.Scalar(!1),stringify:vg};Ld.falseTag=wg;Ld.trueTag=gg});var bg=R(yc=>{"use strict";var FR=we(),Fd=hn(),qR={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:Fd.stringifyNumber},MR={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():Fd.stringifyNumber(e)}},VR={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 FR.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:Fd.stringifyNumber};yc.float=VR;yc.floatExp=MR;yc.floatNaN=qR});var kg=R(Ha=>{"use strict";var Ng=hn(),Oa=e=>typeof e=="bigint"||Number.isInteger(e);function bc(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 qd(e,t,r){let{value:i}=e;if(Oa(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Ng.stringifyNumber(e)}var WR={identify:Oa,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>bc(e,2,2,r),stringify:e=>qd(e,2,"0b")},zR={identify:Oa,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>bc(e,1,8,r),stringify:e=>qd(e,8,"0")},GR={identify:Oa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>bc(e,0,10,r),stringify:Ng.stringifyNumber},JR={identify:Oa,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>bc(e,2,16,r),stringify:e=>qd(e,16,"0x")};Ha.int=GR;Ha.intBin=WR;Ha.intHex=JR;Ha.intOct=zR});var Vd=R(Md=>{"use strict";var Sc=U(),Nc=Fr(),kc=Mr(),Ni=class e extends kc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Sc.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Nc.Pair(t.key,null):r=new Nc.Pair(t,null),kc.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=kc.findPair(this.items,t);return!r&&Sc.isPair(i)?Sc.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=kc.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Nc.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(Nc.createPair(o,null,i));return a}};Ni.tag="tag:yaml.org,2002:set";var UR={collection:"map",identify:e=>e instanceof Set,nodeClass:Ni,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Ni.from(e,t,r),resolve(e,t){if(Sc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Ni,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Md.YAMLSet=Ni;Md.set=UR});var zd=R(Ec=>{"use strict";var KR=hn();function Wd(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 Sg(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return KR.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 YR={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})=>Wd(e,r),stringify:Sg},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=>Wd(e,!1),stringify:Sg},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 p=Wd(u,!1);Math.abs(p)<30&&(p*=60),l-=6e4*p}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Ec.floatTime=XR;Ec.intTime=YR;Ec.timestamp=Eg});var Cg=R(Rg=>{"use strict";var QR=pn(),ZR=dc(),eC=fn(),tC=Ta(),rC=jd(),xg=yg(),Gd=bg(),xc=kg(),iC=ic(),nC=Bd(),aC=wc(),oC=Vd(),Jd=zd(),sC=[QR.map,eC.seq,tC.string,ZR.nullTag,xg.trueTag,xg.falseTag,xc.intBin,xc.intOct,xc.int,xc.intHex,Gd.floatNaN,Gd.floatExp,Gd.float,rC.binary,iC.merge,nC.omap,aC.pairs,oC.set,Jd.intTime,Jd.floatTime,Jd.timestamp];Rg.schema=sC});var Dg=R(Yd=>{"use strict";var Ig=pn(),cC=dc(),Tg=fn(),lC=Ta(),uC=Rd(),Ud=Pd(),Kd=Ad(),dC=og(),pC=lg(),$g=jd(),Da=ic(),jg=Bd(),Og=wc(),Pg=Cg(),Hg=Vd(),Rc=zd(),_g=new Map([["core",dC.schema],["failsafe",[Ig.map,Tg.seq,lC.string]],["json",pC.schema],["yaml11",Pg.schema],["yaml-1.1",Pg.schema]]),Ag={binary:$g.binary,bool:uC.boolTag,float:Ud.float,floatExp:Ud.floatExp,floatNaN:Ud.floatNaN,floatTime:Rc.floatTime,int:Kd.int,intHex:Kd.intHex,intOct:Kd.intOct,intTime:Rc.intTime,map:Ig.map,merge:Da.merge,null:cC.nullTag,omap:jg.omap,pairs:Og.pairs,seq:Tg.seq,set:Hg.set,timestamp:Rc.timestamp},fC={"tag:yaml.org,2002:binary":$g.binary,"tag:yaml.org,2002:merge":Da.merge,"tag:yaml.org,2002:omap":jg.omap,"tag:yaml.org,2002:pairs":Og.pairs,"tag:yaml.org,2002:set":Hg.set,"tag:yaml.org,2002:timestamp":Rc.timestamp};function hC(e,t,r){let i=_g.get(t);if(i&&!e)return r&&!i.includes(Da.merge)?i.concat(Da.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(_g.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(Da.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Ag[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Ag).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=fC;Yd.getTags=hC});var Zd=R(Bg=>{"use strict";var Xd=U(),mC=pn(),vC=fn(),gC=Ta(),Cc=Dg(),wC=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Qd=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Cc.getTags(t,"compat"):t?Cc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Cc.coreKnownTags:{},this.tags=Cc.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Xd.MAP,{value:mC.map}),Object.defineProperty(this,Xd.SCALAR,{value:gC.string}),Object.defineProperty(this,Xd.SEQ,{value:vC.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?wC:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Bg.Schema=Qd});var Fg=R(Lg=>{"use strict";var yC=U(),ep=_a(),Ba=xa();function bC(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=ep.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Ba.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(yC.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Ba.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=ep.stringify(e.contents,n,()=>s=null,c);s&&(l+=Ba.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(ep.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
+
`)?(r.push("..."),r.push(Ba.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(Ba.indentComment(a(c),"")))}return r.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}Lg.stringifyDocument=bC});var La=R(qg=>{"use strict";var NC=Sa(),mn=Js(),ft=U(),kC=Fr(),SC=Hr(),EC=Zd(),xC=Fg(),tp=Vs(),RC=ad(),CC=Ea(),rp=nd(),ip=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ft.NODE_TYPE,{value:ft.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 rp.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,{[ft.NODE_TYPE]:{value:ft.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=ft.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){vn(this.contents)&&this.contents.add(t)}addIn(t,r){vn(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=tp.anchorNames(this);t.anchor=!r||i.has(r)?tp.findNewAnchor(r||"a",i):r}return new NC.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=w=>typeof w=="number"||w instanceof String||w 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:p,setAnchors:d,sourceObjects:f}=tp.createNodeAnchors(this,o||"a"),h={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:p,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:f},m=CC.createNode(t,u,h);return s&&ft.isCollection(m)&&(m.flow=!0),d(),m}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new kC.Pair(n,a)}delete(t){return vn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return mn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):vn(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return ft.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return mn.isEmptyPath(t)?!r&&ft.isScalar(this.contents)?this.contents.value:this.contents:ft.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return ft.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return mn.isEmptyPath(t)?this.contents!==void 0:ft.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=mn.collectionFromPath(this.schema,[t],r):vn(this.contents)&&this.contents.set(t,r)}setIn(t,r){mn.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=mn.collectionFromPath(this.schema,Array.from(t),r):vn(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 rp.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 rp.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 EC.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=SC.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"?RC.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 xC.stringifyDocument(this,t)}};function vn(e){if(ft.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}qg.Document=ip});var Ma=R(qa=>{"use strict";var Fa=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},np=class extends Fa{constructor(t,r,i){super("YAMLParseError",t,r,i)}},ap=class extends Fa{constructor(t,r,i){super("YAMLWarning",t,r,i)}},PC=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};qa.YAMLError=
|
|
66
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(
|
|
67
|
-
`+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||
|
|
68
|
-
`+N.comment:w.comment=N.comment);let y=new
|
|
69
|
-
`+b.comment:l.comment=b.comment),
|
|
70
|
-
`+x:k.comment=x,b.comment=b.comment.substring(x.length+1)}}if(!o&&!y&&!b.found){let x=E?e(r,E,b,n):t(r,b.end,y,null,b,n);l.items.push(x),
|
|
71
|
-
`+S.comment:k.comment=S.comment);let P=new
|
|
72
|
-
`+v.comment:l.comment=v.comment),l.range=[i.offset,m,v.offset]}else l.range=[i.offset,m,m];return l}
|
|
73
|
-
`.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return t.source&&(v+=t.source.length),{value:m,type:a,comment:n.comment,range:[i,v,v]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let m=0;m<s;++m){let[v,g]=o[m];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=m,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 m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let
|
|
74
|
-
`;for(let m=u;m<s;++m){let[v,g]=o[m];l+=v.length+g.length+1;let w=g[g.length-1]==="\r";if(w&&(g=g.slice(0,-1)),g&&v.length<c){let y=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(w?2:1),"BAD_INDENT",y),v=""}a===
|
|
75
|
-
`):v.length>c||g[0]===" "?(
|
|
76
|
-
`:!
|
|
77
|
-
`&&(
|
|
65
|
+
`}};qa.YAMLError=Fa;qa.YAMLParseError=np;qa.YAMLWarning=ap;qa.prettifyError=PC});var Va=R(Mg=>{"use strict";function _C(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,p="",d="",f=!1,h=!1,m=null,v=null,g=null,w=null,N=null,y=null,E=null;for(let k of e)switch(h&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&a(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h=!1),m&&(l&&k.type!=="comment"&&k.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),k.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&k.source.includes(" ")&&(m=k),u=!0;break;case"comment":{u||a(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let S=k.source.substring(1)||" ";p?p+=d+S:p=S,d="",l=!1;break}case"newline":l?p?p+=k.source:(!y||r!=="seq-item-ind")&&(c=!0):d+=k.source,l=!0,f=!0,(v||g)&&(w=k),u=!0;break;case"anchor":v&&a(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&a(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=k,E??(E=k.offset),l=!1,u=!1,h=!0;break;case"tag":{g&&a(k,"MULTIPLE_TAGS","A node can have at most one tag"),g=k,E??(E=k.offset),l=!1,u=!1,h=!0;break}case r:(v||g)&&a(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),y&&a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${t??"collection"}`),y=k,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){N&&a(k,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=k,l=!1,u=!1;break}default:a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,u=!1}let b=e[e.length-1],x=b?b.offset+b.source.length:n;return h&&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"),m&&(l&&m.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:N,found:y,spaceBefore:c,comment:p,hasNewline:f,anchor:v,tag:g,newlineAfterProp:w,end:x,start:E??x}}Mg.resolveProps=_C});var Pc=R(Vg=>{"use strict";function op(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(op(t.key)||op(t.value))return!0}return!1;default:return!0}}Vg.containsNewline=op});var sp=R(Wg=>{"use strict";var AC=Pc();function IC(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&AC.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Wg.flowIndentCheck=IC});var cp=R(Gg=>{"use strict";var zg=U();function TC(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||zg.isScalar(a)&&zg.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}Gg.mapIncludes=TC});var Qg=R(Xg=>{"use strict";var Jg=Fr(),$C=Mr(),Ug=Va(),jC=Pc(),Kg=sp(),OC=cp(),Yg="All mapping items must start at the same column";function HC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??$C.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:p,key:d,sep:f,value:h}=u,m=Ug.resolveProps(p,{indicator:"explicit-key-ind",next:d??f?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!m.found;if(v){if(d&&(d.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&n(c,"BAD_INDENT",Yg)),!m.anchor&&!m.tag&&!f){l=m.end,m.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||jC.containsNewline(d))&&n(d??p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==i.indent&&n(c,"BAD_INDENT",Yg);r.atKey=!0;let g=m.end,w=d?e(r,d,m,n):t(r,g,p,null,m,n);r.schema.compat&&Kg.flowIndentCheck(i.indent,d,n),r.atKey=!1,OC.mapIncludes(r,s.items,w)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let N=Ug.resolveProps(f??[],{indicator:"map-value-ind",next:h,offset:w.range[2],onError:n,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=N.end,N.found){v&&(h?.type==="block-map"&&!N.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&m.start<N.found.offset-1024&&n(w.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let y=h?e(r,h,N,n):t(r,c,f,null,N,n);r.schema.compat&&Kg.flowIndentCheck(i.indent,h,n),c=y.range[2];let E=new Jg.Pair(w,y);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{v&&n(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),N.comment&&(w.comment?w.comment+=`
|
|
68
|
+
`+N.comment:w.comment=N.comment);let y=new Jg.Pair(w);r.options.keepSourceTokens&&(y.srcToken=u),s.items.push(y)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Xg.resolveBlockMap=HC});var ew=R(Zg=>{"use strict";var DC=Vr(),BC=Va(),LC=sp();function FC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??DC.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:p}of i.items){let d=BC.resolveProps(u,{indicator:"seq-item-ind",next:p,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||p)p?.type==="block-seq"?n(d.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let f=p?e(r,p,d,n):t(r,d.end,u,null,d,n);r.schema.compat&&LC.flowIndentCheck(i.indent,p,n),c=f.range[2],s.items.push(f)}return s.range=[i.offset,c,l??c],s}Zg.resolveBlockSeq=FC});var gn=R(tw=>{"use strict";function qC(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}}tw.resolveEnd=qC});var aw=R(nw=>{"use strict";var MC=U(),VC=Fr(),rw=Mr(),WC=Vr(),zC=gn(),iw=Va(),GC=Pc(),JC=cp(),lp="Block collections are not allowed within flow collections",up=e=>e&&(e.type==="block-map"||e.type==="block-seq");function UC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?rw.YAMLMap:WC.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let p=i.offset+i.start.source.length;for(let v=0;v<i.items.length;++v){let g=i.items[v],{start:w,key:N,sep:y,value:E}=g,b=iw.resolveProps(w,{flow:s,indicator:"explicit-key-ind",next:N??y?.[0],offset:p,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!y&&!E){v===0&&b.comma?n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<i.items.length-1&&n(b.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),b.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+b.comment:l.comment=b.comment),p=b.end;continue}!o&&r.options.strict&&GC.containsNewline(N)&&n(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)b.comma&&n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(b.comma||n(b.start,"MISSING_CHAR",`Missing , between ${s} items`),b.comment){let x="";e:for(let k of w)switch(k.type){case"comma":case"space":break;case"comment":x=k.source.substring(1);break e;default:break e}if(x){let k=l.items[l.items.length-1];MC.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
|
|
70
|
+
`+x:k.comment=x,b.comment=b.comment.substring(x.length+1)}}if(!o&&!y&&!b.found){let x=E?e(r,E,b,n):t(r,b.end,y,null,b,n);l.items.push(x),p=x.range[2],up(E)&&n(x.range,"BLOCK_IN_FLOW",lp)}else{r.atKey=!0;let x=b.end,k=N?e(r,N,b,n):t(r,x,w,null,b,n);up(N)&&n(k.range,"BLOCK_IN_FLOW",lp),r.atKey=!1;let S=iw.resolveProps(y??[],{flow:s,indicator:"map-value-ind",next:E,offset:k.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(S.found){if(!o&&!b.found&&r.options.strict){if(y)for(let _ of y){if(_===S.found)break;if(_.type==="newline"){n(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.start<S.found.offset-1024&&n(S.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(S.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=E?e(r,E,S,n):S.found?t(r,S.end,y,null,S,n):null;C?up(E)&&n(C.range,"BLOCK_IN_FLOW",lp):S.comment&&(k.comment?k.comment+=`
|
|
71
|
+
`+S.comment:k.comment=S.comment);let P=new VC.Pair(k,C);if(r.options.keepSourceTokens&&(P.srcToken=g),o){let _=l;JC.mapIncludes(r,_.items,k)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),_.items.push(P)}else{let _=new rw.YAMLMap(r.schema);_.flow=!0,_.items.push(P);let j=(C??k).range;_.range=[k.range[0],j[1],j[2]],l.items.push(_)}p=C?C.range[2]:S.end}}let d=o?"}":"]",[f,...h]=i.end,m=p;if(f?.source===d)m=f.offset+f.source.length;else{let v=s[0].toUpperCase()+s.substring(1),g=u?`${v} must end with a ${d}`:`${v} in block collection must be sufficiently indented and end with a ${d}`;n(p,u?"MISSING_CHAR":"BAD_INDENT",g),f&&f.source.length!==1&&h.unshift(f)}if(h.length>0){let v=zC.resolveEnd(h,m,r.options.strict,n);v.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+v.comment:l.comment=v.comment),l.range=[i.offset,m,v.offset]}else l.range=[i.offset,m,m];return l}nw.resolveFlowCollection=UC});var sw=R(ow=>{"use strict";var KC=U(),YC=we(),XC=Mr(),QC=Vr(),ZC=Qg(),eP=ew(),tP=aw();function dp(e,t,r,i,n,a){let o=r.type==="block-map"?ZC.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?eP.resolveBlockSeq(e,t,r,i,a):tP.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 rP(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,d=>n(a,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:f}=i,h=d&&a?d.offset>a.offset?d:a:d??a;h&&(!f||f.offset<h.offset)&&n(h,"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===XC.YAMLMap.tagName&&s==="map"||o===QC.YAMLSeq.tagName&&s==="seq")return dp(e,t,r,n,o);let c=t.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=t.schema.knownTags[o];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?n(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),dp(e,t,r,n,o)}let l=dp(e,t,r,n,o,c),u=c.resolve?.(l,d=>n(a,"TAG_RESOLVE_FAILED",d),t.options)??l,p=KC.isNode(u)?u:new YC.Scalar(u);return p.range=l.range,p.tag=o,c?.format&&(p.format=c.format),p}ow.composeCollection=rP});var fp=R(cw=>{"use strict";var pp=we();function iP(e,t,r){let i=t.offset,n=nP(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?pp.Scalar.BLOCK_FOLDED:pp.Scalar.BLOCK_LITERAL,o=t.source?aP(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let v=o[m][1];if(v===""||v==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return t.source&&(v+=t.source.length),{value:m,type:a,comment:n.comment,range:[i,v,v]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let m=0;m<s;++m){let[v,g]=o[m];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=m,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 m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let p="",d="",f=!1;for(let m=0;m<u;++m)p+=o[m][0].slice(c)+`
|
|
74
|
+
`;for(let m=u;m<s;++m){let[v,g]=o[m];l+=v.length+g.length+1;let w=g[g.length-1]==="\r";if(w&&(g=g.slice(0,-1)),g&&v.length<c){let y=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(w?2:1),"BAD_INDENT",y),v=""}a===pp.Scalar.BLOCK_LITERAL?(p+=d+v.slice(c)+g,d=`
|
|
75
|
+
`):v.length>c||g[0]===" "?(d===" "?d=`
|
|
76
|
+
`:!f&&d===`
|
|
77
|
+
`&&(d=`
|
|
78
78
|
|
|
79
|
-
`),d
|
|
80
|
-
`,
|
|
81
|
-
`?
|
|
82
|
-
`:
|
|
83
|
-
`:(d
|
|
84
|
-
`+o[m][0].slice(c);
|
|
85
|
-
`&&(
|
|
86
|
-
`);break;default:
|
|
87
|
-
`}let
|
|
79
|
+
`),p+=d+v.slice(c)+g,d=`
|
|
80
|
+
`,f=!0):g===""?d===`
|
|
81
|
+
`?p+=`
|
|
82
|
+
`:d=`
|
|
83
|
+
`:(p+=d+g,d=" ",f=!1)}switch(n.chomp){case"-":break;case"+":for(let m=s;m<o.length;++m)p+=`
|
|
84
|
+
`+o[m][0].slice(c);p[p.length-1]!==`
|
|
85
|
+
`&&(p+=`
|
|
86
|
+
`);break;default:p+=`
|
|
87
|
+
`}let h=i+n.length+t.source.length;return{value:p,type:a,comment:n.comment,range:[i,h,h]}}function nP({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let d=1;d<n.length;++d){let f=n[d];if(!s&&(f==="-"||f==="+"))s=f;else{let h=Number(f);!o&&h?o=h:c===-1&&(c=e+d)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",p=n.length;for(let d=1;d<t.length;++d){let f=t[d];switch(f.type){case"space":l=!0;case"newline":p+=f.source.length;break;case"comment":r&&!l&&i(f,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),p+=f.source.length,u=f.source.substring(1);break;case"error":i(f,"UNEXPECTED_TOKEN",f.message),p+=f.source.length;break;default:{let h=`Unexpected token in block scalar header: ${f.type}`;i(f,"UNEXPECTED_TOKEN",h);let m=f.source;m&&typeof m=="string"&&(p+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:p}}function aP(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}cw.resolveBlockScalar=iP});var mp=R(uw=>{"use strict";var hp=we(),oP=gn();function sP(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(d,f,h)=>r(i+d,f,h);switch(n){case"scalar":s=hp.Scalar.PLAIN,c=cP(a,l);break;case"single-quoted-scalar":s=hp.Scalar.QUOTE_SINGLE,c=lP(a,l);break;case"double-quoted-scalar":s=hp.Scalar.QUOTE_DOUBLE,c=uP(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,p=oP.resolveEnd(o,u,t,r);return{value:c,type:s,comment:p.comment,range:[i,u,p.offset]}}function cP(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}`),lw(e)}function lP(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),lw(e.slice(1,-1)).replace(/''/g,"'")}function lw(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
89
|
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let n=i[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;i=r.exec(e);)i[1]===""?a===`
|
|
90
90
|
`?n+=a:a=`
|
|
91
|
-
`:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function
|
|
91
|
+
`:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function uP(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
|
|
92
92
|
`))if(n===`
|
|
93
|
-
`){let{fold:a,offset:o}=
|
|
93
|
+
`){let{fold:a,offset:o}=dP(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=pP[a];if(o)r+=o;else if(a===`
|
|
94
94
|
`)for(a=e[i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="\r"&&e[i+1]===`
|
|
95
|
-
`)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=
|
|
95
|
+
`)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=fP(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
|
|
96
96
|
`&&!(o==="\r"&&e[i+2]===`
|
|
97
|
-
`)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function
|
|
97
|
+
`)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function dP(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
|
|
98
98
|
`||i==="\r")&&!(i==="\r"&&e[t+2]!==`
|
|
99
99
|
`);)i===`
|
|
100
100
|
`&&(r+=`
|
|
101
|
-
`),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var pP={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function fP(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}}uw.resolveFlowScalar=sP});var fw=R(pw=>{"use strict";var ki=U(),dw=we(),hP=fp(),mP=mp();function vP(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?hP.resolveBlockScalar(e,t,i):mP.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,p=>i(r,"TAG_RESOLVE_FAILED",p)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[ki.SCALAR]:c?l=gP(e.schema,n,c,r,i):t.type==="scalar"?l=wP(e,n,t,i):l=e.schema[ki.SCALAR];let u;try{let p=l.resolve(n,d=>i(r??t,"TAG_RESOLVE_FAILED",d),e.options);u=ki.isScalar(p)?p:new dw.Scalar(p)}catch(p){let d=p instanceof Error?p.message:String(p);i(r??t,"TAG_RESOLVE_FAILED",d),u=new dw.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 gP(e,t,r,i,n){if(r==="!")return e[ki.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[ki.SCALAR])}function wP({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[ki.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[ki.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}pw.composeScalar=vP});var mw=R(hw=>{"use strict";function yP(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}hw.emptyScalarPosition=yP});var ww=R(gp=>{"use strict";var bP=Sa(),NP=U(),kP=sw(),vw=fw(),SP=gn(),EP=mw(),xP={composeNode:gw,composeEmptyNode:vp};function gw(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=RP(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=vw.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=kP.composeCollection(xP,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(p){let d=p instanceof Error?p.message:String(p);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let p=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",p),u=!1}}return l??(l=vp(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&&(!NP.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 vp(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:EP.emptyScalarPosition(t,r,i),indent:-1,source:""},p=vw.composeScalar(e,u,s,l);return o&&(p.anchor=o.source.substring(1),p.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(p.spaceBefore=!0),a&&(p.comment=a,p.range[2]=c),p}function RP({options:e},{offset:t,source:r,end:i},n){let a=new bP.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=SP.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}gp.composeEmptyNode=vp;gp.composeNode=gw});var Nw=R(bw=>{"use strict";var CP=La(),yw=ww(),PP=gn(),_P=Va();function AP(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new CP.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=_P.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?yw.composeNode(l,n,u,o):yw.composeEmptyNode(l,u.end,i,null,u,o);let p=c.contents.range[2],d=PP.resolveEnd(a,p,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,p,d.offset],c}bw.composeDoc=AP});var yp=R(Ew=>{"use strict";var IP=Bs("process"),TP=nd(),$P=La(),Wa=Ma(),kw=U(),jP=Nw(),OP=gn();function za(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 Sw(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var
|
|
106
|
-
${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(
|
|
105
|
+
`)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var wp=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=za(r);a?this.warnings.push(new Wa.YAMLWarning(o,i,n)):this.errors.push(new Wa.YAMLParseError(o,i,n))},this.directives=new TP.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Sw(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(kw.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];kw.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
|
|
107
107
|
${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
|
|
108
|
-
${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
109
|
-
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new
|
|
108
|
+
${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Sw(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(IP.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=za(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=jP.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 Wa.YAMLParseError(za(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 Wa.YAMLParseError(za(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=OP.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
|
|
109
|
+
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Wa.YAMLParseError(za(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 $P.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=wp});var Cw=R(_c=>{"use strict";var HP=fp(),DP=mp(),BP=Ma(),xw=Pa();function LP(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 BP.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return DP.resolveFlowScalar(e,t,i);case"block-scalar":return HP.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function FP(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=xw.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
|
-
`),u=s.substring(0,l),
|
|
112
|
-
`,
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:i,props:
|
|
111
|
+
`),u=s.substring(0,l),p=s.substring(l+1)+`
|
|
112
|
+
`,d=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return Rw(d,c)||d.push({type:"newline",offset:-1,indent:i,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:i,props:d,source:p}}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 qP(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=xw.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">":MP(e,c);break;case'"':bp(e,c,"double-quoted-scalar");break;case"'":bp(e,c,"single-quoted-scalar");break;default:bp(e,c,"scalar")}}function MP(e,t){let r=t.indexOf(`
|
|
114
114
|
`),i=t.substring(0,r),n=t.substring(r+1)+`
|
|
115
|
-
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];
|
|
116
|
-
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function
|
|
117
|
-
`};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}
|
|
115
|
+
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];Rw(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function 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 bp(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}_c.createScalarToken=FP;_c.resolveAsScalar=LP;_c.setScalarValue=qP});var _w=R(Pw=>{"use strict";var VP=e=>"type"in e?Ic(e):Ac(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+=Ac(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Ac(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Ac(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 Ac({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}Pw.stringify=VP});var $w=R(Tw=>{"use strict";var Np=Symbol("break visit"),WP=Symbol("skip children"),Aw=Symbol("remove item");function Si(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Iw(Object.freeze([]),e,t)}Si.BREAK=Np;Si.SKIP=WP;Si.REMOVE=Aw;Si.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};Si.parentCollection=(e,t)=>{let r=Si.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 Iw(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=Iw(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Np)return Np;s===Aw&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}Tw.visit=Si});var Tc=R(Ve=>{"use strict";var kp=Cw(),zP=_w(),GP=$w(),Sp="\uFEFF",Ep="",xp="",Rp="",JP=e=>!!e&&"items"in e,UP=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function KP(e){switch(e){case Sp:return"<BOM>";case Ep:return"<DOC>";case xp:return"<FLOW_END>";case Rp:return"<SCALAR>";default:return JSON.stringify(e)}}function YP(e){switch(e){case Sp:return"byte-order-mark";case Ep:return"doc-mode";case xp:return"flow-error-end";case Rp:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
118
|
`:case`\r
|
|
119
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Ve.createScalarToken=
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
121
|
-
\r `),
|
|
119
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Ve.createScalarToken=kp.createScalarToken;Ve.resolveAsScalar=kp.resolveAsScalar;Ve.setScalarValue=kp.setScalarValue;Ve.stringify=zP.stringify;Ve.visit=GP.visit;Ve.BOM=Sp;Ve.DOCUMENT=Ep;Ve.FLOW_END=xp;Ve.SCALAR=Rp;Ve.isCollection=JP;Ve.isScalar=UP;Ve.prettyToken=KP;Ve.tokenType=YP});var _p=R(Ow=>{"use strict";var Ga=Tc();function Ct(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var jw=new Set("0123456789ABCDEFabcdef"),XP=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$c=new Set(",[]{}"),QP=new Set(` ,[]{}
|
|
121
|
+
\r `),Cp=e=>!e||QP.has(e),Pp=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
|
|
122
122
|
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
123
123
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
|
|
124
124
|
`||!n&&!this.atEnd)return t+i+1}return r===`
|
|
125
125
|
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Ct(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
126
|
-
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===
|
|
126
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Ga.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 Ga.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==="...")&&Ct(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&&!Ct(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===":")&&Ct(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(Cp),"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("..."))&&Ct(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Ga.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(Cp),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ct(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
|
|
127
127
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
|
|
128
128
|
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Ct(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
|
|
129
129
|
`:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
130
|
`)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
131
131
|
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
|
|
132
132
|
`;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
-
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield
|
|
133
|
+
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Ga.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(Ct(a)||t&&$c.has(a))break;r=i}else if(Ct(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(i+=1,n=`
|
|
135
|
-
`,a=this.buffer[i+1]):r=i),a==="#"||t
|
|
136
|
-
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t
|
|
135
|
+
`,a=this.buffer[i+1]):r=i),a==="#"||t&&$c.has(a))break;if(n===`
|
|
136
|
+
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&$c.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Ga.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(Cp),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Ct(i)||r&&$c.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(;!Ct(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(XP.has(r))r=this.buffer[++t];else if(r==="%"&&jw.has(this.buffer[t+1])&&jw.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
137
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Ow.Lexer=Pp});var Ip=R(Hw=>{"use strict";var Ap=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}}}};Hw.LineCounter=Ap});var $p=R(qw=>{"use strict";var ZP=Bs("process"),Dw=Tc(),e_=_p();function Wr(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function Bw(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 Fw(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 jc(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 wn(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 Oc(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 Lw(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Wr(t.start,"explicit-key-ind")&&!Wr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Fw(t.value)?t.value.end?Oc(t.value.end,t.sep):t.value.end=t.sep:Oc(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 e_.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,ZP.env.LOG_TOKENS&&console.log("|",Dw.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Dw.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"&&Lw(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&&Bw(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":{Bw(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=jc(this.peek(2)),i=wn(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
140
|
-
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){
|
|
140
|
+
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Oc(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(Wr(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(Fw(r.key)&&!Wr(r.sep,"newline")){let o=wn(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(Wr(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=wn(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]}):Wr(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&&!Wr(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)){Oc(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||Wr(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=jc(i),a=wn(n);Lw(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
142
|
-
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Ic(t),i=gn(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=Ic(t),i=gn(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())}}};Hw.Parser=Ap});var Fw=R(Ja=>{"use strict";var Dw=gp(),zP=Ba(),Ga=Fa(),GP=md(),JP=U(),UP=_p(),Bw=Ip();function Lw(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new UP.LineCounter||null,prettyErrors:t}}function KP(e,t={}){let{lineCounter:r,prettyErrors:i}=Lw(t),n=new Bw.Parser(r?.addNewLine),a=new Dw.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Ga.prettifyError(e,r)),s.warnings.forEach(Ga.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function qw(e,t={}){let{lineCounter:r,prettyErrors:i}=Lw(t),n=new Bw.Parser(r?.addNewLine),a=new Dw.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 Ga.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Ga.prettifyError(e,r)),o.warnings.forEach(Ga.prettifyError(e,r))),o}function YP(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=qw(e,r);if(!n)return null;if(n.warnings.forEach(a=>GP.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 XP(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 JP.isDocument(e)&&!i?e.toString(r):new zP.Document(e,i,r).toString(r)}Ja.parse=YP;Ja.parseAllDocuments=KP;Ja.parseDocument=qw;Ja.stringify=XP});var Gt=R(Q=>{"use strict";var QP=gp(),ZP=Ba(),e_=Xd(),Tp=Fa(),t_=ka(),zr=U(),r_=qr(),i_=we(),n_=Mr(),a_=Vr(),o_=_c(),s_=Cp(),c_=_p(),l_=Ip(),$c=Fw(),Mw=wa();Q.Composer=QP.Composer;Q.Document=ZP.Document;Q.Schema=e_.Schema;Q.YAMLError=Tp.YAMLError;Q.YAMLParseError=Tp.YAMLParseError;Q.YAMLWarning=Tp.YAMLWarning;Q.Alias=t_.Alias;Q.isAlias=zr.isAlias;Q.isCollection=zr.isCollection;Q.isDocument=zr.isDocument;Q.isMap=zr.isMap;Q.isNode=zr.isNode;Q.isPair=zr.isPair;Q.isScalar=zr.isScalar;Q.isSeq=zr.isSeq;Q.Pair=r_.Pair;Q.Scalar=i_.Scalar;Q.YAMLMap=n_.YAMLMap;Q.YAMLSeq=a_.YAMLSeq;Q.CST=o_;Q.Lexer=s_.Lexer;Q.LineCounter=c_.LineCounter;Q.Parser=l_.Parser;Q.parse=$c.parse;Q.parseAllDocuments=$c.parseAllDocuments;Q.parseDocument=$c.parseDocument;Q.stringify=$c.stringify;Q.visit=Mw.visit;Q.visitAsync=Mw.visitAsync});import{AsyncLocalStorage as u_}from"node:async_hooks";import{performance as jc}from"node:perf_hooks";function $p(e=0){d_+=1,p_+=e;let t=h_.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function Ua(e){let t=jc.now();try{return e()}finally{$p(jc.now()-t)}}async function jp(e){let t=jc.now();try{return await e()}finally{$p(jc.now()-t)}}var d_,p_,h_,wn=T(()=>{"use strict";d_=0,p_=0,h_=new u_});import{spawn as Op}from"node:child_process";import{existsSync as Vw}from"node:fs";import Ei from"node:path";function Hp(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function w_(e){let t=(Hp(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function y_(e,t,r){let n=Ei.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Hp(t,"PATH")??"").split(Ei.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Ei.win32.extname(e)?[e]:w_(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Ei.join(s,c):Ei.resolve(r,c)))}function xi(e,t,r){return y_(e,t,r).find(i=>Vw(i))??e}function b_(e){let t=Hp(e,"SystemRoot");if(t){let r=Ei.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(Vw(r))return r}return"powershell.exe"}function Ka(e){if(e.some(t=>v_.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function N_(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(g_,"utf16le").toString("base64");return Op(b_(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function Dp(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return Op(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=xi(e,i,r.cwd),a=Ei.win32.extname(n).toLowerCase();return m_.has(a)&&Ka(t),f_.has(a)?N_(n,t,{cwd:r.cwd,env:i}):Op(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var f_,m_,v_,g_,Ya=T(()=>{"use strict";f_=new Set([".bat",".cmd",".ps1"]),m_=new Set([".bat",".cmd"]),v_=/[&|<>()^%"!\r\n]/u,g_=["$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 k_,execFileSync as XL}from"node:child_process";import Ww from"node:path";async function Gr(e,t,r={}){let i=r.timeoutMs??S_,n=r.maxBufferBytes??E_;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(n)||n<1)throw new Error("External command limits must be positive integers");let a=Ww.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?xi(e,o,a):e,c=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);c&&Ka(t);let l=()=>new Promise((u,d)=>{let p=!1,h=k_(s,[...t],{cwd:a,env:o,encoding:"utf8",maxBuffer:n,windowsHide:!0,shell:c},(g,w,N)=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",m),g?d(new Xa(e,t,N.trim(),{cause:g,timedOut:x_(g)})):u(w))}),f=g=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",m),h.kill("SIGKILL"),h.stdin?.destroy(),h.stdout?.destroy(),h.stderr?.destroy(),h.unref(),d(new Xa(e,t,"",{timedOut:g})))},m=()=>f(!1),v=setTimeout(()=>f(!0),i);r.signal?.addEventListener("abort",m,{once:!0}),r.signal?.aborted&&m(),h.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(Ww.win32.basename(e))?jp(l):l()}function x_(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}var S_,E_,Xa,yn=T(()=>{"use strict";wn();Ya();S_=6e4,E_=8*1024*1024;Xa=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{execFileSync as A_}from"node:child_process";function Xw(e,t){try{return Ua(()=>A_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:I_,maxBuffer:T_,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Bp(e,t,i)}}function I(e,t){return Xw(e,t).trim()}function Hc(e){return I(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Lp(e,t){I(e,["check-ref-format","--branch",t])}function Qa(e){let t=Xw(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}var I_,T_,Bp,We=T(()=>{"use strict";wn();I_=3e4,T_=8*1024*1024,Bp=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});function O_(e){return e.toLowerCase().startsWith(".env")}function Nn(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>O_(i))?"environment-file":r.some(i=>j_.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>$_.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var $_,j_,Za=T(()=>{"use strict";$_=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),j_=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Yr(e){return e!==0&&e!==0n&&e!=="0"}function Pt(e,t){return Yr(e.dev)&&Yr(t.dev)&&Yr(e.ino)&&Yr(t.ino)}function te(e,t){let r=Yr(e.dev)&&Yr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Yr(e.ino)&&Yr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var eo=T(()=>{"use strict"});var Jt=T(()=>{"use strict";eo()});import{createHash as H_}from"node:crypto";import{promises as _t}from"node:fs";import ft from"node:path";import{TextDecoder as D_}from"node:util";function qp(e,t){let r=ft.relative(e,t);return r===""||!ft.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ft.sep}`)}function B_(e){let t=ft.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})||ft.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=Nn(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 L_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function q_(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Dc(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Pt(r,i)?te(r,i):te(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Qw(e){let t=await _t.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact 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=ft.resolve(e),i=ft.resolve(t);if(!qp(r,i))throw new Error("Native artifact path is outside its root");let n=[await Qw(r)],a=r;for(let o of ft.relative(r,i).split(ft.sep).filter(Boolean)){a=ft.join(a,o);let s=await Qw(a);if(!qp(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Zw(e){for(let t of e){let r=await _t.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!q_(t,r)||await _t.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Z(e){let t=B_(e.ref),r=e.maxBytes===null?null:L_(e.maxBytes??Fp),i=ft.resolve(e.root,...t.split("/")),n=await F_(e.root,ft.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await _t.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 _t.realpath(i);if(!qp(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await _t.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),_t.lstat(i),_t.realpath(i)]);if(await Zw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Dc(a,c)||!Dc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],p=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let N=r===null?h.length:r+1-p,y=await s.read(h,0,Math.min(h.length,N),null);if(y.bytesRead===0)break;if(p+=y.bytesRead,r!==null&&p>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,y.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[f,m,v]=await Promise.all([s.stat(),_t.lstat(i),_t.realpath(i)]);if(await Zw(n),!m.isFile()||m.isSymbolicLink()||v!==o||!Dc(c,f)||!Dc(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,p),w;try{w=new D_("utf-8",{fatal:!0}).decode(g)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:p,hash:e.includeHash===!1?null:H_("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}var Fp,rt=T(()=>{"use strict";Za();Jt();Fp=1024*1024});import{createHash as M_}from"crypto";function At(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function V_(e,t){t.has(e)&&At("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)||At("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&At("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&At("symbol properties are not supported"),`[${e.map(i=>Mp(i,t)).join(",")}]`}finally{t.delete(e)}}function W_(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&At("only plain objects are supported"),t.has(e)&&At("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&At("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))&&At("accessor properties are not supported"),`${JSON.stringify(o)}:${Mp(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Mp(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)||At("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?V_(e,t):W_(e,t);case"bigint":case"function":case"symbol":case"undefined":return At(`${typeof e} values are not supported`)}return At("unsupported value type")}function Bc(e){return Mp(e,new Set)}function $(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 M_("sha256").update(`${e}
|
|
143
|
-
${
|
|
144
|
-
`)){let s=
|
|
142
|
+
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=jc(t),i=wn(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=jc(t),i=wn(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())}}};qw.Parser=Tp});var Gw=R(Ua=>{"use strict";var Mw=yp(),t_=La(),Ja=Ma(),r_=gd(),i_=U(),n_=Ip(),Vw=$p();function Ww(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new n_.LineCounter||null,prettyErrors:t}}function a_(e,t={}){let{lineCounter:r,prettyErrors:i}=Ww(t),n=new Vw.Parser(r?.addNewLine),a=new Mw.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Ja.prettifyError(e,r)),s.warnings.forEach(Ja.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function zw(e,t={}){let{lineCounter:r,prettyErrors:i}=Ww(t),n=new Vw.Parser(r?.addNewLine),a=new Mw.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 Ja.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Ja.prettifyError(e,r)),o.warnings.forEach(Ja.prettifyError(e,r))),o}function o_(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=zw(e,r);if(!n)return null;if(n.warnings.forEach(a=>r_.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 s_(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 t_.Document(e,i,r).toString(r)}Ua.parse=o_;Ua.parseAllDocuments=a_;Ua.parseDocument=zw;Ua.stringify=s_});var Gt=R(Q=>{"use strict";var c_=yp(),l_=La(),u_=Zd(),jp=Ma(),d_=Sa(),zr=U(),p_=Fr(),f_=we(),h_=Mr(),m_=Vr(),v_=Tc(),g_=_p(),w_=Ip(),y_=$p(),Hc=Gw(),Jw=ya();Q.Composer=c_.Composer;Q.Document=l_.Document;Q.Schema=u_.Schema;Q.YAMLError=jp.YAMLError;Q.YAMLParseError=jp.YAMLParseError;Q.YAMLWarning=jp.YAMLWarning;Q.Alias=d_.Alias;Q.isAlias=zr.isAlias;Q.isCollection=zr.isCollection;Q.isDocument=zr.isDocument;Q.isMap=zr.isMap;Q.isNode=zr.isNode;Q.isPair=zr.isPair;Q.isScalar=zr.isScalar;Q.isSeq=zr.isSeq;Q.Pair=p_.Pair;Q.Scalar=f_.Scalar;Q.YAMLMap=h_.YAMLMap;Q.YAMLSeq=m_.YAMLSeq;Q.CST=v_;Q.Lexer=g_.Lexer;Q.LineCounter=w_.LineCounter;Q.Parser=y_.Parser;Q.parse=Hc.parse;Q.parseAllDocuments=Hc.parseAllDocuments;Q.parseDocument=Hc.parseDocument;Q.stringify=Hc.stringify;Q.visit=Jw.visit;Q.visitAsync=Jw.visitAsync});import{AsyncLocalStorage as b_}from"node:async_hooks";import{performance as Dc}from"node:perf_hooks";function Op(e=0){N_+=1,k_+=e;let t=S_.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function Ka(e){let t=Dc.now();try{return e()}finally{Op(Dc.now()-t)}}async function Hp(e){let t=Dc.now();try{return await e()}finally{Op(Dc.now()-t)}}var N_,k_,S_,yn=T(()=>{"use strict";N_=0,k_=0,S_=new b_});import{spawn as Dp}from"node:child_process";import{existsSync as Uw}from"node:fs";import Ei from"node:path";function Bp(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function P_(e){let t=(Bp(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function __(e,t,r){let n=Ei.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Bp(t,"PATH")??"").split(Ei.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Ei.win32.extname(e)?[e]:P_(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Ei.join(s,c):Ei.resolve(r,c)))}function xi(e,t,r){return __(e,t,r).find(i=>Uw(i))??e}function A_(e){let t=Bp(e,"SystemRoot");if(t){let r=Ei.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(Uw(r))return r}return"powershell.exe"}function Ya(e){if(e.some(t=>R_.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function I_(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(C_,"utf16le").toString("base64");return Dp(A_(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function Lp(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return Dp(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=xi(e,i,r.cwd),a=Ei.win32.extname(n).toLowerCase();return x_.has(a)&&Ya(t),E_.has(a)?I_(n,t,{cwd:r.cwd,env:i}):Dp(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var E_,x_,R_,C_,Xa=T(()=>{"use strict";E_=new Set([".bat",".cmd",".ps1"]),x_=new Set([".bat",".cmd"]),R_=/[&|<>()^%"!\r\n]/u,C_=["$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 T_,execFileSync as uF}from"node:child_process";import Kw from"node:path";async function Gr(e,t,r={}){let i=r.timeoutMs??$_,n=r.maxBufferBytes??j_;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(n)||n<1)throw new Error("External command limits must be positive integers");let a=Kw.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?xi(e,o,a):e,c=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);c&&Ya(t);let l=()=>new Promise((u,p)=>{let d=!1,f=T_(s,[...t],{cwd:a,env:o,encoding:"utf8",maxBuffer:n,windowsHide:!0,shell:c},(g,w,N)=>{d||(d=!0,clearTimeout(v),r.signal?.removeEventListener("abort",m),g?p(new Qa(e,t,N.trim(),{cause:g,timedOut:O_(g)})):u(w))}),h=g=>{d||(d=!0,clearTimeout(v),r.signal?.removeEventListener("abort",m),f.kill("SIGKILL"),f.stdin?.destroy(),f.stdout?.destroy(),f.stderr?.destroy(),f.unref(),p(new Qa(e,t,"",{timedOut:g})))},m=()=>h(!1),v=setTimeout(()=>h(!0),i);r.signal?.addEventListener("abort",m,{once:!0}),r.signal?.aborted&&m(),f.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(Kw.win32.basename(e))?Hp(l):l()}function O_(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}var $_,j_,Qa,bn=T(()=>{"use strict";yn();Xa();$_=6e4,j_=8*1024*1024;Qa=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{execFileSync as F_}from"node:child_process";function ry(e,t){try{return Ka(()=>F_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:q_,maxBuffer:M_,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Fp(e,t,i)}}function I(e,t){return ry(e,t).trim()}function Lc(e){return I(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function qp(e,t){I(e,["check-ref-format","--branch",t])}function Za(e){let t=ry(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}var q_,M_,Fp,We=T(()=>{"use strict";yn();q_=3e4,M_=8*1024*1024,Fp=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});function z_(e){return e.toLowerCase().startsWith(".env")}function kn(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>z_(i))?"environment-file":r.some(i=>W_.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>V_.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var V_,W_,eo=T(()=>{"use strict";V_=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),W_=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Yr(e){return e!==0&&e!==0n&&e!=="0"}function Pt(e,t){return Yr(e.dev)&&Yr(t.dev)&&Yr(e.ino)&&Yr(t.ino)}function te(e,t){let r=Yr(e.dev)&&Yr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Yr(e.ino)&&Yr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var to=T(()=>{"use strict"});var Jt=T(()=>{"use strict";to()});import{createHash as G_}from"node:crypto";import{promises as _t}from"node:fs";import ht from"node:path";import{TextDecoder as J_}from"node:util";function Mp(e,t){let r=ht.relative(e,t);return r===""||!ht.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ht.sep}`)}function U_(e){let t=ht.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})||ht.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=kn(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 K_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Y_(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Fc(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Pt(r,i)?te(r,i):te(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function iy(e){let t=await _t.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact 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 X_(e,t){let r=ht.resolve(e),i=ht.resolve(t);if(!Mp(r,i))throw new Error("Native artifact path is outside its root");let n=[await iy(r)],a=r;for(let o of ht.relative(r,i).split(ht.sep).filter(Boolean)){a=ht.join(a,o);let s=await iy(a);if(!Mp(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function ny(e){for(let t of e){let r=await _t.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Y_(t,r)||await _t.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Z(e){let t=U_(e.ref),r=e.maxBytes===null?null:K_(e.maxBytes??Vp),i=ht.resolve(e.root,...t.split("/")),n=await X_(e.root,ht.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await _t.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 _t.realpath(i);if(!Mp(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await _t.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),_t.lstat(i),_t.realpath(i)]);if(await ny(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Fc(a,c)||!Fc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let p=[],d=0,f=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let N=r===null?f.length:r+1-d,y=await s.read(f,0,Math.min(f.length,N),null);if(y.bytesRead===0)break;if(d+=y.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);p.push(Buffer.from(f.subarray(0,y.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[h,m,v]=await Promise.all([s.stat(),_t.lstat(i),_t.realpath(i)]);if(await ny(n),!m.isFile()||m.isSymbolicLink()||v!==o||!Fc(c,h)||!Fc(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(p,d),w;try{w=new J_("utf-8",{fatal:!0}).decode(g)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:d,hash:e.includeHash===!1?null:G_("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}var Vp,rt=T(()=>{"use strict";eo();Jt();Vp=1024*1024});import{createHash as Q_}from"crypto";function At(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function Z_(e,t){t.has(e)&&At("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)||At("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&At("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&At("symbol properties are not supported"),`[${e.map(i=>Wp(i,t)).join(",")}]`}finally{t.delete(e)}}function eA(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&At("only plain objects are supported"),t.has(e)&&At("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&At("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))&&At("accessor properties are not supported"),`${JSON.stringify(o)}:${Wp(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Wp(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)||At("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?Z_(e,t):eA(e,t);case"bigint":case"function":case"symbol":case"undefined":return At(`${typeof e} values are not supported`)}return At("unsupported value type")}function qc(e){return Wp(e,new Set)}function $(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 Q_("sha256").update(`${e}
|
|
143
|
+
${qc(t)}`).digest("hex")}var pe=T(()=>{"use strict"});import Xr from"path";function uy(e,t){return Sn[t][e]}function aA(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in Sn.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Sn.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in Sn.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in Sn.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in Sn.en)return s}return null}function oo(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,no.stringify)(e).trimEnd().split(`
|
|
144
|
+
`)){let s=aA(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of uy(s,t).split(`
|
|
145
145
|
`))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
|
|
146
|
-
`)}function Y_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Xr.posix.isAbsolute(r)||Xr.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 Pi(e){let t=Y_(e,"native.artifact_root");return t.length===0?".":t.join("/")}function oy(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||Xr.posix.isAbsolute(i)||Xr.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 yr(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=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>Lc)throw new Error(`${t} exceeds ${Lc} 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>qc)throw new Error(`${t} contains more than ${qc} wildcard tokens`);return e}function iy(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 to(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 ny(e,t,r){let i=to(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 X_(e){if(e===void 0)return{...ze,include:[...ze.include],exclude:[...ze.exclude]};let t=yr(e,"native.snapshot");return{include:iy(t.include,"native.snapshot.include",ze.include),exclude:iy(t.exclude,"native.snapshot.exclude",ze.exclude),max_files:to(t.max_files,ze.max_files,"native.snapshot.max_files"),max_total_bytes:to(t.max_total_bytes,ze.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:to(t.max_duration_ms,ze.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:to(t.max_selection_records,ze.max_selection_records,"native.snapshot.max_selection_records")}}function Q_(e){if(e===void 0)return;let t=yr(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=yr(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:Pi(i),toArtifactRoot:Pi(n),stage:a,...o?{cleanup:o}:{}}}function Z_(e){if(e===void 0)return;let t=yr(e,"native.finish");if(t.pull_request===void 0)return{};let r=yr(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(Xr.posix.isAbsolute(i[0])||Xr.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??z_;if(!Number.isSafeInteger(n)||n<1||n>ry)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${ry}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function eA(e,t={}){let r=yr(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??Vp;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=Q_(r.pending_root_move),l=Z_(r.finish);return{artifact_root:Pi(i),language:sy(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:X_(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function tA(e){let t=yr(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:oy(t.artifact_layout),language:sy(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function rA(e){let r=yr(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 iA(e){if(e===void 0)return{...ro};let t=yr(e,"memory"),r=t.learning??ro.learning,i=t.retrieval??ro.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 zp(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function nA(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")||Xr.posix.isAbsolute(r)||Xr.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>ey)throw new Error(`${t} exceeds ${ey} 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>ty)throw new Error(`${t} contains more than ${ty} wildcard tokens`);return r}function aA(e){let t=zp(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)=>nA(n,`knowledge.local.include[${a}]`)))],max_file_mb:ny(t.max_file_mb,Fc.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:ny(t.max_total_mb,Fc.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 oA(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 sA(e){let t=zp(e,"knowledge.remote"),r=oA(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 cA(e){if(e===void 0)return{...Wp};let t=zp(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:aA(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:sA(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 lA(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function uA(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 Sn(e,t={}){let r=(0,io.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=lA(n.ambient_resume),o=n.hook===void 0?void 0:rA(n.hook),s=iA(n.memory),c=cA(n.knowledge),l=n.native===void 0?void 0:eA(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:tA(n.classic),d=uA(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 cy(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function ly(e){let t=e.knowledge??{...Wp};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...ro},knowledge:{provider:t.provider,...t.local?{local:{include:[...t.local.include],max_file_mb:t.local.max_file_mb??Fc.max_file_mb,max_total_mb:t.local.max_total_mb??Fc.max_total_mb}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.document_writes?{document_writes:e.native.document_writes}:{},...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:cy(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition,...e.classic.document_evidence?{document_evidence:e.classic.document_evidence}:{}}}:{}}}function it(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function oo(e,t){let r=ly(t),i=Sn((0,io.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...it(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=it(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=it(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local?o.local={...it(a.local),include:[...i.knowledge.local.include],max_file_mb:i.knowledge.local.max_file_mb,max_total_mb:i.knowledge.local.max_total_mb}:delete o.local,i.knowledge.remote){let c={...it(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=it(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures,...i.native.document_writes?{document_writes:i.native.document_writes}:{}};if(i.native.finish?.pull_request){let s=it(a.finish);o.finish={...s,pull_request:{...it(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...it(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=it(a.pending_root_move),c=cy(i.native.pending_root_move),l=it(s.cleanup),u=it(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...it(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition,...i.classic.document_evidence?{document_evidence:i.classic.document_evidence}:{}}),n}function Wc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...ro},knowledge:{...Wp},native:{artifact_root:Pi(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Vp,snapshot:{...ze,include:[...ze.include],exclude:[...ze.exclude]}}}}var io,no,Lc,qc,ey,ty,Vp,ro,Fc,Wp,z_,ry,G_,J_,U_,ze,kn,Qr=T(()=>{"use strict";io=fr(Gt(),1),no=Number.MAX_SAFE_INTEGER,Lc=1024,qc=64,ey=1024,ty=64,Vp=5,ro={learning:!0,retrieval:!0},Fc={include:[],max_file_mb:1,max_total_mb:32},Wp={provider:"local"},z_=12e4,ry=6e5,G_=[".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/**"],J_=["**/.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"],U_=[...G_,...J_].sort((e,t)=>e.localeCompare(t,"en")),ze={include:["**/*"],exclude:[...U_],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4},kn={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
|
|
146
|
+
`)}function oA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Xr.posix.isAbsolute(r)||Xr.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 Pi(e){let t=oA(e,"native.artifact_root");return t.length===0?".":t.join("/")}function dy(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 zc(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||Xr.posix.isAbsolute(i)||Xr.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 yr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function py(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 Gc(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 cy(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=>Gc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function ro(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 ly(e,t,r){let i=ro(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 sA(e){if(e===void 0)return{...ze,include:[...ze.include],exclude:[...ze.exclude]};let t=yr(e,"native.snapshot");return{include:cy(t.include,"native.snapshot.include",ze.include),exclude:cy(t.exclude,"native.snapshot.exclude",ze.exclude),max_files:ro(t.max_files,ze.max_files,"native.snapshot.max_files"),max_total_bytes:ro(t.max_total_bytes,ze.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ro(t.max_duration_ms,ze.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:ro(t.max_selection_records,ze.max_selection_records,"native.snapshot.max_selection_records")}}function cA(e){if(e===void 0)return;let t=yr(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=yr(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:Pi(i),toArtifactRoot:Pi(n),stage:a,...o?{cleanup:o}:{}}}function lA(e){if(e===void 0)return;let t=yr(e,"native.finish");if(t.pull_request===void 0)return{};let r=yr(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(Xr.posix.isAbsolute(i[0])||Xr.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??tA;if(!Number.isSafeInteger(n)||n<1||n>sy)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${sy}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function uA(e,t={}){let r=yr(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??zp;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=cA(r.pending_root_move),l=lA(r.finish);return{artifact_root:Pi(i),language:py(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:sA(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function dA(e){let t=yr(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:dy(t.artifact_layout),language:py(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function pA(e){let r=yr(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)=>zc(i,`hook.allow_paths[${n}]`)))]}}function fA(e){if(e===void 0)return{...io};let t=yr(e,"memory"),r=t.learning??io.learning,i=t.retrieval??io.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 Jp(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function hA(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")||Xr.posix.isAbsolute(r)||Xr.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>ay)throw new Error(`${t} exceeds ${ay} 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>oy)throw new Error(`${t} contains more than ${oy} wildcard tokens`);return r}function mA(e){let t=Jp(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)=>hA(n,`knowledge.local.include[${a}]`)))],max_file_mb:ly(t.max_file_mb,Wc.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:ly(t.max_total_mb,Wc.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 vA(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 gA(e){let t=Jp(e,"knowledge.remote"),r=vA(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 wA(e){if(e===void 0)return{...Gp};let t=Jp(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:mA(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:gA(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 yA(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(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let p=[...new Set(u)];if(!p.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(p.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:p,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function En(e,t={}){let r=(0,no.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=yA(n.ambient_resume),o=n.hook===void 0?void 0:pA(n.hook),s=fA(n.memory),c=wA(n.knowledge),l=n.native===void 0?void 0:uA(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:dA(n.classic),p=bA(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:p,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function fy(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function hy(e){let t=e.knowledge??{...Gp};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...io},knowledge:{provider:t.provider,...t.local?{local:{include:[...t.local.include],max_file_mb:t.local.max_file_mb??Wc.max_file_mb,max_total_mb:t.local.max_total_mb??Wc.max_total_mb}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.document_writes?{document_writes:e.native.document_writes}:{},...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:fy(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition,...e.classic.document_evidence?{document_evidence:e.classic.document_evidence}:{}}}:{}}}function it(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function so(e,t){let r=hy(t),i=En((0,no.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...it(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=it(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=it(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local?o.local={...it(a.local),include:[...i.knowledge.local.include],max_file_mb:i.knowledge.local.max_file_mb,max_total_mb:i.knowledge.local.max_total_mb}:delete o.local,i.knowledge.remote){let c={...it(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=it(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures,...i.native.document_writes?{document_writes:i.native.document_writes}:{}};if(i.native.finish?.pull_request){let s=it(a.finish);o.finish={...s,pull_request:{...it(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...it(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=it(a.pending_root_move),c=fy(i.native.pending_root_move),l=it(s.cleanup),u=it(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...it(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition,...i.classic.document_evidence?{document_evidence:i.classic.document_evidence}:{}}),n}function Jc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...io},knowledge:{...Gp},native:{artifact_root:Pi(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:zp,snapshot:{...ze,include:[...ze.include],exclude:[...ze.exclude]}}}}var no,ao,Mc,Vc,ay,oy,zp,io,Wc,Gp,tA,sy,rA,iA,nA,ze,Sn,Qr=T(()=>{"use strict";no=hr(Gt(),1),ao=Number.MAX_SAFE_INTEGER,Mc=1024,Vc=64,ay=1024,oy=64,zp=5,io={learning:!0,retrieval:!0},Wc={include:[],max_file_mb:1,max_total_mb:32},Gp={provider:"local"},tA=12e4,sy=6e5,rA=[".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/**"],iA=["**/.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"],nA=[...rA,...iA].sort((e,t)=>e.localeCompare(t,"en")),ze={include:["**/*"],exclude:[...nA],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4},Sn={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
|
|
147
147
|
# ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
|
|
148
148
|
# learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
|
|
149
149
|
# retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
|
|
@@ -171,8 +171,8 @@ ${Bc(t)}`).digest("hex")}var pe=T(()=>{"use strict"});import Xr from"path";funct
|
|
|
171
171
|
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
172
172
|
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
173
173
|
# 可选值:true | false`,"classic.document_evidence":`# 文档编辑对已记录检查证据的影响:neutral 在只有文档文件变化时保持 build 和 verify 证据有效,strict 重新绑定工作区的全部文件。
|
|
174
|
-
# 可选值:neutral | strict`}}});import{constants as
|
|
175
|
-
`,r)}var ne=T(()=>{"use strict";rh();Jt()});import{existsSync as vy,promises as Ai}from"fs";import K from"path";import xA from"os";async function oh(e){try{return await Ai.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function CA(e){try{let t=await Ai.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function An(e,t){let r=K.relative(e,t);return r===""||!K.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${K.sep}`)}async function _n(e){let t=[],r=e;for(;!await oh(r);){let n=K.dirname(r);if(n===r)break;t.push(K.basename(r)),r=n}let i=await Ai.realpath(r);return K.resolve(i,...t.reverse())}async function sh(e){try{return(await Ai.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Qc(e){let t=K.resolve(e);try{(await Ai.stat(t)).isDirectory()||(t=K.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=K.resolve(xA.homedir());for(;;){if(!(t===i&&r!==i)){let o=K.join(t,...ho.split("/")),s=t===r||await CA(o);if(await oh(o)&&s)return t}if(await oh(K.join(t,".git")))return t;let a=K.dirname(t);if(a===t)return r;t=a}}function Zc(e){return Pi(e)}async function PA(e,t){let r=Zc(t),i=K.resolve(e,...r.split("/")),n=await Ai.realpath(e),a=await _n(i);if(!An(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function ei(e,t){let r=Zc(t),i=await PA(e,r),n=K.join(i,"comet");if(await sh(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([_n(i),_n(n)]);if(!An(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=K.resolve(e),c=K.join(s,".comet","runtime","native");if(await sh(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Ai.realpath(s),_n(c)]);if(!An(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:K.join(e,...ho.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:K.join(n,"specs"),changesDir:K.join(n,"changes"),archiveDir:K.join(n,"archive"),runtimeDir:c,changesRuntimeDir:K.join(c,"changes"),locksDir:K.join(c,"locks"),transactionsDir:K.join(c,"transactions")}}function gy(e){if(!RA.test(e))throw new Error(`Invalid Native change name: ${e}`)}function me(e,t){gy(t);let r=K.join(e.changesRuntimeDir,t);if(!Ee(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function ch(e,t){gy(t);let r=K.join(e.changesDir,t,"runtime");if(!Ee(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function vt(e,t){let r=me(e,t);if(vy(r))return r;let i=ch(e,t);return vy(i)?i:r}function lh(e,t){if(!t.startsWith("runtime/")||K.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=K.resolve(e,...t.slice(8).split("/"));if(!Ee(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function Ge(e,t){let r=K.resolve(t);if(Ee(e.runtimeDir,r))return e.runtimeDir;if(Ee(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function Ee(e,t){return An(K.resolve(e),K.resolve(t))}async function G(e,t){let r=K.resolve(e),i=K.resolve(t);if(!An(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await sh(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([_n(r),_n(i)]);if(!An(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var ho,RA,ie=T(()=>{"use strict";Qr();ho=".comet/config.yaml",RA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import _A from"path";function AA(e="docs",t="en"){return Wc(e,t)}async function Oe(e){let t=(await Uc(e))?.config??null;return t?.native?t:null}async function tl(e){let t=await Oe(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 rl(e,t,r={}){let i=await uo(e,{allowPartialProject:!0}),n=oo(i.document?.value??{},t),a=_A.join(e,...ho.split("/"));await mt(a,ao(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await nh(e,i.identity)}})}async function wy(e){let t=await Qc(e.startPath),r=await Oe(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${ho} 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?Zc(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??AA(i??"docs"),a=await ei(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var el,gt=T(()=>{"use strict";Qr();Rn();ah();ne();ie();el=Vc});function ee(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 fo({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var fo,mo=T(()=>{"use strict";fo=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 uh(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 Tn(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}]`;ee(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:uh(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>uh(o,`${n}.evidence`)),note:uh(i.note,`${n}.note`)}})}function $n(e,t){if(!t)throw new In(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 In(o,s)}var In,vo=T(()=>{"use strict";mo();In=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 nl(){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 Ii,go,il,jn=T(()=>{"use strict";Ii="comet.native.v4",go="comet.native.local-execution.v4",il=["multi-session","single-session"]});var fh={};Qu(fh,{NativePortableStateVersionConflictError:()=>wo,appendNativePortableHistory:()=>ke,compareAndSwapNativePortableState:()=>Dn,createNativePortableState:()=>by,parseNativePortableState:()=>B,readNativePortableState:()=>yt,writeNativePortableState:()=>yo});import{promises as IA}from"node:fs";function He(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function De(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 xe(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 ph(e,t){return e===null?null:xe(e,t)}function hh(e,t){let r=xe(e,t);if(!OA.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function On(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 DA(e,t){return e===null?null:se(e,t,Number.MIN_SAFE_INTEGER)}function ye(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ut(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function cl(e,t){return Ut(e,t,(r,i)=>xe(r,`${t}[${i}]`))}function Ti(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Hn(e,t){let r=xe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function ol(e,t,r=!1){let i=xe(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 wt(e,t){let r=He(e,t);return De(r,new Set(["text","truncated"]),t),{text:xe(r.text,`${t}.text`,{empty:!0}),truncated:On(r.truncated,`${t}.truncated`)}}function BA(e,t){let r=`Native spec_changes[${t}]`,i=He(e,r);De(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=xe(i.capability,`${r}.capability`);if(!$A.test(n))throw new Error(`${r}.capability is invalid`);let a=ye(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:ol(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:ol(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:hh(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 LA(e){let t="Native workspace",r=He(e,t);De(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=ye(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=ph(r.change_branch,`${t}.change_branch`),a=ph(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:ye(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 qA(e){let t="Native loop",r=He(e,t);De(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=cl(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Ti(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:ye(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ye(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:ph(r.next_action,`${t}.next_action`)}}function FA(e,t){let r=`Native acceptance[${t}]`,i=He(e,r);De(i,new Set(["id","source","text","result","reason"]),r);let n=xe(i.id,`${r}.id`);if(!jA.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:ol(i.source,`${r}.source`),text:xe(i.text,`${r}.text`),result:ye(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:wt(i.reason,`${r}.reason`)}}function MA(e,t){let r=`Native builder_handoff.checks[${t}]`,i=He(e,r);return De(i,new Set(["name","result","note"]),r),{name:wt(i.name,`${r}.name`),result:ye(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:wt(i.note,`${r}.note`)}}function VA(e){let t="Native builder_handoff",r=He(e,t);De(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=cl(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ti(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:He(r.review,`${t}.review`);return n&&De(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:xe(r.candidate_id,`${t}.candidate_id`),identity_provider:xe(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:xe(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),summary:wt(r.summary,`${t}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:Tn(r.acceptance_review)},checks:Ut(r.checks,`${t}.checks`,MA),checks_truncated:On(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ut(r.known_limits,`${t}.known_limits`,(a,o)=>wt(a,`${t}.known_limits[${o}]`)),known_limits_truncated:On(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ye(n.status,["passed"],`${t}.review.status`),summary:wt(n.summary,`${t}.review.summary`),reviewer_execution_ref:xe(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Hn(r.submitted_at,`${t}.submitted_at`)}}function WA(e,t){let r=`Native blockers[${t}]`,i=He(e,r);De(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=cl(i.acceptance_ids,`${r}.acceptance_ids`);return Ti(n,`${r}.acceptance_ids`),{owner:ye(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:wt(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:ye(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function zA(e,t){let r=`Native verification.checks[${t}]`,i=He(e,r);return De(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:xe(i.id,`${r}.id`),name:wt(i.name,`${r}.name`),argv_display:Ut(i.argv_display,`${r}.argv_display`,(n,a)=>wt(n,`${r}.argv_display[${a}]`)),argv_truncated:On(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:ol(i.cwd_ref,`${r}.cwd_ref`,!0),status:ye(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:DA(i.exit_code,`${r}.exit_code`),duration_ms:se(i.duration_ms,`${r}.duration_ms`)}}function GA(e){let t="Native verification",r=He(e,t);De(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ut(r.checks,`${t}.checks`,zA);Ti(i.map(a=>a.id),`${t}.checks IDs`);let n=xe(r.identity_provider,`${t}.identity_provider`);return{candidate_id:xe(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:xe(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":ye(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ye(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:wt(r.summary,`${t}.summary`),risks:Ut(r.risks,`${t}.risks`,(a,o)=>wt(a,`${t}.risks[${o}]`)),risks_truncated:On(r.risks_truncated,`${t}.risks_truncated`),completed_at:Hn(r.completed_at,`${t}.completed_at`)}}function yy(e,t){let r=`Native history[${t}]`,i=He(e,r);De(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=cl(i.unresolved_ids,`${r}.unresolved_ids`);return Ti(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:ye(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:wt(i.summary,`${r}.summary`),completed_at:Hn(i.completed_at,`${r}.completed_at`)}}function JA(e){let t="Native history_overflow.outcome_counts",r=He(e,t),i=["pass","fail","blocked","execution-error","recovery"];return De(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 UA(e){let t="Native history_overflow",r=He(e,t);De(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:Hn(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Hn(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=JA(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 KA(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&&$n(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 YA(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 B(e){let t=He(e,"Native portable state");if(De(t,HA,"Native portable state"),t.schema!==Ii)throw new Error(`Native portable state schema must be ${Ii}`);let r=xe(t.name,"Native state name");if(!TA.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=Ut(t.spec_changes,"Native spec_changes",BA);Ti(i.map(s=>s.capability),"Native spec change capabilities");let n=Ut(t.acceptance,"Native acceptance",FA);Ti(n.map(s=>s.id),"Native acceptance IDs");let a=Ut(t.history,"Native history",yy);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Ii,name:r,language:ye(t.language,["en","zh-CN"],"Native state language"),phase:ye(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ye(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:hh(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:hh(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ye(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:LA(t.workspace),loop:qA(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:VA(t.builder_handoff),blockers:Ut(t.blockers,"Native blockers",WA),verification:t.verification===null?null:GA(t.verification),history:a,history_overflow:UA(t.history_overflow),verification_result:ye(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ye(t.verification_report,["verification.md"],"Native verification_report"),archived:On(t.archived,"Native archived"),created_at:Hn(t.created_at,"Native created_at")};return KA(o),YA(o),o}function by(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return B({schema:Ii,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:nl(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ke(e,t){let r=B(e),i=yy(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 B({...r,history:n,history_overflow:a})}function XA(e,t){let r=(0,sl.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 yt(e){let t=await IA.readFile(e,"utf8");return B(XA(t,"Native portable state"))}async function yo(e,t,r={}){let i=B(t);await mt(e,(0,sl.stringify)(i),r)}async function QA(e,t){let r=al.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);al.set(e,a),await r;try{return await t()}finally{i(),al.get(e)===a&&al.delete(e)}}async function Dn(e){return QA(e.file,async()=>{let t=se(e.expectedStateVersion,"Native expected state version",1),r=B(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await yt(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new wo(t,i.state_version);return await yo(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await yt(e.file);if(n.state_version!==t)throw new wo(t,n.state_version)}}),r})}var sl,TA,$A,jA,OA,HA,wo,al,at=T(()=>{"use strict";vo();sl=fr(Gt(),1);ne();jn();TA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$A=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jA=/^A[1-9][0-9]*$/u,OA=/^[a-f0-9]{64}$/u,HA=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"]),wo=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"};al=new Map});import{promises as ZA}from"node:fs";import eI from"node:path";function ul(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function ll(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 ky(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 oI(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 Sy(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 Cy(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===vh&&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=>!Ey(e.children,l)),xy(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=>!Ey(e.children,a)),xy(i)?i:null}return null}function Ey(e,t){return e.some(r=>r.covers.includes(t))}function xy(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function bt(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 sI(e){let t=ul(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=ul(n,`Native children acceptance_index.${i}`);if(ll(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 cI(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(h=>d[h]!==u[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${p.join(", ")} exactly from the current acceptance catalog`)}}}function Py(e,t,r={}){let i=(0,Ry.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=ul(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==$i&&a!==ti)throw ll(n,Ny,"Native children contract"),new Error(`Native children schema must be ${$i} or ${ti}`);let o=a===$i?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(ll(n,o==="indexed-v2"?rI:Ny,"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,h)=>{let f=ul(p,`Native child ${h}`);if(ll(f,o==="indexed-v2"?aI:o==="summary-v2"?nI:iI,`Native ${s} child fields (child ${h})`),typeof f.name!="string"||!tI.test(f.name))throw new Error(`Native child ${h} name is invalid`);let m=o==="summary-v2";if(m){if(typeof f.summary!="string"||f.summary.trim().length===0)throw new Error(`Native child ${f.name} summary must be a non-empty string`);if(f.summary.length>2e3)throw new Error(`Native child ${f.name} summary exceeds 2000 characters`)}return{name:f.name,summary:m?f.summary:null,depends_on:ky(f.depends_on,`Native child ${f.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?ky(f.covers,`Native child ${f.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 h=p.depends_on.filter(f=>!u.has(f));if(h.length>0)throw new Error(`Native child ${p.name} depends on unknown child: ${h.join(", ")}`)}oI(c);let d=r.policy==="advisory";if(a===vh){if(o==="indexed-v2"){let p=sI(n.acceptance_index);d||cI(p,t,r);let h=Object.keys(p);return d||Sy(c,h,h),{schema:ti,acceptance_index:p,children:c}}return{schema:ti,children:c}}return t&&!d&&Sy(c,t),{schema:$i,children:c}}async function Je(e){let t=eI.join(e.changeDir,mh);try{await ZA.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await Z({root:e.changeDir,ref:mh}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Py(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Cy(a,e.acceptanceIds,e.validation??{}):null}}var Ry,mh,$i,ti,vh,tI,Ny,rI,iI,nI,aI,dl=T(()=>{"use strict";Ry=fr(Gt(),1);rt();mh="children.yaml",$i="comet.native.children.v1",ti="comet.native.children.v2",vh=ti,tI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ny=new Set(["schema","children"]),rI=new Set(["schema","acceptance_index","children"]),iI=new Set(["name","depends_on","covers"]),nI=new Set(["name","summary","depends_on"]),aI=new Set(["name","depends_on","covers"])});function gh(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function wh(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){gh(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Se,executionRef:gh(t.executionRef,"Native execution ref"),[_y]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:gh(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[Ay]:!0})}})}function pl(e){return typeof e=="object"&&e!==null&&e[Ay]===!0}function Iy(e){return typeof e=="object"&&e!==null&&e[_y]===!0}var _y,Ay,Se,ji=T(()=>{"use strict";_y=Symbol("comet.native.trusted-execution-identity"),Ay=Symbol("comet.native.trusted-verifier-envelope"),Se="skill-coordinated"});function hl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function bo(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Oi(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function fl(e,t="/acceptance"){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((r,i)=>{let n=hl(r,`Native Verifier acceptance ${i}`);ee(n,["id","result","reason"],`Native Verifier acceptance ${i}`,`${t}/${i}`);let a=Oi(n.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(n.result)))throw new Error(`Native Verifier acceptance ${a} result is invalid`);return{id:a,result:n.result,reason:Oi(n.reason,`Native Verifier acceptance ${a} reason`)}})}function lI(e,t){let r=hl(e,"Native Verifier final result");if(ee(r,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result",t),!["pass","fail","blocked"].includes(String(r.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(r.risks)||!r.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:bo(r.iteration,"Native Verifier iteration"),attempt:bo(r.attempt,"Native Verifier attempt"),verdict:r.verdict,acceptance:fl(r.acceptance,`${t}/acceptance`),risks:r.risks,summary:Oi(r.summary,"Native Verifier summary")}}function uI(e,t,r){let i=hl(e,`Native Verifier check request ${t}`);if(ee(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`,`${r}/${t}`),!Array.isArray(i.argv)||!i.argv.every(a=>typeof a=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let n=bo(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(n<1)throw new Error("Native Verifier check timeout must be positive");return{id:Oi(i.id,`Native Verifier check request ${t} ID`),name:Oi(i.name,`Native Verifier check request ${t} name`),executable:Oi(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:Oi(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:n,repeatable:i.repeatable}}function No(e,t=""){let r=hl(e,"Native Verifier response");if(r.kind==="final-result")return ee(r,["kind","result"],"Native Verifier response",t),{kind:"final-result",result:lI(r.result,`${t}/result`)};if(r.kind==="request-checks"){if(ee(r,["kind","iteration","attempt","checks"],"Native Verifier response",t),!Array.isArray(r.checks)||r.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:bo(r.iteration,"Native Verifier iteration"),attempt:bo(r.attempt,"Native Verifier attempt"),checks:r.checks.map((i,n)=>uI(i,n,`${t}/checks`))}}throw new Error("Native Verifier response kind is invalid")}function Ty(e){if(!pl(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=No(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=yh(i.result,r);return{...i,result:{...i.result,acceptance:o}}}function yh(e,t){fl(e.acceptance);let r=[...t.acceptanceIds],i=new Set(t.knownAcceptanceIds??r),n=new Set(t.previouslyPassedAcceptanceIds??[]),a=r.filter(m=>!i.has(m)),o=[...n].filter(m=>!i.has(m));if(a.length>0||o.length>0)throw new Error("Native Verifier acceptance binding is internally inconsistent");let s=new Set(r),c=e.acceptance.map(({id:m})=>m),l=c.filter((m,v)=>c.indexOf(m)!==v),u=c.filter(m=>!i.has(m)),d=r.filter(m=>!c.includes(m)),p=e.acceptance.filter(({id:m,result:v})=>s.has(m)||!i.has(m)?!1:!n.has(m)||v!=="passed").map(({id:m,result:v})=>`${m}=${v}`);if(l.length>0||u.length>0||d.length>0||p.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(l)].join(", ")||"none"}; unknown: ${u.join(", ")||"none"}; missing: ${d.join(", ")||"none"}; out-of-scope: ${p.join(", ")||"none"}). Return each required scope ID exactly once and no other acceptance IDs.`);let h=e.acceptance.filter(({id:m})=>s.has(m));if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let f=h.map(({result:m})=>m);if(e.verdict==="pass"&&f.some(m=>m!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!f.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!f.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return h}var ko=T(()=>{"use strict";mo();ji()});function Nt(e,t){if(!dI.test(e))throw new Error(`${t} must be a Git commit`)}function Ue(e){return structuredClone(e)}function ot(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function pI(e,t){if(!bh(t.dependsOn,e.children)){let r=t.dependsOn.filter(i=>e.children.find(({name:n})=>n===i)?.status!=="integrated");throw new Error(`Native Supervisor child ${t.name} dependency ${r[0]??"?"} is not integrated`)}}function bh(e,t){let r=new Map(t.map(({name:i,status:n})=>[i,n]));return e.every(i=>r.get(i)==="integrated")}function $y(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function xo(e){Nt(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:So(e.contract,i.name),contractHash:$("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:Eo,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 So(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 Nh(e){let t=Ue(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on];let o=So(e.contract,n.name),s=$("comet.native.supervisor-contract.v1",e.contract);n.contractHash&&n.contractHash!==s&&n.status!=="integrated"&&n.status!=="archived"&&(n.task=null,n.verifiedCommit=null,n.verification=null,n.checks=[],n.candidateCommit?(n.status="needs-reverify",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):bh(n.dependsOn,t.children)?(n.status="ready",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):(n.status="pending",n.blocker=null)),n.acceptanceScope=o,n.contractHash=s,n.builderFailureCount??=0}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:So(e.contract,n.name),contractHash:$("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0});return t.stateVersion+=1,t}function ri(e,t,r){let i={child:e.child,runId:e.runId},n=(e.checkExecution?.checkStates??[]).filter(({status:o})=>o==="interrupted").map(({id:o})=>o),a=e.role==="builder"?[{kind:"supervisor-builder-result",...i,candidateCommit:"<candidate-commit>"},{kind:"supervisor-builder-failure",...i,reason:"<failure-reason>"}]:[{kind:"supervisor-checks",...i,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],materials:[],...n.length>0?{retry_check_ids:n}:{}},{kind:"supervisor-verifier-result",...i,verdict:"blocked",evidence:{summary:"<verification-summary>",checks:[],acceptance:(e.acceptance??[]).map(({id:o})=>({id:o,result:"blocked",reason:"<evidence>"})),receiptRef:e.checkExecution?.receiptRef??null}}];return{...e,controlProjectRoot:r,returnAction:{cwd:r,commandArgs:["comet","native","next",t,"--runner-input","<temporary-json-file>","--json"],inputOptions:a.map(o=>({name:o.kind,exclusiveGroup:"runner-input",template:o}))}}}function Ro(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=Ue(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);pI(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n,acceptance:i.acceptanceScope??[{id:`child:${i.name}`,source:"children.yaml",text:i.summary??i.name}],contractHash:i.contractHash,verificationBoundary:"child-scope-parent-reverifies-all",checksReason:"not-run"};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,ot(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function jy(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function kh(e,t){let r=jy(e,t),i=Ue(e);return ot(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function ml(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=Ue(e),i=r.children.find(({name:a})=>a===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);let n=i.task.role;return n==="builder"?(i.builderFailureCount=(i.builderFailureCount??0)+1,i.status=i.builderFailureCount>=Nr?"blocked":"ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=n==="builder"&&(i.builderFailureCount??0)>=Nr?`Builder failed ${i.builderFailureCount} times; explicit Builder retry is required. Last failure: ${t.reason}`:t.reason,ot(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Co(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,ot(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Sh(e,t){Nt(t.candidateCommit,"Native Supervisor candidate commit");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.builderFailureCount=0,i.task=null,i.blocker=null,ot(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function Eh(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return yh({verdict:t.verdict,acceptance:t.evidence.acceptance??[]},{acceptanceIds:i.task.acceptance?.map(({id:n})=>n)??i.acceptanceScope?.map(({id:n})=>n)??[`child:${i.name}`],requiredChecksPassed:t.evidence.checks.length>0}),i.verification={...structuredClone(t.evidence)},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(t.verdict==="fail"?(i.status="ready",i.candidateCommit=null,i.verifiedCommit=null,i.verification=null,i.checks=[]):i.status="needs-reverify",i.blocker=t.evidence.summary),ot(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function xh(e,t){if(!Number.isSafeInteger(t.expectedStateVersion)||t.expectedStateVersion<1)throw new Error("Native Supervisor Builder retry state version is invalid");if(e.stateVersion!==t.expectedStateVersion)throw new Error("Native Supervisor Builder retry input is stale");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.status!=="blocked"||i.task!==null||(i.builderFailureCount??0)<Nr)throw new Error(`Native Supervisor child ${t.child} is not waiting for an explicit Builder retry`);if(!bh(i.dependsOn,r.children))throw new Error(`Native Supervisor child ${t.child} dependencies are not integrated`);return i.status="ready",i.candidateCommit=null,i.blocker=null,i.builderFailureCount=0,ot(r,{kind:"task-cancelled",child:i.name,runId:null,summary:"Explicit Builder retry authorized after the failure budget was exhausted"}),r.stateVersion+=1,r}function vl(e,t){Nt(t.integrationCommit,"Native Supervisor integration commit");let r=Ue(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,ot(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}function gl(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 dI,Eo,Nr,Hi=T(()=>{"use strict";pe();ko();dI=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;Eo="comet.native.supervisor.v2",Nr=3});import Po from"node:path";import{promises as Hy}from"node:fs";function Rh(e,t){return Po.join(me(e,t),"supervisor")}function Di(e,t){return Po.join(Rh(e,t),"state.json")}function Dy(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!==Eo)throw new Error(`Native Supervisor state schema must be ${Eo}`);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(Nt(t.integration.targetCommit,"Native Supervisor target commit"),Nt(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");Nt(n.candidateCommit,"Native Supervisor integration candidate commit"),Nt(n.integrationCommit,"Native Supervisor integration check commit"),Oy(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&&Nt(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(Nt(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&&Oy(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 D(e,t,r={}){try{let i=await Hy.readFile(Di(e,t),"utf8"),n=JSON.parse(i);if(Dy(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(()=>(at(),fh)),c=await s(Po.join(o.changesDir,t,"comet-state.yaml")),l=await Je({changeDir:Po.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:bt(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=So(l.contract,u.name),u.contractHash=$("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(()=>(at(),fh)),s=await o(Po.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 wl(e,t){let r=await hI(e,t);if(r.length>0)throw new Error(`Native Supervisor Git binding cannot change while active child tasks exist: ${r.join(", ")}`)}async function hI(e,t){return(await D(e,t,{diagnostics:!0}))?.children.filter(({task:i})=>i!==null).map(({name:i})=>i)??[]}async function F(e,t){Dy(t),await Hy.mkdir(e.changesRuntimeDir,{recursive:!0}),await fe(Di(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Oy(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 kr=T(()=>{"use strict";ne();pe();dl();ie();Hi()});import{createHash as Ph,randomUUID as fI}from"node:crypto";import{promises as st}from"node:fs";import mI from"node:os";import Ke from"node:path";async function Ch(e,t){let r=await st.lstat(e,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(t))throw new Error("Invalid process probe cache");let i=await st.readFile(e),n=await st.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 qy(e){try{let t=JSON.parse((await Ch(Ke.join(e,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(t.file??""))return null;let r=Ke.join(e,t.file),i=await Ch(r,65536);return Ph("sha256").update(i).digest("hex")===t.hash?r:null}catch{return null}}async function wI(e,t){let r,i=fI(),n=Ke.join(e,`probe-${i}.cs`),a=Ke.join(e,`probe-${i}.exe`),o=Ke.join(e,`probe-${i}.json`);try{if(await st.mkdir(e,{recursive:!0,mode:448}),(await st.lstat(e)).isSymbolicLink())return null;r=await st.open(Ke.join(e,"prepare.lock"),"wx",384);let s=await qy(e);if(s)return s;await st.writeFile(n,Ly,{flag:"wx",mode:384});let c;for(let u of["Framework64","Framework"]){let d=Ke.join(t,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await st.access(d),c=d;break}catch{}}if(!c)return null;await Gr(c,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,n],{timeoutMs:1500,maxBufferBytes:4096});let l=Ph("sha256").update(await Ch(a,65536)).digest("hex");return await st.writeFile(o,JSON.stringify({file:Ke.basename(a),hash:l}),{flag:"wx",mode:384}),await st.rename(o,Ke.join(e,"probe.json")),a}catch{return null}finally{await st.unlink(n).catch(()=>{}),await st.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await st.unlink(Ke.join(e,"prepare.lock")).catch(()=>{}))}}async function By(e,t,r){try{let i=await Gr(Ke.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 Gr(Ke.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 yI(e,t){let r=yl.get(e);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:wI(e,t),retryAfter:1/0};return yl.set(e,i),i.promise.then(n=>{yl.get(e)===i&&(n?yl.delete(e):i.retryAfter=performance.now()+gI)}),i.promise}async function Fy(e,t={}){if(!Number.isSafeInteger(e)||e<=0)return null;let r=t.systemRoot??process.env.SystemRoot??"C:\\Windows",i=Ke.join(t.cacheRoot??Ke.join(mI.tmpdir(),"comet-process-identity"),vI),n=async l=>{if(!l)return null;try{let d=(await Gr(l,[String(e)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await qy(i);if(a){let l=await n(a);return l||By(e,r,new AbortController().signal)}let o=yI(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),By(e,r,s.signal).then(c)])}catch{return null}finally{s.abort()}}var Ly,vI,gI,yl,My=T(()=>{"use strict";yn();Ly=`using System;
|
|
174
|
+
# 可选值:neutral | strict`}}});import{constants as Uc,promises as _i}from"fs";function Up(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function my(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function co(e){return{dev:e.dev,ino:e.ino,birthtime:Up(e)}}function Kc(e,t){let r=co(e),i=co(t);return Pt(r,i)?te(r,i):te(r,i)&&Up(e)===Up(t)&&my(e)===my(t)&&e.size===t.size}async function xn(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 _i.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new It("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new It("too-large",`${i} exceeds ${t} bytes`);let o=await _i.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:co(a)});let s=process.platform==="win32"?Uc.O_RDONLY:Uc.O_RDONLY|Uc.O_NOFOLLOW|Uc.O_NONBLOCK,c;try{c=await _i.open(e,s)}catch(l){throw l.code==="ELOOP"?new It("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,p]=await Promise.all([c.stat({bigint:n}),_i.lstat(e,{bigint:n}),_i.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||p!==o||!Kc(a,l)||!Kc(a,u))throw new It("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:p,identity:co(l)}),await r.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-f,{bytesRead:N}=await c.read(h,0,Math.min(h.length,w),null);if(N===0)break;if(f+=N,f>t)throw new It("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(h.subarray(0,N)))}await r.hooks?.beforeFinalCheck?.();let[m,v,g]=await Promise.all([c.stat({bigint:n}),_i.lstat(e,{bigint:n}),_i.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!Kc(a,m)||!Kc(a,v))throw new It("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:co(m)}),{bytes:Buffer.concat(d,f),stat:m,realPath:g}}finally{await c.close()}}var It,lo=T(()=>{"use strict";to();It=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as Yc}from"fs";import Zr from"path";function NA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Kp(e,t){let r=Zr.relative(e,t);return r===""||!Zr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Zr.sep}`)}async function vy(e,t){let r=Zr.resolve(e),i=await Yc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Yc.realpath(r)}async function gy(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Zr.join(n,r[a]);let o;try{o=await Yc.lstat(n)}catch(u){if(NA(u))return{exists:!1,kind:"missing"};throw u}let s=Zr.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 Yc.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 Rn(e,t,r){let i=zc(t,r.label),n=Zr.resolve(e),a=await vy(n,r.label),o=i.split("/"),s=Zr.resolve(n,...o);if(!Kp(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await gy(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function nt(e,t,r,i){let n=await Rn(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 vy(n.projectRoot,i.label);return xn(n.target,r,{...i,verify:async(o,s)=>{if(!Kp(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await gy(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var br=T(()=>{"use strict";lo();Qr()});import{createHash as kA}from"crypto";function Yp(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function SA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Xc(e,t={}){return(await po(e,t)).document}async function wy(e){try{return(await nt(e,uo,ao,{label:uo})).bytes}catch(t){if(SA(t))return null;throw t}}function yy(e){return e?{exists:!0,sha256:kA("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Qc(e){return yy(await wy(e))}async function po(e,t={}){let r=await wy(e);return{document:r?En(r.toString("utf8"),t):null,identity:yy(r)}}async function Xp(e){return(await Xc(e))?.config??null}var uo,Cn=T(()=>{"use strict";Qr();br();uo=".comet/config.yaml"});import{promises as Zp}from"node:fs";async function ef(e,t){let r;for(let i=0;i<=Qp.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===Qp.length||!EA.has(a??""))throw n;await new Promise(o=>setTimeout(o,Qp[i]))}throw r}async function tf(e,t){await ef(()=>Zp.rename(e,t),`rename ${t}`)}async function rf(e){await ef(()=>Zp.unlink(e),`unlink ${e}`)}async function nf(e,t){await ef(()=>Zp.link(e,t),`link ${t}`)}var EA,Qp,af=T(()=>{"use strict";EA=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Qp=[50,100,200]});var Pn=T(()=>{"use strict";af();to()});var dq,of=T(()=>{"use strict";Pn();Cn();br();dq=16*1024});async function sf(e,t){if(!t)return;let r=await Qc(e);if(!Yp(r,t))throw new Error("Project config changed before commit; rerun the operation")}var cf=T(()=>{"use strict";Pn();Qr();Cn();br();of()});import{randomUUID as PA}from"crypto";import{promises as je}from"fs";import Tt from"path";function Zc(e,t){let r=Tt.relative(e,t);return r===""||!Tt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Tt.sep}`)}function _A(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function el(e,t){return te({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function AA(e,t){return el(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function by(e){let t=await je.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 je.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function _n(e){for(let t of e){let r=await je.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!_A(t,r)||await je.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function IA(e,t,r){let[i,n]=await Promise.all([je.lstat(e),je.realpath(e),r?_n(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!el(i,t)||r&&!Zc(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function TA(e,t){let r=Tt.resolve(e),i=Tt.resolve(t);if(!Zc(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await by(r)],a=Tt.relative(r,i).split(Tt.sep).filter(Boolean),o=r;for(let s of a){await _n(n),o=Tt.join(o,s);try{await je.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await by(o);if(!Zc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await _n(n),n}async function $A(e){let t;try{t=await je.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 jA(e,t,r={}){let i=Tt.dirname(e),n=r.containedRoot?await TA(r.containedRoot,i):null;n||await je.mkdir(i,{recursive:!0});let a=Tt.join(i,`.${Tt.basename(e)}.${PA()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await je.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([je.lstat(a),je.realpath(a)]);if(await _n(n),!l.isFile()||l.isSymbolicLink()||!el(s,l)||!Zc(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(),!el(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 IA(a,c,n),await r.beforeCommit?.(),n){await _n(n);let l=await je.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!AA(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await nf(a,e),await rf(a)):await tf(a,e),await $A(i)}catch(l){if(await o?.close(),!n)await je.rm(a,{force:!0});else try{await _n(n),await je.rm(a,{force:!0})}catch{}throw l}}async function mt(e,t,r={}){await jA(e,t,r)}async function he(e,t,r={}){await mt(e,JSON.stringify(t,null,2)+`
|
|
175
|
+
`,r)}var ne=T(()=>{"use strict";af();Jt()});import{existsSync as Ny,promises as Ai}from"fs";import K from"path";import OA from"os";async function lf(e){try{return await Ai.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function DA(e){try{let t=await Ai.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function In(e,t){let r=K.relative(e,t);return r===""||!K.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${K.sep}`)}async function An(e){let t=[],r=e;for(;!await lf(r);){let n=K.dirname(r);if(n===r)break;t.push(K.basename(r)),r=n}let i=await Ai.realpath(r);return K.resolve(i,...t.reverse())}async function uf(e){try{return(await Ai.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function tl(e){let t=K.resolve(e);try{(await Ai.stat(t)).isDirectory()||(t=K.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=K.resolve(OA.homedir());for(;;){if(!(t===i&&r!==i)){let o=K.join(t,...ho.split("/")),s=t===r||await DA(o);if(await lf(o)&&s)return t}if(await lf(K.join(t,".git")))return t;let a=K.dirname(t);if(a===t)return r;t=a}}function rl(e){return Pi(e)}async function BA(e,t){let r=rl(t),i=K.resolve(e,...r.split("/")),n=await Ai.realpath(e),a=await An(i);if(!In(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function ei(e,t){let r=rl(t),i=await BA(e,r),n=K.join(i,"comet");if(await uf(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([An(i),An(n)]);if(!In(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=K.resolve(e),c=K.join(s,".comet","runtime","native");if(await uf(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Ai.realpath(s),An(c)]);if(!In(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:K.join(e,...ho.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:K.join(n,"specs"),changesDir:K.join(n,"changes"),archiveDir:K.join(n,"archive"),runtimeDir:c,changesRuntimeDir:K.join(c,"changes"),locksDir:K.join(c,"locks"),transactionsDir:K.join(c,"transactions")}}function ky(e){if(!HA.test(e))throw new Error(`Invalid Native change name: ${e}`)}function me(e,t){ky(t);let r=K.join(e.changesRuntimeDir,t);if(!Ee(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function df(e,t){ky(t);let r=K.join(e.changesDir,t,"runtime");if(!Ee(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function vt(e,t){let r=me(e,t);if(Ny(r))return r;let i=df(e,t);return Ny(i)?i:r}function pf(e,t){if(!t.startsWith("runtime/")||K.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=K.resolve(e,...t.slice(8).split("/"));if(!Ee(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function Ge(e,t){let r=K.resolve(t);if(Ee(e.runtimeDir,r))return e.runtimeDir;if(Ee(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function Ee(e,t){return In(K.resolve(e),K.resolve(t))}async function G(e,t){let r=K.resolve(e),i=K.resolve(t);if(!In(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await uf(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([An(r),An(i)]);if(!In(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var ho,HA,ie=T(()=>{"use strict";Qr();ho=".comet/config.yaml",HA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import LA from"path";function FA(e="docs",t="en"){return Jc(e,t)}async function Oe(e){let t=(await Xc(e))?.config??null;return t?.native?t:null}async function nl(e){let t=await Oe(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 al(e,t,r={}){let i=await po(e,{allowPartialProject:!0}),n=so(i.document?.value??{},t),a=LA.join(e,...ho.split("/"));await mt(a,oo(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await sf(e,i.identity)}})}async function Sy(e){let t=await tl(e.startPath),r=await Oe(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${ho} 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?rl(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??FA(i??"docs"),a=await ei(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var il,gt=T(()=>{"use strict";Qr();Cn();cf();ne();ie();il=Gc});function ee(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 mo({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var mo,vo=T(()=>{"use strict";mo=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 ff(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 $n(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}]`;ee(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:ff(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>ff(o,`${n}.evidence`)),note:ff(i.note,`${n}.note`)}})}function jn(e,t){if(!t)throw new Tn(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 Tn(o,s)}var Tn,go=T(()=>{"use strict";vo();Tn=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 sl(){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 Ii,wo,ol,On=T(()=>{"use strict";Ii="comet.native.v4",wo="comet.native.local-execution.v4",ol=["multi-session","single-session"]});var gf={};ed(gf,{NativePortableStateVersionConflictError:()=>yo,appendNativePortableHistory:()=>ke,compareAndSwapNativePortableState:()=>Bn,createNativePortableState:()=>xy,parseNativePortableState:()=>B,readNativePortableState:()=>yt,writeNativePortableState:()=>bo});import{promises as qA}from"node:fs";function He(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function De(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 xe(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 mf(e,t){return e===null?null:xe(e,t)}function vf(e,t){let r=xe(e,t);if(!zA.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Hn(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 JA(e,t){return e===null?null:se(e,t,Number.MIN_SAFE_INTEGER)}function ye(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ut(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function dl(e,t){return Ut(e,t,(r,i)=>xe(r,`${t}[${i}]`))}function Ti(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Dn(e,t){let r=xe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function ll(e,t,r=!1){let i=xe(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 wt(e,t){let r=He(e,t);return De(r,new Set(["text","truncated"]),t),{text:xe(r.text,`${t}.text`,{empty:!0}),truncated:Hn(r.truncated,`${t}.truncated`)}}function UA(e,t){let r=`Native spec_changes[${t}]`,i=He(e,r);De(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=xe(i.capability,`${r}.capability`);if(!VA.test(n))throw new Error(`${r}.capability is invalid`);let a=ye(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:ll(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:ll(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:vf(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 KA(e){let t="Native workspace",r=He(e,t);De(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=ye(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=mf(r.change_branch,`${t}.change_branch`),a=mf(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:ye(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 YA(e){let t="Native loop",r=He(e,t);De(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=dl(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Ti(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:ye(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ye(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:mf(r.next_action,`${t}.next_action`)}}function XA(e,t){let r=`Native acceptance[${t}]`,i=He(e,r);De(i,new Set(["id","source","text","result","reason"]),r);let n=xe(i.id,`${r}.id`);if(!WA.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:ll(i.source,`${r}.source`),text:xe(i.text,`${r}.text`),result:ye(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:wt(i.reason,`${r}.reason`)}}function QA(e,t){let r=`Native builder_handoff.checks[${t}]`,i=He(e,r);return De(i,new Set(["name","result","note"]),r),{name:wt(i.name,`${r}.name`),result:ye(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:wt(i.note,`${r}.note`)}}function ZA(e){let t="Native builder_handoff",r=He(e,t);De(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=dl(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ti(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:He(r.review,`${t}.review`);return n&&De(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:xe(r.candidate_id,`${t}.candidate_id`),identity_provider:xe(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:xe(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),summary:wt(r.summary,`${t}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:$n(r.acceptance_review)},checks:Ut(r.checks,`${t}.checks`,QA),checks_truncated:Hn(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ut(r.known_limits,`${t}.known_limits`,(a,o)=>wt(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Hn(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ye(n.status,["passed"],`${t}.review.status`),summary:wt(n.summary,`${t}.review.summary`),reviewer_execution_ref:xe(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Dn(r.submitted_at,`${t}.submitted_at`)}}function eI(e,t){let r=`Native blockers[${t}]`,i=He(e,r);De(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=dl(i.acceptance_ids,`${r}.acceptance_ids`);return Ti(n,`${r}.acceptance_ids`),{owner:ye(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:wt(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:ye(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function tI(e,t){let r=`Native verification.checks[${t}]`,i=He(e,r);return De(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:xe(i.id,`${r}.id`),name:wt(i.name,`${r}.name`),argv_display:Ut(i.argv_display,`${r}.argv_display`,(n,a)=>wt(n,`${r}.argv_display[${a}]`)),argv_truncated:Hn(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:ll(i.cwd_ref,`${r}.cwd_ref`,!0),status:ye(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:JA(i.exit_code,`${r}.exit_code`),duration_ms:se(i.duration_ms,`${r}.duration_ms`)}}function rI(e){let t="Native verification",r=He(e,t);De(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ut(r.checks,`${t}.checks`,tI);Ti(i.map(a=>a.id),`${t}.checks IDs`);let n=xe(r.identity_provider,`${t}.identity_provider`);return{candidate_id:xe(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:xe(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":ye(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ye(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:wt(r.summary,`${t}.summary`),risks:Ut(r.risks,`${t}.risks`,(a,o)=>wt(a,`${t}.risks[${o}]`)),risks_truncated:Hn(r.risks_truncated,`${t}.risks_truncated`),completed_at:Dn(r.completed_at,`${t}.completed_at`)}}function Ey(e,t){let r=`Native history[${t}]`,i=He(e,r);De(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=dl(i.unresolved_ids,`${r}.unresolved_ids`);return Ti(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:ye(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:wt(i.summary,`${r}.summary`),completed_at:Dn(i.completed_at,`${r}.completed_at`)}}function iI(e){let t="Native history_overflow.outcome_counts",r=He(e,t),i=["pass","fail","blocked","execution-error","recovery"];return De(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 nI(e){let t="Native history_overflow",r=He(e,t);De(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:Dn(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Dn(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=iI(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 aI(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&&jn(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 oI(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 B(e){let t=He(e,"Native portable state");if(De(t,GA,"Native portable state"),t.schema!==Ii)throw new Error(`Native portable state schema must be ${Ii}`);let r=xe(t.name,"Native state name");if(!MA.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=Ut(t.spec_changes,"Native spec_changes",UA);Ti(i.map(s=>s.capability),"Native spec change capabilities");let n=Ut(t.acceptance,"Native acceptance",XA);Ti(n.map(s=>s.id),"Native acceptance IDs");let a=Ut(t.history,"Native history",Ey);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Ii,name:r,language:ye(t.language,["en","zh-CN"],"Native state language"),phase:ye(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ye(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:vf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:vf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ye(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:KA(t.workspace),loop:YA(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:ZA(t.builder_handoff),blockers:Ut(t.blockers,"Native blockers",eI),verification:t.verification===null?null:rI(t.verification),history:a,history_overflow:nI(t.history_overflow),verification_result:ye(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ye(t.verification_report,["verification.md"],"Native verification_report"),archived:Hn(t.archived,"Native archived"),created_at:Dn(t.created_at,"Native created_at")};return aI(o),oI(o),o}function xy(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return B({schema:Ii,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:sl(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ke(e,t){let r=B(e),i=Ey(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 B({...r,history:n,history_overflow:a})}function sI(e,t){let r=(0,ul.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 yt(e){let t=await qA.readFile(e,"utf8");return B(sI(t,"Native portable state"))}async function bo(e,t,r={}){let i=B(t);await mt(e,(0,ul.stringify)(i),r)}async function cI(e,t){let r=cl.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);cl.set(e,a),await r;try{return await t()}finally{i(),cl.get(e)===a&&cl.delete(e)}}async function Bn(e){return cI(e.file,async()=>{let t=se(e.expectedStateVersion,"Native expected state version",1),r=B(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await yt(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new yo(t,i.state_version);return await bo(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await yt(e.file);if(n.state_version!==t)throw new yo(t,n.state_version)}}),r})}var ul,MA,VA,WA,zA,GA,yo,cl,at=T(()=>{"use strict";go();ul=hr(Gt(),1);ne();On();MA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WA=/^A[1-9][0-9]*$/u,zA=/^[a-f0-9]{64}$/u,GA=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"]),yo=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"};cl=new Map});import{promises as lI}from"node:fs";import uI from"node:path";function fl(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function pl(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 Cy(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 vI(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 Py(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 Ty(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===yf&&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),p=e.acceptance_index[l];u&&p&&(p.source!==u.source||p.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=>!_y(e.children,l)),Ay(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=>!_y(e.children,a)),Ay(i)?i:null}return null}function _y(e,t){return e.some(r=>r.covers.includes(t))}function Ay(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function bt(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 gI(e){let t=fl(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=fl(n,`Native children acceptance_index.${i}`);if(pl(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 wI(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 p=e[l];if(p.source!==u.source||p.text!==u.text){let d=["source","text"].filter(f=>p[f]!==u[f]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function $y(e,t,r={}){let i=(0,Iy.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=fl(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==$i&&a!==ti)throw pl(n,Ry,"Native children contract"),new Error(`Native children schema must be ${$i} or ${ti}`);let o=a===$i?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(pl(n,o==="indexed-v2"?pI:Ry,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((d,f)=>{let h=fl(d,`Native child ${f}`);if(pl(h,o==="indexed-v2"?mI:o==="summary-v2"?hI:fI,`Native ${s} child fields (child ${f})`),typeof h.name!="string"||!dI.test(h.name))throw new Error(`Native child ${f} name is invalid`);let m=o==="summary-v2";if(m){if(typeof h.summary!="string"||h.summary.trim().length===0)throw new Error(`Native child ${h.name} summary must be a non-empty string`);if(h.summary.length>2e3)throw new Error(`Native child ${h.name} summary exceeds 2000 characters`)}return{name:h.name,summary:m?h.summary:null,depends_on:Cy(h.depends_on,`Native child ${h.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Cy(h.covers,`Native child ${h.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let d of c){let f=d.depends_on.filter(h=>!u.has(h));if(f.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${f.join(", ")}`)}vI(c);let p=r.policy==="advisory";if(a===yf){if(o==="indexed-v2"){let d=gI(n.acceptance_index);p||wI(d,t,r);let f=Object.keys(d);return p||Py(c,f,f),{schema:ti,acceptance_index:d,children:c}}return{schema:ti,children:c}}return t&&!p&&Py(c,t),{schema:$i,children:c}}async function Je(e){let t=uI.join(e.changeDir,wf);try{await lI.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await Z({root:e.changeDir,ref:wf}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=$y(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Ty(a,e.acceptanceIds,e.validation??{}):null}}var Iy,wf,$i,ti,yf,dI,Ry,pI,fI,hI,mI,hl=T(()=>{"use strict";Iy=hr(Gt(),1);rt();wf="children.yaml",$i="comet.native.children.v1",ti="comet.native.children.v2",yf=ti,dI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ry=new Set(["schema","children"]),pI=new Set(["schema","acceptance_index","children"]),fI=new Set(["name","depends_on","covers"]),hI=new Set(["name","summary","depends_on"]),mI=new Set(["name","depends_on","covers"])});function bf(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function Nf(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){bf(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Se,executionRef:bf(t.executionRef,"Native execution ref"),[jy]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:bf(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[Oy]:!0})}})}function ml(e){return typeof e=="object"&&e!==null&&e[Oy]===!0}function Hy(e){return typeof e=="object"&&e!==null&&e[jy]===!0}var jy,Oy,Se,ji=T(()=>{"use strict";jy=Symbol("comet.native.trusted-execution-identity"),Oy=Symbol("comet.native.trusted-verifier-envelope"),Se="skill-coordinated"});function vl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function No(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Oi(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function gl(e,t="/acceptance"){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((r,i)=>{let n=vl(r,`Native Verifier acceptance ${i}`);ee(n,["id","result","reason"],`Native Verifier acceptance ${i}`,`${t}/${i}`);let a=Oi(n.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(n.result)))throw new Error(`Native Verifier acceptance ${a} result is invalid`);return{id:a,result:n.result,reason:Oi(n.reason,`Native Verifier acceptance ${a} reason`)}})}function yI(e,t){let r=vl(e,"Native Verifier final result");if(ee(r,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result",t),!["pass","fail","blocked"].includes(String(r.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(r.risks)||!r.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:No(r.iteration,"Native Verifier iteration"),attempt:No(r.attempt,"Native Verifier attempt"),verdict:r.verdict,acceptance:gl(r.acceptance,`${t}/acceptance`),risks:r.risks,summary:Oi(r.summary,"Native Verifier summary")}}function bI(e,t,r){let i=vl(e,`Native Verifier check request ${t}`);if(ee(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`,`${r}/${t}`),!Array.isArray(i.argv)||!i.argv.every(a=>typeof a=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let n=No(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(n<1)throw new Error("Native Verifier check timeout must be positive");return{id:Oi(i.id,`Native Verifier check request ${t} ID`),name:Oi(i.name,`Native Verifier check request ${t} name`),executable:Oi(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:Oi(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:n,repeatable:i.repeatable}}function ko(e,t=""){let r=vl(e,"Native Verifier response");if(r.kind==="final-result")return ee(r,["kind","result"],"Native Verifier response",t),{kind:"final-result",result:yI(r.result,`${t}/result`)};if(r.kind==="request-checks"){if(ee(r,["kind","iteration","attempt","checks"],"Native Verifier response",t),!Array.isArray(r.checks)||r.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:No(r.iteration,"Native Verifier iteration"),attempt:No(r.attempt,"Native Verifier attempt"),checks:r.checks.map((i,n)=>bI(i,n,`${t}/checks`))}}throw new Error("Native Verifier response kind is invalid")}function Dy(e){if(!ml(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=ko(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=kf(i.result,r);return{...i,result:{...i.result,acceptance:o}}}function kf(e,t){gl(e.acceptance);let r=[...t.acceptanceIds],i=new Set(t.knownAcceptanceIds??r),n=new Set(t.previouslyPassedAcceptanceIds??[]),a=r.filter(m=>!i.has(m)),o=[...n].filter(m=>!i.has(m));if(a.length>0||o.length>0)throw new Error("Native Verifier acceptance binding is internally inconsistent");let s=new Set(r),c=e.acceptance.map(({id:m})=>m),l=c.filter((m,v)=>c.indexOf(m)!==v),u=c.filter(m=>!i.has(m)),p=r.filter(m=>!c.includes(m)),d=e.acceptance.filter(({id:m,result:v})=>s.has(m)||!i.has(m)?!1:!n.has(m)||v!=="passed").map(({id:m,result:v})=>`${m}=${v}`);if(l.length>0||u.length>0||p.length>0||d.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(l)].join(", ")||"none"}; unknown: ${u.join(", ")||"none"}; missing: ${p.join(", ")||"none"}; out-of-scope: ${d.join(", ")||"none"}). Return each required scope ID exactly once and no other acceptance IDs.`);let f=e.acceptance.filter(({id:m})=>s.has(m));if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let h=f.map(({result:m})=>m);if(e.verdict==="pass"&&h.some(m=>m!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!h.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!h.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return f}var So=T(()=>{"use strict";vo();ji()});function Nt(e,t){if(!NI.test(e))throw new Error(`${t} must be a Git commit`)}function Ue(e){return structuredClone(e)}function ot(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function kI(e,t){if(!Sf(t.dependsOn,e.children)){let r=t.dependsOn.filter(i=>e.children.find(({name:n})=>n===i)?.status!=="integrated");throw new Error(`Native Supervisor child ${t.name} dependency ${r[0]??"?"} is not integrated`)}}function Sf(e,t){let r=new Map(t.map(({name:i,status:n})=>[i,n]));return e.every(i=>r.get(i)==="integrated")}function By(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function Ro(e){Nt(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:Eo(e.contract,i.name),contractHash:$("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:xo,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 Eo(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 Ef(e){let t=Ue(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on];let o=Eo(e.contract,n.name),s=$("comet.native.supervisor-contract.v1",e.contract);n.contractHash&&n.contractHash!==s&&n.status!=="integrated"&&n.status!=="archived"&&(n.task=null,n.verifiedCommit=null,n.verification=null,n.checks=[],n.candidateCommit?(n.status="needs-reverify",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):Sf(n.dependsOn,t.children)?(n.status="ready",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):(n.status="pending",n.blocker=null)),n.acceptanceScope=o,n.contractHash=s,n.builderFailureCount??=0}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:Eo(e.contract,n.name),contractHash:$("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0});return t.stateVersion+=1,t}function ri(e,t,r){let i={child:e.child,runId:e.runId},n=(e.checkExecution?.checkStates??[]).filter(({status:o})=>o==="interrupted").map(({id:o})=>o),a=e.role==="builder"?[{kind:"supervisor-builder-result",...i,candidateCommit:"<candidate-commit>"},{kind:"supervisor-builder-failure",...i,reason:"<failure-reason>"}]:[{kind:"supervisor-checks",...i,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],materials:[],...n.length>0?{retry_check_ids:n}:{}},{kind:"supervisor-verifier-result",...i,verdict:"blocked",evidence:{summary:"<verification-summary>",checks:[],acceptance:(e.acceptance??[]).map(({id:o})=>({id:o,result:"blocked",reason:"<evidence>"})),receiptRef:e.checkExecution?.receiptRef??null}}];return{...e,controlProjectRoot:r,returnAction:{cwd:r,commandArgs:["comet","native","next",t,"--runner-input","<temporary-json-file>","--json"],inputOptions:a.map(o=>({name:o.kind,exclusiveGroup:"runner-input",template:o}))}}}function Co(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=Ue(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);kI(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n,acceptance:i.acceptanceScope??[{id:`child:${i.name}`,source:"children.yaml",text:i.summary??i.name}],contractHash:i.contractHash,verificationBoundary:"child-scope-parent-reverifies-all",checksReason:"not-run"};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,ot(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function Ly(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function xf(e,t){let r=Ly(e,t),i=Ue(e);return ot(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function wl(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=Ue(e),i=r.children.find(({name:a})=>a===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);let n=i.task.role;return n==="builder"?(i.builderFailureCount=(i.builderFailureCount??0)+1,i.status=i.builderFailureCount>=Nr?"blocked":"ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=n==="builder"&&(i.builderFailureCount??0)>=Nr?`Builder failed ${i.builderFailureCount} times; explicit Builder retry is required. Last failure: ${t.reason}`:t.reason,ot(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Po(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,ot(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Rf(e,t){Nt(t.candidateCommit,"Native Supervisor candidate commit");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.builderFailureCount=0,i.task=null,i.blocker=null,ot(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function Cf(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return kf({verdict:t.verdict,acceptance:t.evidence.acceptance??[]},{acceptanceIds:i.task.acceptance?.map(({id:n})=>n)??i.acceptanceScope?.map(({id:n})=>n)??[`child:${i.name}`],requiredChecksPassed:t.evidence.checks.length>0}),i.verification={...structuredClone(t.evidence)},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(t.verdict==="fail"?(i.status="ready",i.candidateCommit=null,i.verifiedCommit=null,i.verification=null,i.checks=[]):i.status="needs-reverify",i.blocker=t.evidence.summary),ot(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function Pf(e,t){if(!Number.isSafeInteger(t.expectedStateVersion)||t.expectedStateVersion<1)throw new Error("Native Supervisor Builder retry state version is invalid");if(e.stateVersion!==t.expectedStateVersion)throw new Error("Native Supervisor Builder retry input is stale");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.status!=="blocked"||i.task!==null||(i.builderFailureCount??0)<Nr)throw new Error(`Native Supervisor child ${t.child} is not waiting for an explicit Builder retry`);if(!Sf(i.dependsOn,r.children))throw new Error(`Native Supervisor child ${t.child} dependencies are not integrated`);return i.status="ready",i.candidateCommit=null,i.blocker=null,i.builderFailureCount=0,ot(r,{kind:"task-cancelled",child:i.name,runId:null,summary:"Explicit Builder retry authorized after the failure budget was exhausted"}),r.stateVersion+=1,r}function yl(e,t){Nt(t.integrationCommit,"Native Supervisor integration commit");let r=Ue(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,ot(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}function bl(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 NI,xo,Nr,Hi=T(()=>{"use strict";pe();So();NI=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;xo="comet.native.supervisor.v2",Nr=3});import _o from"node:path";import{promises as qy}from"node:fs";function _f(e,t){return _o.join(me(e,t),"supervisor")}function Di(e,t){return _o.join(_f(e,t),"state.json")}function My(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!==xo)throw new Error(`Native Supervisor state schema must be ${xo}`);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(Nt(t.integration.targetCommit,"Native Supervisor target commit"),Nt(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");Nt(n.candidateCommit,"Native Supervisor integration candidate commit"),Nt(n.integrationCommit,"Native Supervisor integration check commit"),Fy(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&&Nt(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(Nt(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&&Fy(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 D(e,t,r={}){try{let i=await qy.readFile(Di(e,t),"utf8"),n=JSON.parse(i);if(My(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(()=>(at(),gf)),c=await s(_o.join(o.changesDir,t,"comet-state.yaml")),l=await Je({changeDir:_o.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:bt(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:p})=>p===u.name)&&(u.acceptanceScope=Eo(l.contract,u.name),u.contractHash=$("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(()=>(at(),gf)),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 Nl(e,t){let r=await SI(e,t);if(r.length>0)throw new Error(`Native Supervisor Git binding cannot change while active child tasks exist: ${r.join(", ")}`)}async function SI(e,t){return(await D(e,t,{diagnostics:!0}))?.children.filter(({task:i})=>i!==null).map(({name:i})=>i)??[]}async function q(e,t){My(t),await qy.mkdir(e.changesRuntimeDir,{recursive:!0}),await he(Di(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Fy(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 kr=T(()=>{"use strict";ne();pe();hl();ie();Hi()});import{createHash as If,randomUUID as EI}from"node:crypto";import{promises as st}from"node:fs";import xI from"node:os";import Ke from"node:path";async function Af(e,t){let r=await st.lstat(e,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(t))throw new Error("Invalid process probe cache");let i=await st.readFile(e),n=await st.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 zy(e){try{let t=JSON.parse((await Af(Ke.join(e,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(t.file??""))return null;let r=Ke.join(e,t.file),i=await Af(r,65536);return If("sha256").update(i).digest("hex")===t.hash?r:null}catch{return null}}async function PI(e,t){let r,i=EI(),n=Ke.join(e,`probe-${i}.cs`),a=Ke.join(e,`probe-${i}.exe`),o=Ke.join(e,`probe-${i}.json`);try{if(await st.mkdir(e,{recursive:!0,mode:448}),(await st.lstat(e)).isSymbolicLink())return null;r=await st.open(Ke.join(e,"prepare.lock"),"wx",384);let s=await zy(e);if(s)return s;await st.writeFile(n,Wy,{flag:"wx",mode:384});let c;for(let u of["Framework64","Framework"]){let p=Ke.join(t,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await st.access(p),c=p;break}catch{}}if(!c)return null;await Gr(c,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,n],{timeoutMs:1500,maxBufferBytes:4096});let l=If("sha256").update(await Af(a,65536)).digest("hex");return await st.writeFile(o,JSON.stringify({file:Ke.basename(a),hash:l}),{flag:"wx",mode:384}),await st.rename(o,Ke.join(e,"probe.json")),a}catch{return null}finally{await st.unlink(n).catch(()=>{}),await st.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await st.unlink(Ke.join(e,"prepare.lock")).catch(()=>{}))}}async function Vy(e,t,r){try{let i=await Gr(Ke.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 Gr(Ke.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 _I(e,t){let r=kl.get(e);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:PI(e,t),retryAfter:1/0};return kl.set(e,i),i.promise.then(n=>{kl.get(e)===i&&(n?kl.delete(e):i.retryAfter=performance.now()+CI)}),i.promise}async function Gy(e,t={}){if(!Number.isSafeInteger(e)||e<=0)return null;let r=t.systemRoot??process.env.SystemRoot??"C:\\Windows",i=Ke.join(t.cacheRoot??Ke.join(xI.tmpdir(),"comet-process-identity"),RI),n=async l=>{if(!l)return null;try{let p=(await Gr(l,[String(e)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(p)?`win32-ps:${p}`:null}catch{return null}},a=await zy(i);if(a){let l=await n(a);return l||Vy(e,r,new AbortController().signal)}let o=_I(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),Vy(e,r,s.signal).then(c)])}catch{return null}finally{s.abort()}}var Wy,RI,CI,kl,Jy=T(()=>{"use strict";bn();Wy=`using System;
|
|
176
176
|
using System.Runtime.InteropServices;
|
|
177
177
|
class CometProcessIdentity {
|
|
178
178
|
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
|
|
@@ -185,82 +185,86 @@ class CometProcessIdentity {
|
|
|
185
185
|
Console.WriteLine(DateTime.FromFileTimeUtc(creation).Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0;
|
|
186
186
|
} finally { CloseHandle(handle); }
|
|
187
187
|
}
|
|
188
|
-
}`,
|
|
188
|
+
}`,RI=If("sha256").update(Wy).digest("hex"),CI=1e4,kl=new Map});import{promises as Uy}from"node:fs";function II(e){let t=$f.get(e);if(t){if(Date.now()-t.at>AI){$f.delete(e);return}return t.value}}async function ct(e){if(e===process.pid&&Tf!==null)return Tf;let t=II(e);if(t!==void 0)return t;let r=Sl.get(e);r||(r=TI(e),Sl.set(e,r));let i=await r;return Sl.get(e)===r&&Sl.delete(e),e===process.pid&&i!==null&&(Tf=i),i===null&&$f.set(e,{value:null,at:Date.now()}),i}async function TI(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Uy.readFile(`/proc/${e}/stat`,"utf8"),Uy.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 Gy(e);if(process.platform==="darwin"){let t=(await Gr("/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 El(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function Ln(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 ct(e);return r===t?"alive":r===null||El(r)!==El(t)&&Ky.has(El(r))&&Ky.has(El(t))?"unknown":"dead"}async function Fn(e,t){return await Ln(e,t)!=="dead"}var Tf,AI,$f,Sl,Ky,Ao=T(()=>{"use strict";bn();Jy();Tf=null,AI=1e4,$f=new Map,Sl=new Map;Ky=new Set(["win32-wmic","win32-ps"])});import{spawn as $I}from"node:child_process";import jf from"node:path";async function Io(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&jf.win32.isAbsolute(r)?jf.win32.resolve(r):"C:\\Windows",n=jf.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(p,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(p))};try{c=$I(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",p=>u(p===0)),l=setTimeout(()=>u(!1,!0),jI)}catch{u(!1)}});for(let o=0;o<OI;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var jI,OI,Of=T(()=>{"use strict";jI=1e3,OI=2});function Ye(e){return e.replace(HI,"$1 [REDACTED]").replace(DI,"[REDACTED PRIVATE KEY]").replace(BI,"$1[REDACTED]@").replace(LI,"[REDACTED TOKEN]").replace(FI,'$1"[REDACTED]"').replace(qI,"$1$2$1$3$4[REDACTED]$4").replace(MI,"$1$2[REDACTED]")}var HI,DI,BI,LI,FI,qI,MI,ii=T(()=>{"use strict";HI=/\b(Bearer|Basic)\s+[^\s"']+/giu,DI=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,BI=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,LI=/\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,FI=/("(?:[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,qI=/(["'])((?:[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,MI=/\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 VI,constants as WI,createWriteStream as zI,existsSync as Hf,promises as GI,statSync as JI}from"node:fs";import be from"node:path";function Xy(e,t){let r=be.relative(e,t);return r===""||!be.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${be.sep}`)}function Qy(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function To(e,t){if(t.length===0||t.includes("\\")||be.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||be.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=be.resolve(e),i=be.resolve(r,...t.split("/"));if(!Xy(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=JI(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}function qn(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}function Yy(e,t){return be.isAbsolute(e)||/[\\/]/u.test(e)?[be.resolve(t,e)]:(process.env.PATH??"").split(be.delimiter).map(r=>r.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean).map(r=>be.join(r,e))}function UI(e,t){if(process.platform==="win32"){let i=xi(e,process.env,t),n=be.win32.isAbsolute(i)?i:Yy(e,t).find(a=>Hf(a));if(!n||!Hf(n))throw new Error(`executable is not available: ${e}`);return[".bat",".cmd"].includes(be.win32.extname(n).toLowerCase()),void 0}let r=Yy(e,t).find(i=>Hf(i));if(!r)throw new Error(`executable is not available: ${e}`);try{VI(r,WI.X_OK)}catch(i){throw new Error(`executable is not executable: ${e}`,{cause:i})}}function lt(e,t){let r=new Set;t.forEach((i,n)=>{if(r.has(i.id))throw new Error(`Native check plan duplicate ID ${i.id} at /checks/${n}/id`);r.add(i.id);let a;try{if(a=jo(e,i),process.platform==="win32"){let o=xi(i.executable,process.env,a),s=be.win32.extname(o).toLowerCase();(s===".bat"||s===".cmd")&&Ya(i.argv)}UI(i.executable,a)}catch(o){throw new Error(`Native check ${i.id} is invalid at /checks/${n}: ${o.message}`,{cause:o})}})}function $o(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=Ye(r);return KI.test(r)&&(t=!0),i})}function jo(e,t){if(Qy(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return To(e,t.cwdRef)}async function Bi(e){let{plan:t}=e;Qy(e.operationId,"Native check operation ID");let r=jo(e.projectRoot,t),i=be.join(e.runtimeDir,"logs","checks"),n=be.join(i,`${e.operationId}-${t.id}.log`);if(!Xy(be.resolve(e.runtimeDir),be.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await GI.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=zI(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=Lp(t.executable,t.argv,{cwd:r,env:process.env})}catch(v){o.destroy(),c(v);return}let u=!1,p=null,d=null,f=Promise.resolve(),h=!1,m=setTimeout(()=>{u=!0,Io(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);if(m.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",v=>{p=v,o.write(`
|
|
189
189
|
[comet] failed to start check: ${Ye(v.message)}
|
|
190
|
-
`)}),l.once("close",(v,g)=>{
|
|
191
|
-
`,"utf8"),await r.sync(),i=
|
|
190
|
+
`)}),l.once("close",(v,g)=>{h=!0,clearTimeout(m);let w=(e.now??(()=>new Date))();f.then(()=>{if(d!==null){o.destroy(),c(d);return}o.end(()=>{let N=u||p!==null||g!==null;s({id:t.id,name:t.name,argvDisplay:$o(t.argv),cwdRef:t.cwdRef,status:N?"interrupted":v===0?"passed":"failed",exitCode:v,signal:g,timedOut:u,durationMs:Math.max(0,w.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:w.toISOString(),repeatable:t.repeatable,logRef:be.relative(e.runtimeDir,n).split(be.sep).join("/")})})})}),o.once("error",v=>{clearTimeout(m),d??=v,h?f.then(()=>c(d)):Io(l).catch(()=>l.kill("SIGKILL"))}),l.pid!==void 0&&e.onSpawn){let v=l.pid;f=Promise.resolve().then(()=>e.onSpawn({pid:v})).catch(async g=>{d=g,l.exitCode===null&&l.signalCode===null&&await Io(l).catch(()=>l.kill("SIGKILL"))})}})}var KI,Mn=T(()=>{"use strict";Xa();Of();ii();KI=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu});import{AsyncLocalStorage as YI}from"async_hooks";import{randomUUID as tb}from"crypto";import{promises as kt}from"fs";import rb from"os";import ce from"path";function ZI(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function eT(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 ib(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 Rl(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Pt(r,i)?te(r,i):te(r,i)&&e.size===t.size}function Oo(e,t){return Rl(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function tT(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&&Oo(e.identity,t.identity)}async function St(e){let t,r;try{let i=await xn(e,Zy,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof It?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Zy} 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:eT(JSON.parse(t.toString("utf8")),e),identity:ib(r)}}async function rT(e){return(await St(e))?.owner??null}async function Bf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==rb.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await Ln(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function iT(e,t){try{await kt.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await kt.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Cl(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(!Oo(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await kt.mkdir(t,{recursive:!0});let i=ce.join(t,`${ce.basename(e.file)}.${e.owner.id}.${tb()}.removed`);try{await kt.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||!Rl(n.identity,e.identity))throw await iT(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await kt.rm(i,{force:!0}),"removed"}async function nb(e){let t=await ct(process.pid);return{id:tb(),pid:process.pid,hostname:rb.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function ab(e,t){let r;try{r=await kt.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await rT(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)+`
|
|
191
|
+
`,"utf8"),await r.sync(),i=ib(await r.stat({bigint:!0}))}finally{await r.close()}let n=await St(e);if(!i||!n||n.owner.id!==t.id||!Rl(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function nT(e,t){let r=await G(e.runtimeDir,e.locksDir);await kt.mkdir(r,{recursive:!0});let i=await G(e.runtimeDir,ce.join(r,Df));await kt.mkdir(i,{recursive:!0});let n=await nb(t),a=ce.join(i,`.${n.id}.tmp`),o=ce.join(i,`${n.id}.claim`);try{let s=await ab(a,n);await kt.rename(a,o);let c=await St(o);if(!c||!Rl(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 kt.rm(a,{force:!0})}}async function aT(e){let t=ce.dirname(e.file),r=!1,i=ce.basename(e.file);for(let n of await kt.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=ce.join(t,n.name);if(ce.resolve(a)!==ce.resolve(e.file))try{let o=await St(a),s=await Bf(o);if(s.status==="missing")continue;let c=await St(a);if(!c)continue;if(!o||c.owner.id!==o.owner.id||!Oo(c.identity,o.identity)){n.name<i&&(r=!0);continue}if(s.status==="stale"&&o){await Cl(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function ob(e){let t=await St(e.file);if(t){if(t.owner.id!==e.owner.id||!Oo(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Cl(t,ce.dirname(e.file))}}async function oT(e,t){let r=Date.now()+XI;for(;;){let i=await nT(e,t);if(!await aT(i))return i;if(await ob(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 sT(e){let t=xl.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return xl.set(e,n),await t,()=>{r(),xl.get(e)===n&&xl.delete(e)}}async function Pl(e,t,r){let i=ce.resolve(e.locksDir),n=eb.getStore();if(n?.has(i))return r();let a=await sT(i);try{let o=await oT(e,t),s=new Map(n??[]);return s.set(i,o),await eb.run(s,async()=>{try{return await r()}finally{await ob(o)}})}finally{a()}}async function sb(e,t,r){let i=[...new Map(e.map(a=>[ce.resolve(a.locksDir),a])).values()].sort((a,o)=>ce.resolve(a.locksDir).localeCompare(ce.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Pl(o,t,()=>n(a+1)):r()};return n(0)}async function _l(e,t,r){return Pl(e,`acquire ${t}`,async()=>{let i=await G(e.runtimeDir,e.locksDir);await kt.mkdir(i,{recursive:!0});let n=await G(e.runtimeDir,ce.join(i,ZI(t))),a=await nb(r),o=await ab(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Al(e){await St(e.file)&&await Pl({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${ce.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(!Oo(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=ce.join(e.locksDir,Df);await Cl(t,r)})}function cT(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 cb(e){return Bf(await St(e))}async function lb(e,t,r,i={}){return Pl(e,`take over ${ce.basename(t)}`,async()=>{let n=await G(e.runtimeDir,e.locksDir),a=await G(e.runtimeDir,t);if(ce.resolve(ce.dirname(a))!==ce.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await St(a),s=await Bf(o);if(s.status==="missing")return{status:"missing"};if(r&&!tT(r,s))return{status:"changed",diagnosis:s};let c=i.allowAgedUnknown===!0&&s.status==="unknown"&&cT(o?.owner??null)>=QI;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=ce.join(n,Df);return await Cl(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var Zy,Df,XI,QI,eb,xl,Ho=T(()=>{"use strict";lo();Ao();ie();Jt();Zy=16*1024,Df=".coordinator",XI=5e3,QI=900*1e3,eb=new YI,xl=new Map});import{createHash as lT}from"node:crypto";function qi(e){return e.replaceAll(`\r
|
|
192
192
|
`,`
|
|
193
193
|
`).replaceAll("\r",`
|
|
194
|
-
`)}function
|
|
195
|
-
`),i=
|
|
194
|
+
`)}function Vn(e){return lT("sha256").update(qi(e)).digest("hex")}function Vf(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z(`${t} must be an object`);return e}function mb(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new z(`${r} has unknown field(s): ${i.join(", ")}`)}function Wf(e,t){if(typeof e!="string"||e.trim().length===0)throw new z(`${t} must be a non-empty string`);return e.trim()}function db(e,t){if(e!==void 0){if(typeof e!="string")throw new z(`${t} must be text`);return qi(e).replace(/^\n+|\n+$/gu,"")}}function Il(e,t){let r=Wf(e,t).toLowerCase();if(!dT.test(r))throw new z(`${t} must be a SHA-256 hash`);return r}function pb(e,t,r){let i=Vf(e,t),n=Object.entries(i);if(n.length>ub)throw new z(`${t} must contain at most ${ub} entries`);let a={};for(let[o,s]of n){if(qf(o,`${t} ID`)!==o)throw new z(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=Il(s,`${t}.${o}`)}return a}function qf(e,t){let r=Wf(e,t);if(!hb.test(r))throw new z(`${t} is not a valid stable requirement ID`);return r}function pT(e,t){let r=Wf(e,t);if(!uT.test(r))throw new z(`${t} is not a valid capability ID`);return r}function fT(e,t){let r=`Native delta operations[${t}]`,i=Vf(e,r);mb(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=qf(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new z(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:qf(i.to_id,`${r}.to_id`),c=db(i.title,`${r}.title`),l=db(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:Il(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!l?.trim())throw new z(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!l?.trim())throw new z(`${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 z(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||l==="")throw new z(`${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 hT(e){let t=Vf(e,"Native delta");if(mb(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==Lf)throw new z(`Native delta schema must be ${Lf}`);let r=pT(t.capability,"Native delta capability"),i=Il(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new z("Native delta base_version must be a positive integer");let n=t.legacy_hash===void 0?void 0:Il(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=pb(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:pb(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new z("Native delta operations must be an array");let s=t.operations.map(fT),c=new Set;for(let[l,u]of s.entries()){let p=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let d of p){if(c.has(d))throw new z(`Native delta operations contain duplicate or overlapping requirement ID ${d} at ${l}`);c.add(d)}}if(o!==void 0){if(a===void 0)throw new z("Native delta independent_requirements requires base_requirements");for(let[l,u]of Object.entries(o)){if(c.has(l))throw new z(`Native delta requirement ${l} cannot be both addressed and independent`);let p=a[l];if(u===null?p!==void 0:p!==u)throw new z(`Native delta independent_requirements does not match baseline ${l}`)}}return{schema:Lf,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 mT(e){let t=(0,Mf.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new z(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function Do(e){return hT(typeof e=="string"?mT(e):e)}function vT(e){let t=/^\s{0,3}(#{1,6})\s+/u.exec(e);return t?t[1].length:null}function gT(e){let t=[],r=null;for(let[i,n]of e.entries()){let a=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(n.trimEnd());if(a){r?a[1][0]===r.marker&&a[1].length>=r.length&&a[2].trim().length===0&&(r=null):r={marker:a[1][0],length:a[1].length};continue}if(r)continue;let o=/^(\s{0,3})(#{2,6})\s+Requirement:\s*([^\s]+)(?:\s+(.*?))?\s*$/u.exec(n);if(!o)continue;let s=o[3];if(!hb.test(s))throw new z(`Native total Spec requirement ID is invalid: ${s}`);t.push({line:i,level:o[2].length,id:s,title:o[4]?.trim()??""})}return t}function Fi(e){let t=qi(e),r=t.split(`
|
|
195
|
+
`),i=gT(r),n=[],a=new Set;for(let l of i){if(a.has(l.id))throw new z(`Native total Spec contains duplicate requirement ID ${l.id}`);a.add(l.id);let u=r.length;for(let p=l.line+1;p<r.length;p+=1){if(i.some(f=>f.line===p)){u=p;break}let d=vT(r[p]);if(d!==null&&d<=l.level){u=p;break}}n.push({start:l.line,end:u,marker:l})}let o=new Map;for(let l of n){let u=`${r.slice(l.start,l.end).join(`
|
|
196
196
|
`)}${l.end<r.length?`
|
|
197
|
-
`:""}`,
|
|
198
|
-
`).replace(/^\n/u,"").replace(/\n+$/u,"");o.set(l.marker.id,{id:l.marker.id,level:l.marker.level,title:l.marker.title,body:
|
|
197
|
+
`:""}`,p=r.slice(l.start+1,l.end).join(`
|
|
198
|
+
`).replace(/^\n/u,"").replace(/\n+$/u,"");o.set(l.marker.id,{id:l.marker.id,level:l.marker.level,title:l.marker.title,body:p,raw:u,startLine:l.start,endLine:l.end})}let s=[],c=0;for(let l of n)s.push(r.slice(c,l.start).join(`
|
|
199
199
|
`)),c=l.end;return s.push(r.slice(c).join(`
|
|
200
200
|
`)),{text:t,lines:r,requirements:o,legacyText:s.join(`
|
|
201
|
-
`)}}function
|
|
201
|
+
`)}}function zf(e){return Vn(e)}function Sr(e){return Vn(e)}function vb(e){let t=Fi(e).legacyText;return Vn(t.split(`
|
|
202
202
|
`).filter(r=>r.trim().length>0).join(`
|
|
203
|
-
`).trim())}function
|
|
203
|
+
`).trim())}function gb(e,t){let r=Fi(e),i=[];for(let n of t.operations){if(n.operation==="remove")continue;let a=n.operation==="rename"?n.to_id:n.id,o=r.requirements.get(a);if(!o)throw new z(`Native delta target Spec is missing requirement ${a} for ${n.operation}`);i.push(o.raw.trimEnd())}return i.length===0?"":`${i.join(`
|
|
204
204
|
|
|
205
205
|
`)}
|
|
206
|
-
`}function
|
|
206
|
+
`}function Tl(e,t,r,i){let n=`${"#".repeat(e)} Requirement: ${t}${r?.trim()?` ${r.trim()}`:""}`,a=qi(i).replace(/\n+$/u,"");return[n,"",...a.split(`
|
|
207
207
|
`),"",""].join(`
|
|
208
|
-
`)}function
|
|
208
|
+
`)}function Ff(e){return e.operation==="rename"?[e.id,e.to_id]:[e.id]}function $l(e,t){if(e.operation==="rename"){if(!t)throw new z(`Rename target does not exist: ${e.id}`);return{id:e.to_id,level:t.level,title:e.title??t.title,body:e.body??t.body}}return{id:e.id,level:t?.level??2,title:e.title??t?.title,body:e.body??t?.body??""}}function wT(e,t,r){let i=Fi(e),n=[...i.lines],a=i.requirements.get(t.id);if(!a)throw new z(`Requirement target disappeared: ${t.id}`);return n.splice(a.startLine,a.endLine-a.startLine,...r.split(`
|
|
209
209
|
`)),n.join(`
|
|
210
|
-
`)}function
|
|
210
|
+
`)}function yT(e,t){let r=qi(e),i=r.length===0||r.endsWith(`
|
|
211
211
|
|
|
212
212
|
`)?"":`
|
|
213
213
|
`,n=`${r}${i}`;return`${n.endsWith(`
|
|
214
214
|
`)||n.length===0?n:`${n}
|
|
215
|
-
`}${t}`}function
|
|
216
|
-
`)}else t=cT(t,s,_l(c.level,c.id,c.title,c.body))}r.push(...Dh(a)),i.push({id:a.id,operation:a.operation,status:"changed",targetIds:Dh(a)})}let n=Fi(t);return{markdown:n,base_hash:e.delta.base_hash,result_hash:Mn(n),rebased:e.rebased,changedRequirementIds:[...new Set(r)],operationResults:i}}function fb(e){let t=qi(e.baselineMarkdown);if(Mn(t.text)!==e.delta.base_hash)throw new Li([e.delta.capability],`Native delta base hash does not match the current total Spec for ${e.delta.capability}`);pT(e.delta,t),dT(e.delta,t);for(let r of e.delta.operations)e.allowAlreadyApplied&&hb(r,t)||uT(r,t);return hT({baselineMarkdown:t.text,delta:e.delta,allowAlreadyApplied:e.allowAlreadyApplied??!1,rebased:!1})}var Lh,Hh,cb,eT,lb,tT,ab,z,Li,Vh=T(()=>{"use strict";Lh=fr(Gt(),1),Hh="comet.native.delta.v1",cb="delta.yaml",eT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lb=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,tT=/^[a-f0-9]{64}$/iu,ab=512,z=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}},Li=class extends Error{code="native-delta-conflict";conflictIds;constructor(t,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(t)]}}});var Kt,Yt,Xt,Do=T(()=>{"use strict";Kt="comet.native.v3",Yt="comet.native.v2",Xt="comet.native.v1"});import fT from"node:path";function qo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function wb(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 Fo(e){if(!gb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function yb(e){if(!gb.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function bb(e,t){if(e.length===0||fT.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function kT(e,t){let r=qo(e,`spec_changes[${t}]`);if(wb(r,gT,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(yb(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"&&bb(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"||!zh.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"||!zh.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 ST(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 Gh(e,t){if(wb(e,t,xr),typeof e.name!="string")throw new Error("Native change name is required");if(Fo(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"||!wT.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&&!yT.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(kT),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"||!bT.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"&&bb(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!ST(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 Vn(e){let t=qo(e,xr);if(t.schema!==Xt)throw new Error(`Expected ${Xt}`);return{schema:Xt,...Gh(t,mT)}}function Lo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Wh(e,t,r){if(e===null)return null;let i=typeof e=="string"?NT.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 ET(e){if(e==null)return null;if(typeof e!="string"||!zh.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function xT(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 Wn(e){let t=qo(e,xr);if(t.schema!==Yt)throw new Error(`Expected ${Yt}`);if(Lo(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Yt} minimum_runtime_version must be 2`);return{schema:Yt,minimum_runtime_version:2,revision:Lo(t.revision,"Native v2 revision"),...Gh(t,vb)}}function Mi(e){let t=qo(e,xr);if(t.schema!==Kt){if(t.schema===Xt||t.schema===Yt){let o=t.schema===Xt?Vn(t):Wn(t);throw new Bo(o.name,o.schema)}throw new Qt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Lo(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Qt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Lo(t.revision,"Native revision"),n=Gh(t,vT),a=ET(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Kt,minimum_runtime_version:3,revision:i,verification_protocol:xT(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Wh(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Wh(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Wh(t.partial_allowance,"Native partial_allowance","allowances")}}function Jh(e){let t=qo(e,xr);if(t.schema===Xt){let n=Vn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Kt}`}}if(t.schema===Yt){let n=Wn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Kt}`}}if(t.schema!==Kt){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 Qt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Lo(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Qt(t.schema,r).message};let i=Mi(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var mb,mT,vb,vT,gT,wT,yT,bT,xr,zh,gb,NT,Bo,Qt,Il=T(()=>{"use strict";Do();mb=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],mT=new Set(mb),vb=new Set([...mb,"minimum_runtime_version","revision"]),vT=new Set([...vb,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),gT=new Set(["capability","operation","source","base_hash"]),wT=new Set(["shape","build","verify","archive"]),yT=new Set(["implicit","confirmed"]),bT=new Set(["pending","pass","fail"]),xr="comet-state.yaml",zh=/^[a-f0-9]{64}$/u,gb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NT=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Bo=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"},Qt=class extends Error{constructor(r,i){super(r!==Kt||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"}});function RT(e,t){return Uh[e][t]}function Kh(e,t){return kb[e][t]??Sb[e][t]}function Tl(e){return Eb.get(e.trim().toLocaleLowerCase("en-US"))??null}function $l(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>`# ${RT(e,i)}
|
|
217
|
-
|
|
218
|
-
`
|
|
215
|
+
`}${t}`}function wb(e,t){if(e.operation==="add"||e.operation==="modify"){let a=t.requirements.get(e.id);if(!a)return!1;let o=$l(e,e.operation==="modify"?a:void 0);return a.raw===Tl(o.level,o.id,o.title,o.body)}if(e.operation==="remove")return!1;let r=t.requirements.get(e.to_id),i=t.requirements.get(e.id);if(!r||i)return!1;let n=$l(e,{id:e.id,level:r.level,title:r.title,body:r.body,raw:r.raw,startLine:r.startLine,endLine:r.endLine});return r.raw===Tl(n.level,n.id,n.title,n.body)}function bT(e,t){let r=t.requirements.get(e.id);if(e.operation==="add"){if(r)throw new z(`Add target already exists: ${e.id}`);return}if(!r)throw new z(`Native delta target does not exist: ${e.id}`);if(e.expected_hash!==zf(r.raw))throw new z(`Native delta ${e.operation} expected_hash does not match ${e.id}`);if(e.operation==="rename"&&t.requirements.has(e.to_id))throw new z(`Rename destination already exists: ${e.to_id}`)}function NT(e,t){if(e.base_requirements===void 0)return;let r=e.base_requirements,i=t.requirements;if(Object.keys(r).length!==i.size)throw new z("Native delta base_requirements must describe the complete total Spec baseline");for(let[n,a]of i)if(r[n]!==zf(a.raw))throw new z(`Native delta base_requirements does not match requirement ${n}`)}function kT(e,t){let r=vb(t.text);if(r!==Vn("")&&e.legacy_hash!==r)throw new z("Native delta modifying a legacy total Spec requires a matching legacy_hash")}function ST(e){let t=qi(e.baselineMarkdown),r=[],i=[];for(let a of e.delta.operations){let o=Fi(t),s=o.requirements.get(a.id);if(e.allowAlreadyApplied&&wb(a,o)){i.push({id:a.id,operation:a.operation,status:"already-applied",targetIds:Ff(a)});continue}if(a.operation==="add"){if(s)throw new Li([a.id],`Native delta add conflicts with existing requirement ${a.id}`);let c=$l(a,void 0);t=yT(t,Tl(c.level,c.id,c.title,c.body))}else{if(!s)throw new Li([a.id],`Native delta ${a.operation} target does not exist: ${a.id}`);if(a.expected_hash!==zf(s.raw))throw new Li([a.id],`Native delta ${a.operation} conflicts with concurrent requirement ${a.id}`);let c=$l(a,s);if(a.operation==="rename"&&Fi(t).requirements.has(a.to_id))throw new Li([a.id,a.to_id],`Native delta rename destination already exists: ${a.to_id}`);if(a.operation==="remove"){let l=[...Fi(t).lines];l.splice(s.startLine,s.endLine-s.startLine),t=l.join(`
|
|
216
|
+
`)}else t=wT(t,s,Tl(c.level,c.id,c.title,c.body))}r.push(...Ff(a)),i.push({id:a.id,operation:a.operation,status:"changed",targetIds:Ff(a)})}let n=qi(t);return{markdown:n,base_hash:e.delta.base_hash,result_hash:Vn(n),rebased:e.rebased,changedRequirementIds:[...new Set(r)],operationResults:i}}function yb(e){let t=Fi(e.baselineMarkdown);if(Vn(t.text)!==e.delta.base_hash)throw new Li([e.delta.capability],`Native delta base hash does not match the current total Spec for ${e.delta.capability}`);kT(e.delta,t),NT(e.delta,t);for(let r of e.delta.operations)e.allowAlreadyApplied&&wb(r,t)||bT(r,t);return ST({baselineMarkdown:t.text,delta:e.delta,allowAlreadyApplied:e.allowAlreadyApplied??!1,rebased:!1})}var Mf,Lf,fb,uT,hb,dT,ub,z,Li,Gf=T(()=>{"use strict";Mf=hr(Gt(),1),Lf="comet.native.delta.v1",fb="delta.yaml",uT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hb=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,dT=/^[a-f0-9]{64}$/iu,ub=512,z=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}},Li=class extends Error{code="native-delta-conflict";conflictIds;constructor(t,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(t)]}}});var Kt,Yt,Xt,Bo=T(()=>{"use strict";Kt="comet.native.v3",Yt="comet.native.v2",Xt="comet.native.v1"});import ET from"node:path";function qo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Sb(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 Mo(e){if(!kb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Eb(e){if(!kb.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function xb(e,t){if(e.length===0||ET.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function TT(e,t){let r=qo(e,`spec_changes[${t}]`);if(Sb(r,CT,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Eb(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"&&xb(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"||!Uf.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"||!Uf.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 $T(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 Kf(e,t){if(Sb(e,t,xr),typeof e.name!="string")throw new Error("Native change name is required");if(Mo(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!PT.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&&!_T.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(TT),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"||!AT.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"&&xb(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!$T(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 Wn(e){let t=qo(e,xr);if(t.schema!==Xt)throw new Error(`Expected ${Xt}`);return{schema:Xt,...Kf(t,xT)}}function Fo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Jf(e,t,r){if(e===null)return null;let i=typeof e=="string"?IT.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 jT(e){if(e==null)return null;if(typeof e!="string"||!Uf.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function OT(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 zn(e){let t=qo(e,xr);if(t.schema!==Yt)throw new Error(`Expected ${Yt}`);if(Fo(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Yt} minimum_runtime_version must be 2`);return{schema:Yt,minimum_runtime_version:2,revision:Fo(t.revision,"Native v2 revision"),...Kf(t,Nb)}}function Mi(e){let t=qo(e,xr);if(t.schema!==Kt){if(t.schema===Xt||t.schema===Yt){let o=t.schema===Xt?Wn(t):zn(t);throw new Lo(o.name,o.schema)}throw new Qt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Fo(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Qt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Fo(t.revision,"Native revision"),n=Kf(t,RT),a=jT(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Kt,minimum_runtime_version:3,revision:i,verification_protocol:OT(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Jf(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Jf(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Jf(t.partial_allowance,"Native partial_allowance","allowances")}}function Yf(e){let t=qo(e,xr);if(t.schema===Xt){let n=Wn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Kt}`}}if(t.schema===Yt){let n=zn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Kt}`}}if(t.schema!==Kt){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 Qt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Fo(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Qt(t.schema,r).message};let i=Mi(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var bb,xT,Nb,RT,CT,PT,_T,AT,xr,Uf,kb,IT,Lo,Qt,jl=T(()=>{"use strict";Bo();bb=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],xT=new Set(bb),Nb=new Set([...bb,"minimum_runtime_version","revision"]),RT=new Set([...Nb,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),CT=new Set(["capability","operation","source","base_hash"]),PT=new Set(["shape","build","verify","archive"]),_T=new Set(["implicit","confirmed"]),AT=new Set(["pending","pass","fail"]),xr="comet-state.yaml",Uf=/^[a-f0-9]{64}$/u,kb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,IT=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Lo=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"},Qt=class extends Error{constructor(r,i){super(r!==Kt||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"}});function Cb(e,t){return Xf[e][t]}function Zf(e,t){return Pb[e][t]??_b[e][t]}function Ol(e){return Ab.get(e.trim().toLocaleLowerCase("en-US"))??null}function HT(e){return Vi[e].section}function DT(e,t){return Vi[e].subsections[t]}function $b(e){return`${Vi.en.subsections[e]}/${Vi["zh-CN"].subsections[e]}`}function jb(e){return Ib.has(e.trim().toLocaleLowerCase("en-US"))}function Ob(e){return Tb.get(e.trim().toLocaleLowerCase("en-US"))??null}function Hl(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>{if(i!=="scope")return`# ${Cb(e,i)}
|
|
217
|
+
`;let n=[`# ${Cb(e,i)}
|
|
218
|
+
`];n.push(`## ${HT(e)}
|
|
219
|
+
`);for(let a of Qf)n.push(`### ${DT(e,a)}
|
|
220
|
+
`);return n.join(`
|
|
221
|
+
`)}).join(`
|
|
222
|
+
`)}function Xe(e,t,r){return e==="zh-CN"?r:t}var Qf,Xf,Pb,_b,Ab,Rb,Ib,Tb,Vi,Wi=T(()=>{"use strict";Qf=["created","modified","deleted","notCreated"],Xf={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:"验证预期"}},Pb={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:"结论"}},_b={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:"结论"}},Ab=new Map,Rb=new Map,Ib=new Set,Tb=new Map,Vi={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(Xf)){for(let[t,r]of Object.entries(Xf[e]))Ab.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Pb[e]))Rb.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(_b[e]))Rb.set(r.toLocaleLowerCase("en-US"),t)}for(let e of Object.keys(Vi)){Ib.add(Vi[e].section.toLocaleLowerCase("en-US"));for(let[t,r]of Object.entries(Vi[e].subsections))Tb.set(r.toLocaleLowerCase("en-US"),t)}});function Bb(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 Hb(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 Db(e){return e.includes("-->")||e.includes("--!>")}function*Dl(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
219
223
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
220
|
-
`,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=
|
|
221
|
-
`),[],i)),"Brief",i)}function
|
|
222
|
-
`),s.context,i),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of jl(e)){let d=u?Cb(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 h=Mo(p[1]);if(h.length===0)throw new Error("Scenario title must not be empty");s={level:d.level,title:h,body:[],context:o.map(f=>f.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(),_b(a,"Specification",i)}var CT,Yh,Ol,Vo=T(()=>{"use strict";Vi();pe();CT="comet.native.acceptance.v1",Yh=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ol=Object.freeze({maxCriteria:1024})});import Ab from"node:path";function Ib(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Ab.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Ab.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function AT(e,t){return e.localeCompare(t,"en")}function Hl(e){let t=Ib(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((o,s)=>AT(o.capability,s.capability));if(new Set(r.map(o=>o.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=Xh(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:o,text:s})=>({source:o,text:s})),n=i.length;for(let o of r){let s=Ib(o.source,`Native spec source for ${o.capability}`);for(let c of Qh(o.markdown,s,Number.MAX_SAFE_INTEGER,"none",{resolveBriefReferences:e.resolveBriefReferences===!0})){if(c.briefAcceptanceRef!==void 0){let l=Number(c.briefAcceptanceRef.slice(1))-1;if(!Number.isSafeInteger(l)||l<0||l>=n)throw new Error(`Native Spec references unknown brief acceptance ${c.briefAcceptanceRef}: ${s}`);continue}i.push({source:s,text:c.text})}}let a=new Set;for(let o of i){o.text=Mo(o.text);let s=o.text;if(a.has(s))throw new Error(`Native acceptance contains a duplicate criterion: ${o.text}`);a.add(s)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((o,s)=>({id:`A${s+1}`,source:o.source,text:o.text}))}function Tb(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!_T.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function $b(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var _T,Dl=T(()=>{"use strict";Vo();_T=/^A[1-9]\d*$/u});function IT(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function J(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(IT(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var ni=T(()=>{"use strict"});import TT from"node:path";function BT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function LT(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function qT(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 FT(e){return e.schema===Xt?Vn(e):e.schema===Yt?Wn(e):Mi(e)}function MT(e){return TT.posix.normalize(e.replaceAll("\\","/"))}function VT(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:MT(t.source)})}function WT(e){return e==="shape"?"shape":"build"}function zT(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function GT(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function jb(e){let t=FT(e.state);Tb(e.acceptance);let r=WT(t.phase),i=r==="shape"?0:1,n=LT(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return B({schema:Ii,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:VT(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:zT(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:J(GT(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:nl(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Zh(e){let t=BT(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!$T.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Bl)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!OT.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!jT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!DT.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!HT.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Bl,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:qT(t.createdAt,"Native portable migration transaction createdAt")}}function Ob(e){switch(Zh(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Bl,$T,jT,OT,HT,DT,ef=T(()=>{"use strict";Il();Dl();at();ni();jn();Do();Bl="comet.native.portable-migration.v1",$T=new Set(["schema","id","change","fromSchema","status","createdAt"]),jT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,OT=/^[a-z0-9][a-z0-9-]{7,127}$/u,HT=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),DT=new Set([Xt,Yt,Kt])});import rf from"node:path";function qb(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fb(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 tf(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 Db(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function e$(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=qb(e,r);if(Fb(i,ZT,r),typeof i.capability!="string"||!Lb.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=tf(i.base_hash,`${r}.base_hash`),s=Db(i.delta_content,`${r}.delta_content`),c=Db(i.source_content,`${r}.source_content`),l=tf(i.expected_target_hash,`${r}.expected_target_hash`),u=tf(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=Ho(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(Sr(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(Sr(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||Sr(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 t$(e){let t=qb(e,"Native portable Archive transaction");if(Fb(t,QT,"Native portable Archive transaction"),t.schema!==Hb)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!KT.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Lb.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"||!YT.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"||!XT.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(e$);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:Hb,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 Ll(e){let t=JT.exec(e);if(t)return{kind:"archive",change:t[1]};let r=UT.exec(e);return r?{kind:"migration",change:r[1]}:null}function ql(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Ll(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return rf.join(e.transactionsDir,r)}async function nf(e,t){let r=Ll(t);if(!r)return null;let i=await Z({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=rf.join(e.transactionsDir,t);if(r.kind==="archive"){let s=t$(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=Zh(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Fl(e,t){let r=ql(e,t);try{return await nf(e,rf.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Mb(e){return e.kind==="archive"||e.journal.status!=="committed"}var Hb,Bb,JT,UT,KT,YT,XT,QT,ZT,Lb,Ml=T(()=>{"use strict";rt();Vh();ef();Hb="comet.native.archive-transaction.v4",Bb="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",JT=new RegExp(`^portable-archive-(${Bb})\\.json$`,"u"),UT=new RegExp(`^portable-migration-(${Bb})\\.json$`,"u"),KT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,YT=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,XT=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),QT=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ZT=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),Lb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as r$}from"node:crypto";import{constants as Vl,promises as $t}from"node:fs";import jt from"node:path";function zl(e,t){let r=jt.relative(e,t);return r===""||!jt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${jt.sep}`)}function i$(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function n$(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function a$(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Wl(e,t){return te({...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 af(e,t){let r=await $t.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await $t.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function o$(e,t,r){let i=jt.resolve(e),n=jt.resolve(t);if(!zl(i,n))throw new Error(`${r} is outside its managed root`);let a=[await af(i,r)],o=i;for(let s of jt.relative(i,n).split(jt.sep).filter(Boolean)){await Wi(a,r),o=jt.join(o,s);let c=await af(o,r);if(!zl(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Wi(a,r),a}async function Wi(e,t){for(let r of e){let i=await $t.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!n$(r,i)||await $t.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function s$(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 Wo(e){let t=e.maxBytes===null?null:i$(e.maxBytes),r=jt.resolve(e.file),i=await o$(e.root,jt.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>af(jt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Wi(i,e.label);let a=await $t.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=a$(a),s=await $t.realpath(r);if(!zl(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>zl(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Vl.O_RDONLY:Vl.O_RDONLY|Vl.O_NOFOLLOW|Vl.O_NONBLOCK,l=await $t.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,p]=await Promise.all([$t.lstat(r),$t.realpath(r)]);if(await Wi(i,e.label),await Wi(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==s||!Wl(o,u)||!Wl(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await s$(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[f,m,v]=await Promise.all([l.stat(),$t.lstat(r),$t.realpath(r)]);if(await Wi(i,e.label),await Wi(n,e.label),!m.isFile()||m.isSymbolicLink()||v!==s||!Wl(o,f)||!Wl(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:r$("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}var Zt=T(()=>{"use strict";ne();Jt()});import Rr from"path";import{TextDecoder as l$}from"util";function Jl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ul(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 Gb(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function of(e,t){if(typeof e!="string"||e.length===0||Rr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Gl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Vb(e,t){if(of(e,t),e.includes("\\")||e!==Rr.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 m$(e,t){let r=Jl(e,`transaction operations[${t}]`);if(Ul(r,d$,`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`);of(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&of(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 Jb(e){let t=Jl(e,"Native Archive transaction journal");if(Ul(t,p$,"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"||!zb.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(!Gb(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Gl(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=Jl(s,`Archive transaction operations[${c}]`);if(Ul(l,h$,`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`);Vb(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Vb(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Gl(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(Gl(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`);Gl(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 v$(e){let t=Jl(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Jb(t);if(Ul(t,u$,"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"||!zb.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Rr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Rr.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(!Gb(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(m$),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 g$(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Rr.join(e.transactionsDir,t)}function Ub(e,t){let r=g$(e,t);return{directory:r,journal:Rr.join(r,"transaction.json"),events:Rr.join(r,"events.jsonl"),staged:Rr.join(r,"staged"),backups:Rr.join(r,"backups")}}async function cf(e,t){let r=Ub(e,t);return await Promise.all(Object.values(r).map(i=>G(e.runtimeDir,i))),r}async function lf(e,t,r={}){let i=await cf(e,t),n=await Wo({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(f$.decode(n.bytes)),o=v$(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var u$,d$,p$,h$,zb,f$,Kl=T(()=>{"use strict";ne();ie();Zt();u$=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),d$=new Set(["id","type","source","target","staged","backup"]),p$=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),h$=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),zb=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),f$=new l$("utf-8",{fatal:!0})});import{promises as w$}from"fs";import y$ from"path";async function b$(e,t,r){let i;try{i=await w$.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 lf(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(Ll(n.name))try{let a=await nf(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Mb(a))return!0}catch{return!0}return!1}async function N$(e,t){let r=Date.now()+5e3,i=y$.join(e.locksDir,"root-move.lock");for(;;)try{return await Rl(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await ib(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await nb(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 A(e,t,r,i){let n=await N$(e,t);try{if(await tl(e.projectRoot),await b$(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Cl(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
|
|
223
|
-
`)}}}var ve=T(()=>{"use strict";gt();
|
|
224
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function hf(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 X$(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function sN(e){let t=el(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?X$(n):void 0;if(a&&!a())return!1;let o=hf(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=hf(r,c,a),o===null||o.size===0)return!1}return hf(r,o,a)?.has(r.length)??!1}}function Q$(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>el(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>el(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=Y$(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(sN),excludeMatchers:r.map(sN),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 Et(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Un(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ir(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function uN(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=oN.posix.normalize(e);if(r!==e||oN.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function Z$(e,t){let r=Et(e,`Native snapshot entry ${t}`);xt(r,M$,`Native snapshot entry ${t}`);let i=uN(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!nu.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:ir(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!U$.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function ej(e,t){let r=Et(e,`Native snapshot omission ${t}`);if(xt(r,V$,`Native snapshot omission ${t}`),!G$.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!J$.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:uN(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:ir(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function tj(e){let t=Et(e,"Native snapshot omission overflow");if(xt(t,W$,"Native snapshot omission overflow"),typeof t.hash!="string"||!nu.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:Un(t.count,"Native snapshot omission overflow count")}}function Jn(e,t){let r=Et(e,t);if(xt(r,L$,t),typeof r.hash!="string"||!nu.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=ir(r.recordCount,`${t} recordCount`),n=ir(r.storedRecordCount,`${t} storedRecordCount`),a=ir(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 cN(e){let t=Et(e,"Native Git selection evidence");if(xt(t,B$,"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=Jn(t.stageBefore,"Native Git selection stageBefore"),i=Jn(t.combined,"Native Git selection combined"),n=Jn(t.stageAfter,"Native Git selection stageAfter"),a=Jn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Jn(t.finalCombined,"Native Git selection finalCombined"),s=Jn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!iu(r,n)||!iu(n,a)||!iu(i,o)||!iu(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 lN(e,t){let r=Et(e,t);if(xt(r,F$,t),typeof r.hash!="string"||!nu.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=ir(r.visitedNodeCount,`${t} visitedNodeCount`),n=ir(r.recordCount,`${t} recordCount`),a=ir(r.storedRecordCount,`${t} storedRecordCount`),o=ir(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 rj(e){let t=Et(e,"Native physical selection evidence");if(xt(t,q$,"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=lN(t.before,"Native physical selection before"),i=lN(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!K$(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 ff(e){let t=Et(e,"Native content snapshot manifest");if(xt(t,$$,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!z$.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let b=Et(t.capture,"Native content snapshot capture");if(xt(b,H$,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=b.gitSelection===void 0?void 0:cN(b.gitSelection),k=b.physicalSelection===void 0?void 0:rj(b.physicalSelection),S=null;if(b.projection!==void 0){let C=Et(b.projection,"Native content snapshot projection");if(xt(C,D$,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");S={provider:"git",...C.selection===void 0?{}:{selection:cN(C.selection)}}}if(b.provider==="git"){if(k||S)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&S)throw new Error("Native physical-tree capture cannot combine selection and projection");r=S?{provider:"physical-tree",projection:S}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}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=Et(t.limits,"Native content snapshot limits");xt(i,j$,"Native content snapshot limits");let n={maxFiles:Un(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Un(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Un(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Un(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Un(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=Et(t.policy,"Native snapshot policy");if(xt(b,O$,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Q$({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(Z$),s=t.omitted.map(ej),c=ir(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:tj(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,x)=>b+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>T$||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),p=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...p])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||p.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,f=h?.status==="overflow"||h?.status==="overflow-and-changed",m=h?.status==="changed"||h?.status==="overflow-and-changed";if(f!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(m!==(p.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(b=>b.reason==="physical-enumeration-limit"),g=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...v,...g])if(b.path!=="."||b.size!==null||b.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 w=r?.physicalSelection,N=w?.status==="overflow"||w?.status==="overflow-and-changed",y=w?.status==="changed"||w?.status==="overflow-and-changed";if(N!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(y!==(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}:{}}}var oV,T$,$$,j$,O$,H$,D$,B$,L$,q$,F$,M$,V$,W$,z$,G$,J$,nu,U$,sV,cV,lV,uV,dV,Go=T(()=>{"use strict";wn();ne();gt();rr();Jt();ie();Zt();Za();oV={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},T$=1e3,$$=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),j$=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),O$=new Set(["schema","include","exclude","hash"]),H$=new Set(["provider","gitSelection","physicalSelection","projection"]),D$=new Set(["provider","selection"]),B$=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),L$=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),q$=new Set(["schema","status","before","after"]),F$=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),M$=new Set(["path","hash","size","type","gitObjectId"]),V$=new Set(["path","size","type","reason"]),W$=new Set(["ref","hash","count"]),z$=new Set(["change-created","legacy-migration","explicit"]),G$=new Set(["file","directory","other"]),J$=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"]),nu=/^[a-f0-9]{64}$/u,U$=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,sV=64*1024,cV=64*1024,lV={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},uV={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};dV=(1n<<256n)-1n});import{createHash as wN}from"node:crypto";import dN from"path";function Te(e,t){return e<t?-1:e>t?1:0}function vf(e){if(!wf.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function cj(e,t){return e===t?0:e===null?-1:t===null?1:Te(e,t)}function si(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=dN.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||dN.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function NN(e,t){return e==="."?e:si(e,t)}function Kn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function lj(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:si(e.path,`${t} path`),hash:e.hash,size:Kn(e.size,`${t} size`),type:"file"}}function uj(e,t){return{path:NN(e.path,`${t} path`),size:e.size===null?null:Kn(e.size,`${t} size`),type:e.type,reason:e.reason}}function dj(e,t){return Te(e.path,t.path)||Te(e.hash,t.hash)||e.size-t.size}function pj(e,t){return Te(e.path,t.path)||Te(e.reason,t.reason)||Te(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Ko(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
224
|
+
`,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=Hb(l,t);else if(r)Db(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let p=Hb(l,null);if(p!==null)t=p;else{let d=l.trimStart();if(d.startsWith("<!--")&&!Db(d))r=!0;else{let f=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);f&&n.has(f[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${f[1]}\\s*>`,"iu").test(d)&&(i=f[1])}}}if(c===-1)break;o=c+1}}function Vo(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Lb(e,t,r,i=[],n="content-hash"){let a=Vo(r),o=t.replaceAll("\\","/").trim(),s=i.map(Vo);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-${$(BT,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Fb(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 LT(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Dl(e)){n=s+1;let c=o?Bb(a):null;c?.level===1&&(Ol(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 th(e,t="brief.md",r=Bl.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=LT(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:p}of Dl(e)){if(p<n.start||p>=n.end)continue;let d=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let f=d[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:p}of Dl(e)){if(p<n.start||p>=n.end)continue;let d=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===a?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),Fb(o.map(l=>Lb("brief-example",t,l.join(`
|
|
225
|
+
`),[],i)),"Brief",i)}function rh(e,t="spec.md",r=Bl.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({...Lb("spec-scenario",t,[s.title,...s.body].join(`
|
|
226
|
+
`),s.context,i),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of Dl(e)){let p=u?Bb(l):null,d=p?/^Scenario\s*:\s*(.*)$/iu.exec(p.text):null;if(d){for(c();o.at(-1)&&o.at(-1).level>=p.level;)o.pop();let f=Vo(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");s={level:p.level,title:f,body:[],context:o.map(h=>h.text)}}else if(p){for(s!==null&&p.level<=s.level?c():s!==null&&s.body.push(l);o.at(-1)&&o.at(-1).level>=p.level;)o.pop();o.push(p)}else s!==null&&u&&s.body.push(l)}return c(),Fb(a,"Specification",i)}var BT,eh,Bl,Wo=T(()=>{"use strict";Wi();pe();BT="comet.native.acceptance.v1",eh=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Bl=Object.freeze({maxCriteria:1024})});import qb from"node:path";function Mb(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||qb.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||qb.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function qT(e,t){return e.localeCompare(t,"en")}function Ll(e){let t=Mb(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((o,s)=>qT(o.capability,s.capability));if(new Set(r.map(o=>o.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=th(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:o,text:s})=>({source:o,text:s})),n=i.length;for(let o of r){let s=Mb(o.source,`Native spec source for ${o.capability}`);for(let c of rh(o.markdown,s,Number.MAX_SAFE_INTEGER,"none",{resolveBriefReferences:e.resolveBriefReferences===!0})){if(c.briefAcceptanceRef!==void 0){let l=Number(c.briefAcceptanceRef.slice(1))-1;if(!Number.isSafeInteger(l)||l<0||l>=n)throw new Error(`Native Spec references unknown brief acceptance ${c.briefAcceptanceRef}: ${s}`);continue}i.push({source:s,text:c.text})}}let a=new Set;for(let o of i){o.text=Vo(o.text);let s=o.text;if(a.has(s))throw new Error(`Native acceptance contains a duplicate criterion: ${o.text}`);a.add(s)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((o,s)=>({id:`A${s+1}`,source:o.source,text:o.text}))}function Vb(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!FT.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Wb(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var FT,Fl=T(()=>{"use strict";Wo();FT=/^A[1-9]\d*$/u});function MT(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function J(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(MT(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var ni=T(()=>{"use strict"});import VT from"node:path";function KT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function YT(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function XT(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 QT(e){return e.schema===Xt?Wn(e):e.schema===Yt?zn(e):Mi(e)}function ZT(e){return VT.posix.normalize(e.replaceAll("\\","/"))}function e$(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:ZT(t.source)})}function t$(e){return e==="shape"?"shape":"build"}function r$(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function i$(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function zb(e){let t=QT(e.state);Vb(e.acceptance);let r=t$(t.phase),i=r==="shape"?0:1,n=YT(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return B({schema:Ii,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:e$(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:r$(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:J(i$(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:sl(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function ih(e){let t=KT(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!WT.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==ql)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!GT.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!zT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!UT.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!JT.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:ql,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:XT(t.createdAt,"Native portable migration transaction createdAt")}}function Gb(e){switch(ih(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var ql,WT,zT,GT,JT,UT,nh=T(()=>{"use strict";jl();Fl();at();ni();On();Bo();ql="comet.native.portable-migration.v1",WT=new Set(["schema","id","change","fromSchema","status","createdAt"]),zT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GT=/^[a-z0-9][a-z0-9-]{7,127}$/u,JT=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),UT=new Set([Xt,Yt,Kt])});import oh from"node:path";function Xb(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qb(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 ah(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 Ub(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function d$(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Xb(e,r);if(Qb(i,u$,r),typeof i.capability!="string"||!Yb.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(d=>d==="."||d==="..")))throw new Error(`${r}.delta_source is invalid`);let o=ah(i.base_hash,`${r}.base_hash`),s=Ub(i.delta_content,`${r}.delta_content`),c=Ub(i.source_content,`${r}.source_content`),l=ah(i.expected_target_hash,`${r}.expected_target_hash`),u=ah(i.result_hash,`${r}.result_hash`),p=a!==void 0;if(p&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(p&&(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(!p&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(p){let d=Do(s);if(d.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(d.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(Sr(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(Sr(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(d=>d==="."||d===".."))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||Sr(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 p$(e){let t=Xb(e,"Native portable Archive transaction");if(Qb(t,l$,"Native portable Archive transaction"),t.schema!==Jb)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!o$.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Yb.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"||!s$.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"||!c$.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(d$);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:Jb,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 Ml(e){let t=n$.exec(e);if(t)return{kind:"archive",change:t[1]};let r=a$.exec(e);return r?{kind:"migration",change:r[1]}:null}function Vl(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Ml(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return oh.join(e.transactionsDir,r)}async function sh(e,t){let r=Ml(t);if(!r)return null;let i=await Z({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=oh.join(e.transactionsDir,t);if(r.kind==="archive"){let s=p$(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=ih(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Wl(e,t){let r=Vl(e,t);try{return await sh(e,oh.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Zb(e){return e.kind==="archive"||e.journal.status!=="committed"}var Jb,Kb,n$,a$,o$,s$,c$,l$,u$,Yb,zl=T(()=>{"use strict";rt();Gf();nh();Jb="comet.native.archive-transaction.v4",Kb="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",n$=new RegExp(`^portable-archive-(${Kb})\\.json$`,"u"),a$=new RegExp(`^portable-migration-(${Kb})\\.json$`,"u"),o$=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,s$=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,c$=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),l$=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),u$=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),Yb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as f$}from"node:crypto";import{constants as Gl,promises as $t}from"node:fs";import jt from"node:path";function Ul(e,t){let r=jt.relative(e,t);return r===""||!jt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${jt.sep}`)}function h$(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function m$(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function v$(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Jl(e,t){return te({...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 ch(e,t){let r=await $t.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await $t.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function g$(e,t,r){let i=jt.resolve(e),n=jt.resolve(t);if(!Ul(i,n))throw new Error(`${r} is outside its managed root`);let a=[await ch(i,r)],o=i;for(let s of jt.relative(i,n).split(jt.sep).filter(Boolean)){await zi(a,r),o=jt.join(o,s);let c=await ch(o,r);if(!Ul(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await zi(a,r),a}async function zi(e,t){for(let r of e){let i=await $t.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!m$(r,i)||await $t.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function w$(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 zo(e){let t=e.maxBytes===null?null:h$(e.maxBytes),r=jt.resolve(e.file),i=await g$(e.root,jt.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>ch(jt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await zi(i,e.label);let a=await $t.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=v$(a),s=await $t.realpath(r);if(!Ul(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Ul(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Gl.O_RDONLY:Gl.O_RDONLY|Gl.O_NOFOLLOW|Gl.O_NONBLOCK,l=await $t.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[p,d]=await Promise.all([$t.lstat(r),$t.realpath(r)]);if(await zi(i,e.label),await zi(n,e.label),!u.isFile()||!p.isFile()||p.isSymbolicLink()||d!==s||!Jl(o,u)||!Jl(o,p))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let f=await w$(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[h,m,v]=await Promise.all([l.stat(),$t.lstat(r),$t.realpath(r)]);if(await zi(i,e.label),await zi(n,e.label),!m.isFile()||m.isSymbolicLink()||v!==s||!Jl(o,h)||!Jl(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:f,hash:f$("sha256").update(f).digest("hex"),size:f.length}}finally{await l.close()}}var Zt=T(()=>{"use strict";ne();Jt()});import Rr from"path";import{TextDecoder as b$}from"util";function Yl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xl(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 iN(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function lh(e,t){if(typeof e!="string"||e.length===0||Rr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Kl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function eN(e,t){if(lh(e,t),e.includes("\\")||e!==Rr.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 R$(e,t){let r=Yl(e,`transaction operations[${t}]`);if(Xl(r,k$,`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`);lh(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&lh(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 nN(e){let t=Yl(e,"Native Archive transaction journal");if(Xl(t,S$,"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"||!rN.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(!iN(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Kl(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=Yl(s,`Archive transaction operations[${c}]`);if(Xl(l,E$,`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`);eN(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&eN(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Kl(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(Kl(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`);Kl(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 C$(e){let t=Yl(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return nN(t);if(Xl(t,N$,"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"||!rN.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Rr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Rr.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(!iN(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(R$),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 P$(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Rr.join(e.transactionsDir,t)}function aN(e,t){let r=P$(e,t);return{directory:r,journal:Rr.join(r,"transaction.json"),events:Rr.join(r,"events.jsonl"),staged:Rr.join(r,"staged"),backups:Rr.join(r,"backups")}}async function dh(e,t){let r=aN(e,t);return await Promise.all(Object.values(r).map(i=>G(e.runtimeDir,i))),r}async function ph(e,t,r={}){let i=await dh(e,t),n=await zo({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(x$.decode(n.bytes)),o=C$(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var N$,k$,S$,E$,rN,x$,Ql=T(()=>{"use strict";ne();ie();Zt();N$=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),k$=new Set(["id","type","source","target","staged","backup"]),S$=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),E$=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),rN=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),x$=new b$("utf-8",{fatal:!0})});import{promises as _$}from"fs";import A$ from"path";async function I$(e,t,r){let i;try{i=await _$.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 ph(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(Ml(n.name))try{let a=await sh(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Zb(a))return!0}catch{return!0}return!1}async function T$(e,t){let r=Date.now()+5e3,i=A$.join(e.locksDir,"root-move.lock");for(;;)try{return await _l(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await cb(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await lb(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 A(e,t,r,i){let n=await T$(e,t);try{if(await nl(e.projectRoot),await I$(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Al(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
|
|
227
|
+
`)}}}var ve=T(()=>{"use strict";gt();Ho();zl();Ql()});import{createHash as $$}from"node:crypto";import{promises as fh}from"node:fs";import oN from"node:os";import Ot from"node:path";function Gn(e){return{id:e.id,name:e.name,status:"planned",repeatable:e.repeatable,executionCount:0,argvDisplay:$o(e.argv),cwdRef:e.cwdRef,exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}}function Zl(e,t){return{...e,name:t.name,status:t.status,argvDisplay:[...t.argvDisplay],cwdRef:t.cwdRef,exitCode:t.exitCode,signal:t.signal,timedOut:t.timedOut,durationMs:t.durationMs,startedAt:t.startedAt,completedAt:t.completedAt,logRef:t.logRef}}function eu(e){if(e.status!=="passed"&&e.status!=="failed"&&e.status!=="interrupted"||e.startedAt===null||e.completedAt===null||e.logRef===null)throw new Error(`Native Supervisor check ${e.id} has incomplete Runtime evidence`);return{id:e.id,name:e.name,argvDisplay:[...e.argvDisplay],cwdRef:e.cwdRef,status:e.status,exitCode:e.exitCode,signal:e.signal,timedOut:e.timedOut,durationMs:e.durationMs,startedAt:e.startedAt,completedAt:e.completedAt,repeatable:e.repeatable,logRef:e.logRef}}function j$(e,t){let r=Ot.relative(Ot.resolve(e),Ot.resolve(t));return r===""||!Ot.isAbsolute(r)&&!r.startsWith(`..${Ot.sep}`)}function er(e,t){try{return I(e,t)}catch(r){return`unavailable:${r instanceof Error?r.message:String(r)}`}}async function sN(e){let t=er(e,["ls-files","--others","--exclude-standard","-z"]);return t===null||t.startsWith("unavailable:")?[{error:t}]:Promise.all(t.split("\0").filter(Boolean).sort().map(async r=>{let i=r.replaceAll("\\","/"),n=Ot.resolve(e,...i.split("/"));if(!j$(e,n))return{path:i,error:"escaped"};try{let a=await fh.lstat(n);if(a.isSymbolicLink())return{path:i,kind:"symlink",target:await fh.readlink(n)};if(!a.isFile())return{path:i,kind:"other",size:a.size};let o=await fh.readFile(n);return{path:i,kind:"file",size:a.size,digest:$$("sha256").update(o).digest("hex")}}catch(a){return{path:i,error:a instanceof Error?a.message:String(a)}}}))}async function O$(e){let t=er(e,["ls-files","--stage","-z"]);if(t===null||t.startsWith("unavailable:"))return[{error:t}];let r=t.split("\0").map(i=>/^160000\s+[^\s]+\s+\d+\t(.+)$/u.exec(i)?.[1]).filter(i=>i!==void 0).sort();return Promise.all(r.map(async i=>({path:i.replaceAll("\\","/"),head:er(Ot.resolve(e,i),["rev-parse","HEAD"]),status:er(Ot.resolve(e,i),["status","--porcelain=v1","-z","--untracked-files=all"]),diff:er(Ot.resolve(e,i),["diff","--binary","HEAD","--submodule=diff"]),untracked:await sN(Ot.resolve(e,i))})))}async function tu(e){let t=Object.entries(process.env).map(([r,i])=>[r,i??null]).sort(([r],[i])=>r.localeCompare(i));return $("comet.native.supervisor-check-input.v2",{kind:e.kind,parent:e.parent,child:e.child,runId:e.runId,projectRoot:Ot.resolve(e.projectRoot),candidateCommit:e.candidateCommit,integrationCommit:e.integrationCommit??null,contractHash:e.contractHash??null,plans:e.plans,materials:e.materials,machineId:oN.hostname(),runtime:{execPath:process.execPath,version:process.version,platform:process.platform,arch:process.arch,environment:t},git:{head:er(e.projectRoot,["rev-parse","HEAD"]),branch:er(e.projectRoot,["branch","--show-current"]),status:er(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none"]),diff:er(e.projectRoot,["diff","--binary","HEAD","--submodule=diff"]),stagedDiff:er(e.projectRoot,["diff","--cached","--binary","--submodule=diff"]),submodules:await O$(e.projectRoot),untracked:await sN(e.projectRoot)}})}function ru(){return oN.hostname()}var hh=T(()=>{"use strict";We();Mn();pe()});import{createHash as H$}from"node:crypto";import{lstatSync as D$,readFileSync as cN,promises as lN}from"node:fs";import iu from"node:path";function pN(e){try{if(I(e,["ls-files","--",nu]))return!1;let t=iu.join(e,nu),r=D$(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(cN(uN(e),"utf8")).hash===dN(cN(t))}catch{return!1}}async function fN(e){let t=iu.join(e,nu),r;try{r=await lN.readFile(t)}catch(n){if(n.code==="ENOENT")return;throw n}let i=uN(e);await lN.mkdir(iu.dirname(i),{recursive:!0}),await he(i,{hash:dN(r)},{containedRoot:e})}function tr(e,t=[]){return Za(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===nu&&pN(e))}var nu,uN,dN,Jn=T(()=>{"use strict";We();ne();nu=".comet/config.yaml",uN=e=>iu.join(e,".comet","runtime","native","workspace-config.json"),dN=e=>H$("sha256").update(e).digest("hex")});import{createHash as q$}from"crypto";function ut(e){return q$("sha256").update(e).digest("hex")}var rr=T(()=>{"use strict"});import gN from"path";function ou(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function oj(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 sj(e,t){return ut(`comet.native.snapshot-policy.v1
|
|
228
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function vh(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 cj(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function wN(e){let t=il(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?cj(n):void 0;if(a&&!a())return!1;let o=vh(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=vh(r,c,a),o===null||o.size===0)return!1}return vh(r,o,a)?.has(r.length)??!1}}function lj(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>il(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>il(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=sj(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(wN),excludeMatchers:r.map(wN),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 Et(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xt(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 ir(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=gN.posix.normalize(e);if(r!==e||gN.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function uj(e,t){let r=Et(e,`Native snapshot entry ${t}`);xt(r,Z$,`Native snapshot entry ${t}`);let i=NN(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!su.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:ir(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!aj.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function dj(e,t){let r=Et(e,`Native snapshot omission ${t}`);if(xt(r,ej,`Native snapshot omission ${t}`),!ij.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!nj.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:ir(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function pj(e){let t=Et(e,"Native snapshot omission overflow");if(xt(t,tj,"Native snapshot omission overflow"),typeof t.hash!="string"||!su.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 Un(e,t){let r=Et(e,t);if(xt(r,Y$,t),typeof r.hash!="string"||!su.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=ir(r.recordCount,`${t} recordCount`),n=ir(r.storedRecordCount,`${t} storedRecordCount`),a=ir(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 yN(e){let t=Et(e,"Native Git selection evidence");if(xt(t,K$,"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=Un(t.stageBefore,"Native Git selection stageBefore"),i=Un(t.combined,"Native Git selection combined"),n=Un(t.stageAfter,"Native Git selection stageAfter"),a=Un(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Un(t.finalCombined,"Native Git selection finalCombined"),s=Un(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(p=>p.overflow),l=!ou(r,n)||!ou(n,a)||!ou(i,o)||!ou(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 bN(e,t){let r=Et(e,t);if(xt(r,Q$,t),typeof r.hash!="string"||!su.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=ir(r.visitedNodeCount,`${t} visitedNodeCount`),n=ir(r.recordCount,`${t} recordCount`),a=ir(r.storedRecordCount,`${t} storedRecordCount`),o=ir(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 fj(e){let t=Et(e,"Native physical selection evidence");if(xt(t,X$,"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=bN(t.before,"Native physical selection before"),i=bN(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!oj(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 gh(e){let t=Et(e,"Native content snapshot manifest");if(xt(t,W$,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!rj.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let b=Et(t.capture,"Native content snapshot capture");if(xt(b,J$,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=b.gitSelection===void 0?void 0:yN(b.gitSelection),k=b.physicalSelection===void 0?void 0:fj(b.physicalSelection),S=null;if(b.projection!==void 0){let C=Et(b.projection,"Native content snapshot projection");if(xt(C,U$,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");S={provider:"git",...C.selection===void 0?{}:{selection:yN(C.selection)}}}if(b.provider==="git"){if(k||S)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&S)throw new Error("Native physical-tree capture cannot combine selection and projection");r=S?{provider:"physical-tree",projection:S}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}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=Et(t.limits,"Native content snapshot limits");xt(i,z$,"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 b=Et(t.policy,"Native snapshot policy");if(xt(b,G$,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=lj({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(uj),s=t.omitted.map(dj),c=ir(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:pj(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,x)=>b+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>V$||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 p=s.filter(b=>b.reason==="git-enumeration-limit"),d=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...p,...d])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(p.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let f=r?.provider==="git"?r.gitSelection:r?.projection?.selection,h=f?.status==="overflow"||f?.status==="overflow-and-changed",m=f?.status==="changed"||f?.status==="overflow-and-changed";if(h!==(p.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(m!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(b=>b.reason==="physical-enumeration-limit"),g=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...v,...g])if(b.path!=="."||b.size!==null||b.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 w=r?.physicalSelection,N=w?.status==="overflow"||w?.status==="overflow-and-changed",y=w?.status==="changed"||w?.status==="overflow-and-changed";if(N!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(y!==(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}:{}}}var yV,V$,W$,z$,G$,J$,U$,K$,Y$,X$,Q$,Z$,ej,tj,rj,ij,nj,su,aj,bV,NV,kV,SV,EV,Jo=T(()=>{"use strict";yn();ne();gt();rr();Jt();ie();Zt();eo();yV={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},V$=1e3,W$=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),z$=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),G$=new Set(["schema","include","exclude","hash"]),J$=new Set(["provider","gitSelection","physicalSelection","projection"]),U$=new Set(["provider","selection"]),K$=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Y$=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),X$=new Set(["schema","status","before","after"]),Q$=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Z$=new Set(["path","hash","size","type","gitObjectId"]),ej=new Set(["path","size","type","reason"]),tj=new Set(["ref","hash","count"]),rj=new Set(["change-created","legacy-migration","explicit"]),ij=new Set(["file","directory","other"]),nj=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"]),su=/^[a-f0-9]{64}$/u,aj=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,bV=64*1024,NV=64*1024,kV={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},SV={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};EV=(1n<<256n)-1n});import{createHash as _N}from"node:crypto";import kN from"path";function Te(e,t){return e<t?-1:e>t?1:0}function yh(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 yj(e,t){return e===t?0:e===null?-1:t===null?1:Te(e,t)}function si(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=kN.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||kN.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function TN(e,t){return e==="."?e:si(e,t)}function Yn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function bj(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:si(e.path,`${t} path`),hash:e.hash,size:Yn(e.size,`${t} size`),type:"file"}}function Nj(e,t){return{path:TN(e.path,`${t} path`),size:e.size===null?null:Yn(e.size,`${t} size`),type:e.type,reason:e.reason}}function kj(e,t){return Te(e.path,t.path)||Te(e.hash,t.hash)||e.size-t.size}function Sj(e,t){return Te(e.path,t.path)||Te(e.reason,t.reason)||Te(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Yo(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
225
229
|
`,"utf8")}function oi(e,t,r){let i=`${t}
|
|
226
|
-
${
|
|
227
|
-
`),e.omissionOverflow&&oi(a,"existing-overflow",e.omissionOverflow);let o=(
|
|
228
|
-
`);let r=0;kN(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){oi(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Yo(o,n.path)&&(a+=1,oi(t,"change-attribution",o));oi(t,"change-end",{attributionCount:a}),a===0&&oi(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&&oi(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function Sj(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=bj(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let x=new Set(r.externalDrift.paths),k=new Set(o.changePaths),S=r.externalDrift.paths.filter(C=>!k.has(C)||n.some(P=>Yo(P,C)));if(S.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${S.slice(0,8).join(", ")}`);if(x.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=$(Jo,e),c=$(Jo,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[x,k]of[["baseline",e],["current",t]])for(let S of k.omitted){if(l.length>=sj)break;l.push(Cr({kind:"snapshot-omission",source:x,path:S.path,evidence:{reason:S.reason,size:S.size,type:S.type}},`${x} snapshot omitted ${S.path}: ${S.reason}`))}let d=e.omitted.length+t.omitted.length,p=[...hN("baseline",e),...hN("current",t),...o.totalChanges===0&&a===null?[Cr({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")]:[]],h=()=>{if(r.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(k=>x.has(k)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(k=>!x.has(k))}},f=x=>{let k=o.candidates.slice(0,x.detailedChangeCount),S=k.filter(tt=>tt.attributedTo.length===0&&!u.has(tt.path)),C=o.totalChanges-k.length,P=o.totalUnattributed-S.length,_=d-x.detailedOmissionCount,j=P+_,ue=[...S.map(tt=>Cr({kind:"unattributed-change",source:"implementation-scope",path:tt.path,evidence:{after:tt.after,before:tt.before,changeKind:tt.kind}},`Changed path is not covered by a declared artifact: ${tt.path}`)),...l.slice(0,x.detailedOmissionCount),...p,...j>0?[xN(x.overflowHash,{changes:C,unattributed:P,unresolved:j})]:[]],de=gj(ue),Or=x.includeGitAdvisory?h():void 0;return{schema:mf,contractHash:i,baselineProjectionRef:vf(s),baselineProjectionHash:s,currentProjectionRef:vf(c),currentProjectionHash:c,complete:de.length===0,declaredArtifacts:n,changes:k,unattributed:S,unresolvedScopes:de,noCodeReason:a,...Or?{gitAdvisory:Or}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},m=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let x=f({detailedChangeCount:m,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:w});if(Ko({...x,scopeHash:w})<=Gi)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let y=o.totalChanges>m||d>v?kj({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:m,detailedOmissionCount:v}):w,E=f({detailedChangeCount:m,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:y}),b={...E,scopeHash:$(bN,E)};if(Ko(b)>Gi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function nr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ar(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 zi(e,t){if(typeof e!="string"||!wf.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function mN(e,t,r){let i=vf(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function au(e,t){let r=nr(e,"Native snapshot projection");if(ar(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==yN)throw new Error("Native snapshot projection schema is invalid");let i=ff({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=fj(i);if($(Jo,r)!==$(Jo,n))throw new Error("Native snapshot projection is not canonical");let a=$(Jo,n);if(t!==void 0&&zi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function yf(e,t){let r=nr(e,`Declared artifact ${t}`);if(ar(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:si(r.path,`Declared artifact ${t} path`),kind:r.kind}}function vN(e,t){if(e===null)return null;let r=nr(e,t);return ar(r,["hash","size"],[],t),{hash:zi(r.hash,`${t} hash`),size:Kn(r.size,`${t} size`)}}function gN(e,t){let r=nr(e,`Implementation change ${t}`);if(ar(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(yf),n=ou(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=vN(r.before,`Implementation change ${t} before`),o=vN(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:si(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function xj(e,t){let r=nr(e,`Unresolved scope ${t}`);ar(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"?NN(r.path,`Unresolved scope ${t} path`):si(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function Uo(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)=>si(n,`${t} ${a}`)),i=[...new Set(r)].sort(Te);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function RN(e){let t=nr(e,"Native implementation external drift");if(ar(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=Uo(t.paths,"Native external drift paths");return EN({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function su(e){let t=nr(e,"Native implementation scope"),r=[...Ej].filter(S=>S!=="gitAdvisory"&&S!=="externalDrift");if(ar(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==mf)throw new Error("Native implementation scope schema is invalid");let i=zi(t.contractHash,"Implementation scope contractHash"),n=zi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=mN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=zi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=mN(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(yf);if(JSON.stringify(c)!==JSON.stringify(ou(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(gN),u=[...l].sort((S,C)=>Te(S.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(S=>S.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(S=>`${S.kind}:${S.path}`));if(l.some(S=>S.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(S=>JSON.stringify(S.attributedTo)!==JSON.stringify(c.filter(C=>Yo(C,S.path)))))throw new Error("Implementation scope change attribution is inconsistent");let p=t.unattributed.map(gN),h=t.externalDrift===void 0?void 0:RN(t.externalDrift),f=new Set(h?.paths??[]),m=l.filter(S=>S.attributedTo.length===0&&!f.has(S.path));if(JSON.stringify(p)!==JSON.stringify(m))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(xj),g=v.filter(S=>S.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let w=g[0]===void 0?null:Nj(g[0]);if(w&&(w.changes+w.unresolved===0||w.unattributed>w.changes||w.unattributed>w.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let N=t.noCodeReason,y=[...m.map(S=>Cr({kind:"unattributed-change",source:"implementation-scope",path:S.path,evidence:{after:S.after,before:S.before,changeKind:S.kind}},`Changed path is not covered by a declared artifact: ${S.path}`)),...l.length+(w?.changes??0)===0&&N===null?[Cr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=v.filter(S=>S.kind==="unattributed-change"||S.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(gf))||new Set(v.map(S=>S.id)).size!==v.length||JSON.stringify(E)!==JSON.stringify(y.sort(gf))||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 b;if(t.gitAdvisory!==void 0){let S=nr(t.gitAdvisory,"Implementation scope Git advisory");if(ar(S,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),S.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Uo(S.changedPaths,"Git changed paths"),P=Uo(S.pathsPresentInSnapshotChanges,"Git present paths"),_=Uo(S.pathsAbsentFromSnapshotChanges,"Git absent paths"),j=[...P,..._].sort(Te);if(JSON.stringify(j)!==JSON.stringify(C)||_.some(ue=>l.some(de=>de.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:P,pathsAbsentFromSnapshotChanges:_}}let x={schema:mf,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:p,unresolvedScopes:v,noCodeReason:N,...b?{gitAdvisory:b}:{},...h?{externalDrift:h}:{}},k=zi(t.scopeHash,"Implementation scope scopeHash");if($(bN,x)!==k)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:k}}function Rj(e){let t=nr(e,"Native implementation scope authority");if(ar(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(yf);if(JSON.stringify(r)!==JSON.stringify(ou(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=Uo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:RN(t.externalDrift),a=yj({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 Xo(e){let t=nr(e,"Native implementation scope bundle");ar(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=Rj(t.authority),i=au(t.baseline),n=au(t.current),a=su(t.scope),o=Sj(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 CN(e){let t=su(e.scope);return Xo({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 mf,yN,Jo,bN,ij,nj,aj,wf,Gi,oj,sj,Ej,Yn=T(()=>{"use strict";pe();Go();mf="comet.native.implementation-scope.v2",yN="comet.native.content-snapshot-projection.v1",Jo="comet.native.content-snapshot-projection.v1",bN="comet.native.implementation-scope.v2",ij="comet.native.unresolved-scope-id.v1",nj="comet.native.scope-detail-overflow.v1",aj="comet.native.snapshot-projection-overflow.v2",wf=/^[a-f0-9]{64}$/u,Gi=1024*1024,oj=128,sj=128;Ej=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import PN from"node:path";function Pr(e,t){if(!AN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function IN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function TN(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 bf(e,t,r=2e3){let i=Ye(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function Qo(e,t){let r=PN.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})||PN.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 Aj(e,t,r){let i=Qo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Nn(i),a=i.toLowerCase(),o=r?Qo(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 Nf(e){let t=Qo(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 Xn(e,t){return e<t?-1:e>t?1:0}function cu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function lu(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 $N(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 _N(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 Ij(e){let t=cu(e,"Native acceptance trace");if(lu(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"||!AN.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=Qo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=cu(o,`Native acceptance trace entry ${s}`);if(lu(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=>Nf(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Xn))||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:Qo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:bf(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Xn(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=Pr(t.traceHash,"Native acceptance trace hash");if($(Cj,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function jN(e){let t=cu(e,"Native partial allowance");if(lu(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(Xn))||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:TN(t.change),scopeHash:Pr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:bf(t.reason,"Partial allowance reason"),confirmedSummary:bf(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:IN(t.sourceRevision),confirmedAt:$N(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=Pr(t.allowanceHash,"Native partial allowance hash");if($(Pj,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function kf(e){let t=cu(e,"Native verification evidence");if(lu(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=Pr(t.implementationScopeHash,"Native verification implementation scope hash"),i=Ij(t.acceptanceTrace),n=Pr(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:Pr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(p=>Nf(p));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Xn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(p=>p.evidenceRefs))].sort(Xn);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=>Nf(p));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Xn)))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:TN(t.change),sourceRevision:IN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Pr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:_N(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:Aj(t.reportRef,"Native verification report ref"),reportHash:Pr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:_N(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:$N(t.createdAt,"Native verification timestamp")},d=Pr(t.envelopeHash,"Native verification envelope hash");if($(_j,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var AN,Cj,Pj,_j,uu=T(()=>{"use strict";pe();ii();Za();Yn();AN=/^[a-f0-9]{64}$/u,Cj="comet.native.acceptance-trace.v2",Pj="comet.native.partial-allowance.v1",_j="comet.native.verification-evidence.v2"});var du,Tj,$j,jj,xV,Oj,RV,Sf=T(()=>{"use strict";pe();du="scoped-text-safety",Tj=1,$j=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),jj="comet.native.checker-policy.v1",xV=$(jj,{policy:du,version:Tj,limits:$j,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),Oj=["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"],RV=new Set(Oj)});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 ci(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 _r(e,t){if(typeof e!="string"||!Dj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ht(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Ye(e).trim();if(!r||r.length>Fj||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Ef(e,t){let r=Ht(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 Zo(e,t,r=Ht,i=!1,n=Mj){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 Wj(e,t){if(typeof e!="string"||!Bj.test(e))throw new Error(`${t} is invalid`);return e}function zj(e){let t=Qn(e,"Native verification receipt bindings");if(ci(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!Lj.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:_r(t.contractHash,"Native verification receipt contract hash"),scopeHash:_r(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:_r(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:_r(t.artifactHash,"Native verification receipt artifact hash")}}function Gj(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=qj.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function Jj(e,t,r,i){let n=Qn(t,`Native ${e} evidence`);if(e==="automated-check"){if(ci(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=Ef(n.startedAt,"Native automated-check start time"),o=Ef(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(ci(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(ci(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:Ht(n.executable,"Native automated-check executable"),args:Zo(n.args,"Native automated-check arguments",Ht,!0),cwd:Ht(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:Ht(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:_r(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:_r(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:_r(n.outputHash,"Native automated-check output hash"),outputSummary:Ht(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){ci(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=Gj(n.checkReceiptRef);if(_r(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Zo(n.subjects,"Native static inspection subjects",Ht,i==="required-check"),rule:Ht(n.rule,"Native static inspection rule"),resultSummary:Ht(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return ci(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Zo(n.steps,"Native manual evidence steps"),observations:Zo(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function Uj(e){let t=Qn(e,"Native verification receipt");if(ci(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=Ht(t.actor,"Native verification receipt actor"),o=Zo(t.acceptanceIds,"Native receipt acceptance IDs",Wj,i==="required-check",Vj).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:xf,kind:r,role:i,status:n,bindings:zj(t.bindings),acceptanceIds:o,actor:a,issuedAt:Ef(t.issuedAt,"Native verification receipt issue time"),evidence:Jj(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==du||s.actor!==`native-runtime:${du}`))throw new Error("Native required check policy identity is invalid");return s}function Rf(e){let t=Qn(e,"Native verification receipt");if(ci(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==xf)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=Uj(i),a=_r(t.receiptHash,"Native verification receipt hash");if($(Hj,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}var xf,Hj,Dj,Bj,Lj,qj,Fj,Mj,Vj,pu=T(()=>{"use strict";pe();Sf();ii();xf="comet.native.verification-receipt.v3",Hj=xf,Dj=/^[a-f0-9]{64}$/u,Bj=/^acceptance-[a-f0-9]{64}$/u,Lj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qj=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Fj=4096,Mj=256,Vj=1024});var zN={};Qu(zN,{MAX_NATIVE_EVIDENCE_DOCUMENT_BYTES:()=>or,MAX_NATIVE_IMPLEMENTATION_SCOPE_BUNDLE_BYTES:()=>Kj,listNativeVerificationReceiptRefs:()=>VN,nativeEvidenceRef:()=>li,nativeReportEvidenceRef:()=>Zj,readArchivedNativeVerificationAcceptanceCounts:()=>o0,readNativeImplementationScope:()=>is,readNativeImplementationScopeBundle:()=>fu,readNativePartialAllowance:()=>If,readNativeVerificationEvidence:()=>Tf,readNativeVerificationReceipt:()=>mu,readNativeVerificationReportSnapshot:()=>rs,removeNativeVerificationReportSnapshot:()=>qN,writeNativeImplementationScope:()=>n0,writeNativePartialAllowance:()=>a0,writeNativeVerificationEvidence:()=>WN,writeNativeVerificationReceipt:()=>MN,writeNativeVerificationReportSnapshot:()=>ts});import{createHash as BN}from"node:crypto";import{promises as Be}from"node:fs";import Dt from"node:path";function Cf(e,t){let r=Dt.relative(e,t);return r===""||!Dt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Dt.sep}`)}function Yj(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function es(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Pt(r,i)?te(r,i):te(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ON(e){let t=await Be.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Be.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Xj(e,t){let r=Dt.resolve(e),i=Dt.resolve(t);if(!Cf(r,i))throw new Error("Native evidence path is outside its change");let n=[await ON(r)],a=r;for(let o of Dt.relative(r,i).split(Dt.sep).filter(Boolean)){a=Dt.join(a,o);let s=await ON(a);if(!Cf(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function HN(e){for(let t of e){let r=await Be.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Yj(t,r)||await Be.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function Qj(e,t,r={}){let i=await Xj(t,Dt.dirname(e));await r.afterParentChainCaptured?.();let n=await Be.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Be.realpath(e);if(!Cf(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Be.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Be.lstat(e),Be.realpath(e)]);if(await HN(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!es(s,n)||!es(s,c))throw new Error("Native evidence document changed while opening");if(s.size>or)throw new Error(`Native evidence document exceeds ${or} bytes`);await r.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(64*1024);for(;;){let v=or+1-d,g=await o.read(p,0,Math.min(p.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>or)throw new Error(`Native evidence document exceeds ${or} bytes`);u.push(Buffer.from(p.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[h,f,m]=await Promise.all([o.stat(),Be.lstat(e),Be.realpath(e)]);if(await HN(i),!f.isFile()||f.isSymbolicLink()||m!==a||!es(s,h)||!es(s,f))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function li(e,t){if(!LN.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function Zj(e){return li("reports",e)}async function ts(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>or||BN("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return Ui({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function qN(e){let t=Pf(e.paths,e.name,"reports",e.hash),r=Ge(e.paths,t);await G(r,t);let i=await Be.lstat(t);if(await rs(e.paths,e.name,e.hash),await G(r,t),!es(i,await Be.lstat(t)))throw new Error("Native report evidence changed before rollback");await Be.unlink(t)}async function rs(e,t,r,i,n){if(!LN.test(r))throw new Error("Native report evidence hash is invalid");let a=await sr({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"||BN("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 Ji(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 Pf(e,t,r,i,n){let a=li(r,i);return n?Dt.join(n,...a.split("/")):lh(vt(e,t),a)}async function sr(e){let t=Pf(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??Ge(e.paths,t);return await G(r,t),Qj(t,r,e.hooks)}async function Ui(e){hu(e.value);let t=Pf(e.paths,e.name,e.kind,e.hash),r=Ge(e.paths,t);await G(r,t);try{let n=await sr(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return li(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await fe(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await sr(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return li(e.kind,e.hash)}function hu(e){if(e0(e)>or)throw new Error(`Native evidence document exceeds ${or} bytes`)}function e0(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
229
|
-
`,"utf8")}function DN(e,t){return au(e,t)}function t0(e,t){let r=su(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function FN(e,t,r){let i=jN(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function _f(e,t,r){let i=kf(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}function r0(e){return{total:e.total,evidenced:e.evidenced,skipped:e.skipped}}function i0(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;let i=e;if(i.schema!=="comet.native.verification-evidence.v1")return null;if(i.change!==t||i.envelopeHash!==r)throw new Error("Legacy Native verification evidence ref/hash/change mismatch");let n=i.acceptanceTrace;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Legacy Native acceptance trace is invalid");let a=n,{total:o,evidenced:s,skipped:c}=a,l=typeof o=="number"?o:Number.NaN,u=typeof s=="number"?s:Number.NaN,d=typeof c=="number"?c:Number.NaN;if(a.schema!=="comet.native.acceptance-trace.v1"||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||!Number.isSafeInteger(d)||l<0||u<0||d<0||u+d>l)throw new Error("Legacy Native acceptance trace is invalid");return{total:l,evidenced:u,skipped:d}}async function Af(e,t,r,i=!1,n){let a=await is(e,t,r.implementationScopeRef,void 0,n);if(i&&await rs(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 If(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 n0(e){let t=Xo(e.bundle),{baseline:r,current:i,scope:n}=t;return hu(r),hu(i),hu(n),await Ui({paths:e.paths,name:e.name,kind:"snapshots",hash:n.baselineProjectionHash,value:r}),await Ui({paths:e.paths,name:e.name,kind:"snapshots",hash:n.currentProjectionHash,value:i}),Ui({paths:e.paths,name:e.name,kind:"scopes",hash:n.scopeHash,value:n})}async function fu(e,t,r,i,n){let a=Ji(r,"scopes"),o=t0(await sr({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=Ji(o.baselineProjectionRef,"snapshots"),c=Ji(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([sr({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>DN(d,s)),sr({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>DN(d,c))]);return CN({baseline:l,current:u,scope:o})}async function is(e,t,r,i,n){return(await fu(e,t,r,i,n)).scope}async function a0(e){let t=FN(e.allowance,e.name,e.allowance.allowanceHash),r=await is(e.paths,e.name,li("scopes",t.scopeHash)),i=r.unresolvedScopes.map(n=>n.id).sort();if(r.complete||JSON.stringify(i)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return Ui({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function If(e,t,r,i,n){let a=Ji(r,"allowances");return FN(await sr({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function MN(e){let t=Rf(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return Ui({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function mu(e,t,r,i,n){let a=Ji(r,"receipts"),o=Rf(await sr({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){let r=Dt.join(vt(e,t),"evidence","receipts");await G(Ge(e,r),r);let i;try{i=await Be.readdir(r,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isFile()).map(n=>/^([a-f0-9]{64})\.json$/u.exec(n.name)?.[1]).filter(n=>n!==void 0).sort().map(n=>li("receipts",n))}async function WN(e){let t=_f(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await Af(e.paths,e.name,t,!0),Ui({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function Tf(e,t,r,i,n){let a=Ji(r,"verifications"),o=_f(await sr({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await Af(e,t,o,!1,n),o}async function o0(e,t,r,i){let n=Ji(r,"verifications"),a=await sr({paths:e,name:t,kind:"verifications",hash:n,changeDir:i}),o=i0(a,t,n);if(o)return o;let s=_f(a,t,n);return await Af(e,t,s,!1,i),r0(s.acceptanceTrace)}var LN,or,Kj,ui=T(()=>{"use strict";ne();ie();Jt();Yn();uu();pu();LN=/^[a-f0-9]{64}$/u,or=Gi,Kj=3*or});var JN={};Qu(JN,{executeNativeSupervisorChecks:()=>Of,readNativeSupervisorCheckEvidence:()=>Zn});import{createHash as s0,randomUUID as c0}from"node:crypto";import{promises as GN}from"node:fs";import jf from"node:path";function as(e){return s0("sha256").update(e).digest("hex")}function $f(e,t){if(I(t.projectRoot,["branch","--show-current"])!==`comet/supervisor/${e}/${t.child}`||I(t.projectRoot,["rev-parse","HEAD"])!==t.baseCommit||!tr(t.projectRoot))throw new Error("Native Supervisor checks require the clean current candidate in its bound worktree")}function ns(e,t,r){let i=e?.children.find(n=>n.name===t)?.task;if(!i||i.role!=="verifier"||i.runId!==r)throw new Error("Native Supervisor check runId is not current");return i}async function l0(e,t){return Promise.all(t.map(async r=>{let i=Xl(r),n=await G(e,jf.resolve(e,...i.logRef.split(/[\\/]/u))),a=await GN.readFile(n,"utf8"),o=Ye(a);return{...i,logContent:o.slice(0,128*1024),logDigest:as(o)}}))}function u0(e,t){return typeof e.logContent=="string"&&typeof e.logDigest=="string"&&e.logDigest.length>0&&t.status===e.status&&t.id===e.id&&t.name===e.name&&JSON.stringify(t.argvDisplay)===JSON.stringify(e.argvDisplay)&&t.cwdRef===e.cwdRef&&t.exitCode===e.exitCode&&t.signal===e.signal&&t.timedOut===e.timedOut&&t.durationMs===e.durationMs&&t.startedAt===e.startedAt&&t.completedAt===e.completedAt&&t.repeatable===e.repeatable&&t.logRef===e.logRef}async function d0(e){try{let t=me(e.paths,e.parent);return(await Promise.all(e.checks.map(async i=>{if(typeof i.logContent!="string"||typeof i.logDigest!="string")return!1;let n=await G(t,jf.resolve(t,...i.logRef.split(/[\\/]/u))),a=Ye(await GN.readFile(n,"utf8"));return as(a)===i.logDigest&&a.slice(0,128*1024)===i.logContent}))).every(Boolean)}catch{return!1}}function p0(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function h0(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}async function Of(e){if(e.plans.length===0||new Set(e.plans.map(({id:l})=>l)).size!==e.plans.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(e.plans.some(({repeatable:l})=>!l))throw new Error("Native Supervisor checks must be repeatable for safe recovery");if(e.materials.some(({name:l,content:u})=>!l.trim()||Buffer.byteLength(u)>1024*1024))throw new Error("Native Supervisor external material name or size is invalid");let t=p0(e.retryCheckIds),r=await A(e.paths,"reserve Supervisor checks",async()=>{let l=await D(e.paths,e.parent),u=ns(l,e.child,e.runId);$f(e.parent,u),lt(u.projectRoot,e.plans);let d=Zl(),p=await Ql({kind:"child",parent:e.parent,child:e.child,runId:e.runId,projectRoot:u.projectRoot,candidateCommit:u.baseCommit,contractHash:u.contractHash??null,plans:e.plans,materials:e.materials}),h=$("comet.native.supervisor-check-plan.v2",{machineId:d,inputFingerprint:p}),f=u.checkExecution;if(f?.status==="running"){let w=await Ln(f.ownerPid,f.ownerIdentity),N=Date.parse(f.expiresAt??"")||Date.parse(f.startedAt)+3e4;if(w){if(!(Date.now()<N))throw new Error("Native Supervisor check lease expired while owner PID is alive; inspect the original execution before retrying");if(f.key!==h)throw new Error("Native Supervisor check plan is already running with different inputs");return{task:structuredClone(u),execute:!1}}let y=f.activeProcess;if(y===void 0||y?.status==="starting")throw new Error(`Native Supervisor check process registration is incomplete. Check logs in ${jf.join(me(e.paths,e.parent),"logs","checks")} for operation ${f.operationId}; stop any remaining check process in ${u.projectRoot}, then submit supervisor-cancel for child ${e.child} and runId ${u.runId}, and dispatch a new Verifier for the preserved candidate.`);if(y&&await Ln(y.pid,y.identity)){if(!(Date.now()<N))throw new Error(`Native Supervisor check ${y.checkId} is still running as PID ${y.pid} after its owner exited and lease expired; stop that original check process, then retry supervisor-checks for ${e.child}.`);return{task:structuredClone(u),execute:!1}}if(f.checkStates?.length&&f.checkStates.every(({status:b})=>b==="passed"||b==="failed")&&f.receiptRef){f.status="completed";try{return await Zn({...e,task:u,receiptRef:f.receiptRef}),l.stateVersion+=1,await F(e.paths,l),{task:structuredClone(u),execute:!1,key:f.key}}catch{f.status="interrupted"}}f.status="interrupted";for(let b of f.checkStates??[])(b.status==="planned"||b.status==="running")&&(b.status="interrupted")}let m=f?.key===h&&f.machineId===d&&f.inputFingerprint===p;if(t){if(!m||f?.status!=="interrupted")throw new Error("Native Supervisor check retry requires the interrupted current plan on the same candidate, machine and workspace");h0(f.checkStates,e.plans,t)}else if(f?.status==="interrupted"&&m)return{task:structuredClone(u),execute:!1,key:h};if(f?.status==="completed"&&m&&f.receiptRef)try{return await Zn({...e,task:u,receiptRef:f.receiptRef}),{task:structuredClone(u),execute:!1,key:h}}catch{}let v=t&&f?.checkStates?f.checkStates.map(w=>t.has(w.id)?{...w,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{...w}):e.plans.map(zn),g=e.plans.map(w=>v.find(N=>N.id===w.id)??zn(w));return u.checkExecution={operationId:c0(),key:h,status:"running",ownerPid:process.pid,ownerIdentity:await ct(process.pid)??void 0,activeProcess:null,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+e.plans.reduce((w,N)=>w+N.timeoutMs,0)+3e4).toISOString(),machineId:d,inputFingerprint:p,checkStates:g},u.checksReason="running",l.stateVersion+=1,await F(e.paths,l),{task:structuredClone(u),execute:!0,key:h,plansToExecute:e.plans.filter(w=>!t||t.has(w.id))}}),{task:i}=r,n=i.checkExecution.operationId;if(!r.execute)return i.checkExecution.status==="completed"&&i.checkExecution.receiptRef&&await Zn({...e,task:i,receiptRef:i.checkExecution.receiptRef}),{status:i.checkExecution.status==="completed"?"completed":i.checkExecution.status==="interrupted"?"interrupted":"running",operationId:n,...i.checkExecution.receiptRef?{receiptRef:i.checkExecution.receiptRef}:{}};let a=me(e.paths,e.parent),o=r.plansToExecute,s=async l=>{await A(e.paths,"register Supervisor check process",async()=>{let u=await D(e.paths,e.parent),d=ns(u,e.child,e.runId);if(d.checkExecution?.operationId!==n||d.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");if(l?.status==="starting"){let p=d.checkExecution.checkStates?.find(({id:h})=>h===l.checkId);if(!p||p.status!=="planned")throw new Error(`Native Supervisor check ${l.checkId} is not planned`);p.status="running",p.executionCount+=1,p.startedAt=new Date().toISOString(),p.completedAt=null,p.logRef=null}d.checkExecution.activeProcess=l,u.stateVersion+=1,await F(e.paths,u)})},c=async l=>A(e.paths,"record Supervisor check result",async()=>{let u=await D(e.paths,e.parent),d=ns(u,e.child,e.runId);if(d.checkExecution?.operationId!==n||d.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");let p=d.checkExecution.checkStates?.find(({id:h})=>h===l.id);if(!p)throw new Error(`Native Supervisor check state is missing: ${l.id}`);Object.assign(p,Yl(p,l)),d.checkExecution.activeProcess=null,u.stateVersion+=1,await F(e.paths,u)});try{for(let v of o){await s({status:"starting",checkId:v.id});let g=await Bi({projectRoot:i.projectRoot,runtimeDir:a,operationId:n,plan:v,onSpawn:async({pid:w})=>{await s({status:"running",checkId:v.id,pid:w,identity:await ct(w)??void 0})}});if(await c(g),g.status==="interrupted")throw new Error(`Native Supervisor check ${g.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let l=await D(e.paths,e.parent),u=ns(l,e.child,e.runId);$f(e.parent,u);let d=u.checkExecution?.checkStates;if(!d||d.some(({status:v})=>!["passed","failed"].includes(v)))throw new Error("Native Supervisor check plan remains incomplete; retry each interrupted check explicitly");let p=await l0(a,d),h={schema:"comet.native.supervisor-checks.v1",parent:e.parent,child:e.child,runId:e.runId,candidateCommit:i.baseCommit,contractHash:i.contractHash??null,operationId:n,planHash:r.key,machineId:u.checkExecution.machineId,inputFingerprint:u.checkExecution.inputFingerprint,checks:p,materials:e.materials.map(({name:v,content:g})=>{let w=Ye(g);return{name:v,content:w,hash:as(w)}})},f=JSON.stringify(h),m=await ts({paths:e.paths,name:e.parent,hash:as(f),text:f});return await A(e.paths,"complete Supervisor checks",async()=>{let v=await D(e.paths,e.parent),g=ns(v,e.child,e.runId);if(g.checkExecution?.operationId!==n)throw new Error("Native Supervisor check operation is stale");$f(e.parent,g),g.checkExecution.status="completed",g.checkExecution.receiptRef=m,g.checkExecution.activeProcess=null,g.checksReason="completed",v.stateVersion+=1,await F(e.paths,v)}),{status:"completed",operationId:n,receiptRef:m}}catch(l){throw await A(e.paths,"interrupt Supervisor checks",async()=>{let u=await D(e.paths,e.parent),d=u?.children.find(({name:p})=>p===e.child)?.task;if(d?.runId===e.runId&&d.checkExecution?.operationId===n){d.checkExecution.status="interrupted",d.checkExecution.activeProcess=null;for(let p of d.checkExecution.checkStates??[])(p.status==="planned"||p.status==="running")&&(p.status="interrupted");d.checksReason="not-run",u.stateVersion+=1,await F(e.paths,u)}}),l}}async function Zn(e){let t=/^runtime\/evidence\/reports\/([a-f0-9]{64})\.json$/u.exec(e.receiptRef);if(!t)throw new Error("Native Supervisor receipt ref is invalid");let r=JSON.parse(await rs(e.paths,e.parent,t[1])),i=e.task,n=i.checkExecution?.checkStates,a=n!==void 0&&Array.isArray(r.checks)&&r.checks.length===n.length&&r.checks.every((s,c)=>u0(s,n[c])),o=Array.isArray(r.checks)&&await d0({paths:e.paths,parent:e.parent,checks:r.checks});if(r.schema!=="comet.native.supervisor-checks.v1"||r.parent!==e.parent||r.child!==i.child||r.runId!==i.runId||r.candidateCommit!==i.baseCommit||r.contractHash!==(i.contractHash??null)||r.operationId!==i.checkExecution?.operationId||r.planHash!==i.checkExecution.key||r.machineId!==i.checkExecution.machineId||r.inputFingerprint!==i.checkExecution.inputFingerprint||i.checkExecution.status!=="completed"||i.checkExecution.receiptRef!==e.receiptRef||!Array.isArray(r.checks)||r.checks.length===0||!a||!o||!Array.isArray(r.materials)||r.materials.some(({content:s,hash:c})=>as(s)!==c))throw new Error("Native Supervisor receipt does not match the current candidate, runId, contract or execution");return r}var Hf=T(()=>{"use strict";Gn();We();_o();pe();Fn();df();ui();ve();ie();ii();kr()});var QN=fr(Gt(),1);import{promises as b0}from"node:fs";import Bt from"node:path";wn();yn();import{execFileSync as R_}from"child_process";import C_ from"fs";import Ri from"path";import{AsyncLocalStorage as Gw}from"node:async_hooks";Ya();var Ci=new Gw,Jw=new Gw;function Uw(e){return Ci.getStore()?e():Ci.run(new Map,e)}function P_(e){let t=Ci.getStore();for(let r of e)t?.set(Jr(r.root),e);return e}function Ur(e,t){return Ua(()=>R_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function Kr(e,t){return Jr(e)===Jr(t)}function Jr(e){let t=Ri.resolve(e);try{let r=C_.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function oe(e){try{let t=Jw.getStore()?.get(Jr(e)),r=Ci.getStore()?.get(t??Jr(e));if(r){let c=zw(t??e,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=Ri.resolve(Ur(e,["rev-parse","--show-toplevel"])),n=Ci.getStore()?.get(Jr(i))??Kw(e),a=zw(i,n);if(Ci.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=Ur(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Kr(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Oc(e){try{let t=Ci.getStore()?.get(Jw.getStore()?.get(Jr(e))??Jr(e));return t?t.map(r=>({...r})):(Ur(e,["rev-parse","--is-inside-work-tree"]),Kw(e))}catch{return[]}}function Kw(e){let t=__(Ur(e,["worktree","list","--porcelain","-z"]));return P_(t),t.map(r=>({...r}))}function __(e){let t=e.split("\0"),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:Ri.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 gr(e){return Oc(e).map(t=>t.root)}function zw(e,t){let r=t.find(a=>Kr(Ri.resolve(a.root),Ri.resolve(e)));if(!r)return null;let i=Ri.resolve(t[0].root),n=Ri.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!Kr(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function Yw(e){try{return Ur(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function bn(e,t){try{return Ur(e,["check-ref-format","--branch",t]),Ur(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function wr(e,t){try{let r=Ur(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}We();rt();pe();gt();ie();at();dl();dl();Hi();kr();import{randomUUID as m0}from"node:crypto";import vu from"node:path";We();_o();ne();pe();Fn();ve();ie();df();Hi();kr();Gn();We();import{promises as zo}from"node:fs";import Qe from"node:path";gt();Gn();Oo();ie();var ai=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function aN(e,t){let r=Qe.relative(e,t);return r===""||!Qe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Qe.sep}`)}function iN(e){return JSON.stringify(e.native)}async function ru(e,t){let r=await Oe(e);if(r&&t){if(iN(r)!==iN(t))throw new Error(`Native worktree configuration differs from the source project: ${Qe.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await rl(e,t),await rN(e),!0):!1}async function C$(e,t){if(!aN(e,t))return!1;let i=`/${Qe.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=I(e,["rev-parse","--git-common-dir"]),a=Qe.resolve(e,n),o=Qe.join(a,"info","exclude"),s="";try{s=await zo.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await zo.mkdir(Qe.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
230
|
+
${qc(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function Ej(e){if(Yo(e)<=Ji)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=_N("sha256");a.update(`${vj}
|
|
231
|
+
`),e.omissionOverflow&&oi(a,"existing-overflow",e.omissionOverflow);let o=(d,f)=>{f||(i+=1),n+=1,oi(a,"omission",d)},s=d=>{i+=1,n+=1,oi(a,"entry",d)},c=()=>{for(let d=r.length-1;d>=0;d-=1){let f=r[d];if(!(f.reason==="git-enumeration-limit"||f.reason==="git-selection-changed"||f.reason==="physical-enumeration-limit"||f.reason==="physical-selection-changed"))return r.splice(d,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(;Yo(u)>Ji;){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 h=0;h<f;h+=1){let m=c();if(m===null)break;o(m,!0)}}else if(t.length>0){let f=Math.max(1,Math.ceil(t.length/4));for(let h of t.splice(-f))s(h)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let p=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${p}`,hash:p,count:n}}}function xj(e){let t=gh(e),r=t.entries.map((n,a)=>bj(n,`Snapshot entry ${a}`));if(r.sort(kj),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)=>Nj(n,`Snapshot omission ${a}`));return i.sort(Sj),Ej({schema:AN,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 lu(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:si(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)=>Te(r.path,i.path)||Te(r.kind,i.kind))}function Xo(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function SN(e){return e?{hash:e.hash,size:e.size}:null}function $N(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:Te(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:SN(c),after:SN(l)})}}function Rj(e,t){return{...e,attributedTo:t.filter(r=>Xo(r,e.path))}}function Cr(e,t){return{id:`scope:${$(hj,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function Cj(e,t){let r=t.omitted.map(i=>Cr({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(Cr({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(Cr({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 EN(e,t){return Cj(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function bh(e,t){return Te(e.kind,t.kind)||Te(e.source,t.source)||yj(e.path,t.path)||Te(e.id,t.id)}function Pj(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(bh)}function jN(e){return[...new Set(e.map((t,r)=>si(t,`Git path ${r}`)))].sort(Te)}function xN(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 _j(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 ON(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=jN(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:xN(e.baseCommit,"Native external drift base commit"),targetBranch:_j(e.targetBranch,"Native external drift target branch"),targetCommit:xN(e.targetCommit,"Native external drift target commit"),paths:t}}function Aj(e){if(typeof e.contractHash!="string"||!Nh.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:lu(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:jN(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:ON(e.externalDrift)}}}function Ij(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,p=0,d=0;return $N(e,t,f=>{let h=r.some(m=>Xo(m,f.path));if(p+=1,c.push(f.path),!h&&!n?.has(f.path)&&(d+=1),o?.has(f.path)&&s.push(f.path),!u&&a.length<gj){let m=Rj(f,r),v=Yo(m);l+v<=Ji?(a.push(m),l+=v):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:p,totalUnattributed:d}}function HN(e,t){return Cr({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 Tj(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:Yn(Number(t[1]),"Scope overflow change count"),unresolved:Yn(Number(t[2]),"Scope overflow unresolved count"),unattributed:Yn(Number(t[3]),"Scope overflow unattributed count")},i=Gi(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(HN(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function $j(e){let t=_N("sha256");t.update(`${mj}
|
|
232
|
+
`);let r=0;$N(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){oi(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Xo(o,n.path)&&(a+=1,oi(t,"change-attribution",o));oi(t,"change-end",{attributionCount:a}),a===0&&oi(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&&oi(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function jj(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=Ij(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let x=new Set(r.externalDrift.paths),k=new Set(o.changePaths),S=r.externalDrift.paths.filter(C=>!k.has(C)||n.some(P=>Xo(P,C)));if(S.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${S.slice(0,8).join(", ")}`);if(x.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=$(Uo,e),c=$(Uo,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[x,k]of[["baseline",e],["current",t]])for(let S of k.omitted){if(l.length>=wj)break;l.push(Cr({kind:"snapshot-omission",source:x,path:S.path,evidence:{reason:S.reason,size:S.size,type:S.type}},`${x} snapshot omitted ${S.path}: ${S.reason}`))}let p=e.omitted.length+t.omitted.length,d=[...EN("baseline",e),...EN("current",t),...o.totalChanges===0&&a===null?[Cr({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 x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(k=>x.has(k)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(k=>!x.has(k))}},h=x=>{let k=o.candidates.slice(0,x.detailedChangeCount),S=k.filter(tt=>tt.attributedTo.length===0&&!u.has(tt.path)),C=o.totalChanges-k.length,P=o.totalUnattributed-S.length,_=p-x.detailedOmissionCount,j=P+_,ue=[...S.map(tt=>Cr({kind:"unattributed-change",source:"implementation-scope",path:tt.path,evidence:{after:tt.after,before:tt.before,changeKind:tt.kind}},`Changed path is not covered by a declared artifact: ${tt.path}`)),...l.slice(0,x.detailedOmissionCount),...d,...j>0?[HN(x.overflowHash,{changes:C,unattributed:P,unresolved:j})]:[]],de=Pj(ue),Or=x.includeGitAdvisory?f():void 0;return{schema:wh,contractHash:i,baselineProjectionRef:yh(s),baselineProjectionHash:s,currentProjectionRef:yh(c),currentProjectionHash:c,complete:de.length===0,declaredArtifacts:n,changes:k,unattributed:S,unresolvedScopes:de,noCodeReason:a,...Or?{gitAdvisory:Or}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},m=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let x=h({detailedChangeCount:m,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:w});if(Yo({...x,scopeHash:w})<=Ji)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let y=o.totalChanges>m||p>v?$j({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:m,detailedOmissionCount:v}):w,E=h({detailedChangeCount:m,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:y}),b={...E,scopeHash:$(IN,E)};if(Yo(b)>Ji)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function nr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ar(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 Gi(e,t){if(typeof e!="string"||!Nh.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function RN(e,t,r){let i=yh(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function cu(e,t){let r=nr(e,"Native snapshot projection");if(ar(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==AN)throw new Error("Native snapshot projection schema is invalid");let i=gh({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=xj(i);if($(Uo,r)!==$(Uo,n))throw new Error("Native snapshot projection is not canonical");let a=$(Uo,n);if(t!==void 0&&Gi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function kh(e,t){let r=nr(e,`Declared artifact ${t}`);if(ar(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:si(r.path,`Declared artifact ${t} path`),kind:r.kind}}function CN(e,t){if(e===null)return null;let r=nr(e,t);return ar(r,["hash","size"],[],t),{hash:Gi(r.hash,`${t} hash`),size:Yn(r.size,`${t} size`)}}function PN(e,t){let r=nr(e,`Implementation change ${t}`);if(ar(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(kh),n=lu(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=CN(r.before,`Implementation change ${t} before`),o=CN(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:si(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function Hj(e,t){let r=nr(e,`Unresolved scope ${t}`);ar(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"?TN(r.path,`Unresolved scope ${t} path`):si(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function Ko(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)=>si(n,`${t} ${a}`)),i=[...new Set(r)].sort(Te);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function DN(e){let t=nr(e,"Native implementation external drift");if(ar(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=Ko(t.paths,"Native external drift paths");return ON({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function uu(e){let t=nr(e,"Native implementation scope"),r=[...Oj].filter(S=>S!=="gitAdvisory"&&S!=="externalDrift");if(ar(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==wh)throw new Error("Native implementation scope schema is invalid");let i=Gi(t.contractHash,"Implementation scope contractHash"),n=Gi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=RN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Gi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=RN(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(kh);if(JSON.stringify(c)!==JSON.stringify(lu(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(PN),u=[...l].sort((S,C)=>Te(S.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(S=>S.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let p=new Set(c.map(S=>`${S.kind}:${S.path}`));if(l.some(S=>S.attributedTo.some(C=>!p.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(S=>JSON.stringify(S.attributedTo)!==JSON.stringify(c.filter(C=>Xo(C,S.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=t.unattributed.map(PN),f=t.externalDrift===void 0?void 0:DN(t.externalDrift),h=new Set(f?.paths??[]),m=l.filter(S=>S.attributedTo.length===0&&!h.has(S.path));if(JSON.stringify(d)!==JSON.stringify(m))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(Hj),g=v.filter(S=>S.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let w=g[0]===void 0?null:Tj(g[0]);if(w&&(w.changes+w.unresolved===0||w.unattributed>w.changes||w.unattributed>w.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let N=t.noCodeReason,y=[...m.map(S=>Cr({kind:"unattributed-change",source:"implementation-scope",path:S.path,evidence:{after:S.after,before:S.before,changeKind:S.kind}},`Changed path is not covered by a declared artifact: ${S.path}`)),...l.length+(w?.changes??0)===0&&N===null?[Cr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=v.filter(S=>S.kind==="unattributed-change"||S.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(bh))||new Set(v.map(S=>S.id)).size!==v.length||JSON.stringify(E)!==JSON.stringify(y.sort(bh))||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 b;if(t.gitAdvisory!==void 0){let S=nr(t.gitAdvisory,"Implementation scope Git advisory");if(ar(S,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),S.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Ko(S.changedPaths,"Git changed paths"),P=Ko(S.pathsPresentInSnapshotChanges,"Git present paths"),_=Ko(S.pathsAbsentFromSnapshotChanges,"Git absent paths"),j=[...P,..._].sort(Te);if(JSON.stringify(j)!==JSON.stringify(C)||_.some(ue=>l.some(de=>de.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:P,pathsAbsentFromSnapshotChanges:_}}let x={schema:wh,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:v,noCodeReason:N,...b?{gitAdvisory:b}:{},...f?{externalDrift:f}:{}},k=Gi(t.scopeHash,"Implementation scope scopeHash");if($(IN,x)!==k)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:k}}function Dj(e){let t=nr(e,"Native implementation scope authority");if(ar(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(kh);if(JSON.stringify(r)!==JSON.stringify(lu(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=Ko(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:DN(t.externalDrift),a=Aj({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 Qo(e){let t=nr(e,"Native implementation scope bundle");ar(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=Dj(t.authority),i=cu(t.baseline),n=cu(t.current),a=uu(t.scope),o=jj(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 BN(e){let t=uu(e.scope);return Qo({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 wh,AN,Uo,IN,hj,mj,vj,Nh,Ji,gj,wj,Oj,Xn=T(()=>{"use strict";pe();Jo();wh="comet.native.implementation-scope.v2",AN="comet.native.content-snapshot-projection.v1",Uo="comet.native.content-snapshot-projection.v1",IN="comet.native.implementation-scope.v2",hj="comet.native.unresolved-scope-id.v1",mj="comet.native.scope-detail-overflow.v1",vj="comet.native.snapshot-projection-overflow.v2",Nh=/^[a-f0-9]{64}$/u,Ji=1024*1024,gj=128,wj=128;Oj=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import LN from"node:path";function Pr(e,t){if(!qN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function MN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function VN(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 Sh(e,t,r=2e3){let i=Ye(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function Zo(e,t){let r=LN.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})||LN.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 qj(e,t,r){let i=Zo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=kn(i),a=i.toLowerCase(),o=r?Zo(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 Eh(e){let t=Zo(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 Qn(e,t){return e<t?-1:e>t?1:0}function du(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pu(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 WN(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 FN(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 Mj(e){let t=du(e,"Native acceptance trace");if(pu(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"||!qN.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=Zo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=du(o,`Native acceptance trace entry ${s}`);if(pu(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(p=>typeof p!="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(p=>Eh(p)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Qn))||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:Zo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Sh(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Qn(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=Pr(t.traceHash,"Native acceptance trace hash");if($(Bj,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function zN(e){let t=du(e,"Native partial allowance");if(pu(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(Qn))||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:VN(t.change),scopeHash:Pr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Sh(t.reason,"Partial allowance reason"),confirmedSummary:Sh(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:MN(t.sourceRevision),confirmedAt:WN(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=Pr(t.allowanceHash,"Native partial allowance hash");if($(Lj,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function xh(e){let t=du(e,"Native verification evidence");if(pu(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=Pr(t.implementationScopeHash,"Native verification implementation scope hash"),i=Mj(t.acceptanceTrace),n=Pr(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:Pr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(d=>Eh(d));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Qn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(d=>d.evidenceRefs))].sort(Qn);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(d=>Eh(d));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Qn)))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:VN(t.change),sourceRevision:MN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Pr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:FN(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:qj(t.reportRef,"Native verification report ref"),reportHash:Pr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:FN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:WN(t.createdAt,"Native verification timestamp")},p=Pr(t.envelopeHash,"Native verification envelope hash");if($(Fj,u)!==p)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:p}}var qN,Bj,Lj,Fj,fu=T(()=>{"use strict";pe();ii();eo();Xn();qN=/^[a-f0-9]{64}$/u,Bj="comet.native.acceptance-trace.v2",Lj="comet.native.partial-allowance.v1",Fj="comet.native.verification-evidence.v2"});var hu,Vj,Wj,zj,BV,Gj,LV,Rh=T(()=>{"use strict";pe();hu="scoped-text-safety",Vj=1,Wj=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),zj="comet.native.checker-policy.v1",BV=$(zj,{policy:hu,version:Vj,limits:Wj,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),Gj=["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"],LV=new Set(Gj)});function Zn(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 ci(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 _r(e,t){if(typeof e!="string"||!Uj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ht(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Ye(e).trim();if(!r||r.length>Qj||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Ch(e,t){let r=Ht(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 es(e,t,r=Ht,i=!1,n=Zj){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 t0(e,t){if(typeof e!="string"||!Kj.test(e))throw new Error(`${t} is invalid`);return e}function r0(e){let t=Zn(e,"Native verification receipt bindings");if(ci(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!Yj.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:_r(t.contractHash,"Native verification receipt contract hash"),scopeHash:_r(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:_r(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:_r(t.artifactHash,"Native verification receipt artifact hash")}}function i0(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=Xj.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function n0(e,t,r,i){let n=Zn(t,`Native ${e} evidence`);if(e==="automated-check"){if(ci(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=Ch(n.startedAt,"Native automated-check start time"),o=Ch(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=Zn(n.worktree,"Native automated-check worktree");if(ci(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=Zn(n.afterFence,"Native automated-check after fence");if(ci(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:Ht(n.executable,"Native automated-check executable"),args:es(n.args,"Native automated-check arguments",Ht,!0),cwd:Ht(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:Ht(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:_r(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:_r(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:_r(n.outputHash,"Native automated-check output hash"),outputSummary:Ht(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){ci(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=i0(n.checkReceiptRef);if(_r(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:es(n.subjects,"Native static inspection subjects",Ht,i==="required-check"),rule:Ht(n.rule,"Native static inspection rule"),resultSummary:Ht(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return ci(n,["steps","observations"],"Native manual-evidence evidence"),{steps:es(n.steps,"Native manual evidence steps"),observations:es(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function a0(e){let t=Zn(e,"Native verification receipt");if(ci(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=Ht(t.actor,"Native verification receipt actor"),o=es(t.acceptanceIds,"Native receipt acceptance IDs",t0,i==="required-check",e0).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:Ph,kind:r,role:i,status:n,bindings:r0(t.bindings),acceptanceIds:o,actor:a,issuedAt:Ch(t.issuedAt,"Native verification receipt issue time"),evidence:n0(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==hu||s.actor!==`native-runtime:${hu}`))throw new Error("Native required check policy identity is invalid");return s}function _h(e){let t=Zn(e,"Native verification receipt");if(ci(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Ph)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=a0(i),a=_r(t.receiptHash,"Native verification receipt hash");if($(Jj,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}var Ph,Jj,Uj,Kj,Yj,Xj,Qj,Zj,e0,mu=T(()=>{"use strict";pe();Rh();ii();Ph="comet.native.verification-receipt.v3",Jj=Ph,Uj=/^[a-f0-9]{64}$/u,Kj=/^acceptance-[a-f0-9]{64}$/u,Yj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Xj=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Qj=4096,Zj=256,e0=1024});var rk={};ed(rk,{MAX_NATIVE_EVIDENCE_DOCUMENT_BYTES:()=>or,MAX_NATIVE_IMPLEMENTATION_SCOPE_BUNDLE_BYTES:()=>o0,listNativeVerificationReceiptRefs:()=>ek,nativeEvidenceRef:()=>li,nativeReportEvidenceRef:()=>u0,readArchivedNativeVerificationAcceptanceCounts:()=>g0,readNativeImplementationScope:()=>ns,readNativeImplementationScopeBundle:()=>gu,readNativePartialAllowance:()=>jh,readNativeVerificationEvidence:()=>Oh,readNativeVerificationReceipt:()=>wu,readNativeVerificationReportSnapshot:()=>is,removeNativeVerificationReportSnapshot:()=>XN,writeNativeImplementationScope:()=>m0,writeNativePartialAllowance:()=>v0,writeNativeVerificationEvidence:()=>tk,writeNativeVerificationReceipt:()=>ZN,writeNativeVerificationReportSnapshot:()=>rs});import{createHash as KN}from"node:crypto";import{promises as Be}from"node:fs";import Dt from"node:path";function Ah(e,t){let r=Dt.relative(e,t);return r===""||!Dt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Dt.sep}`)}function s0(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ts(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Pt(r,i)?te(r,i):te(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function GN(e){let t=await Be.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Be.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function c0(e,t){let r=Dt.resolve(e),i=Dt.resolve(t);if(!Ah(r,i))throw new Error("Native evidence path is outside its change");let n=[await GN(r)],a=r;for(let o of Dt.relative(r,i).split(Dt.sep).filter(Boolean)){a=Dt.join(a,o);let s=await GN(a);if(!Ah(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function JN(e){for(let t of e){let r=await Be.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!s0(t,r)||await Be.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function l0(e,t,r={}){let i=await c0(t,Dt.dirname(e));await r.afterParentChainCaptured?.();let n=await Be.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Be.realpath(e);if(!Ah(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Be.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Be.lstat(e),Be.realpath(e)]);if(await JN(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!ts(s,n)||!ts(s,c))throw new Error("Native evidence document changed while opening");if(s.size>or)throw new Error(`Native evidence document exceeds ${or} bytes`);await r.afterOpen?.();let u=[],p=0,d=Buffer.allocUnsafe(64*1024);for(;;){let v=or+1-p,g=await o.read(d,0,Math.min(d.length,v),null);if(g.bytesRead===0)break;if(p+=g.bytesRead,p>or)throw new Error(`Native evidence document exceeds ${or} bytes`);u.push(Buffer.from(d.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[f,h,m]=await Promise.all([o.stat(),Be.lstat(e),Be.realpath(e)]);if(await JN(i),!h.isFile()||h.isSymbolicLink()||m!==a||!ts(s,f)||!ts(s,h))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,p).toString("utf8"))}finally{await o.close()}}function li(e,t){if(!YN.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function u0(e){return li("reports",e)}async function rs(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>or||KN("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return Ki({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function XN(e){let t=Ih(e.paths,e.name,"reports",e.hash),r=Ge(e.paths,t);await G(r,t);let i=await Be.lstat(t);if(await is(e.paths,e.name,e.hash),await G(r,t),!ts(i,await Be.lstat(t)))throw new Error("Native report evidence changed before rollback");await Be.unlink(t)}async function is(e,t,r,i,n){if(!YN.test(r))throw new Error("Native report evidence hash is invalid");let a=await sr({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"||KN("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 Ui(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 Ih(e,t,r,i,n){let a=li(r,i);return n?Dt.join(n,...a.split("/")):pf(vt(e,t),a)}async function sr(e){let t=Ih(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??Ge(e.paths,t);return await G(r,t),l0(t,r,e.hooks)}async function Ki(e){vu(e.value);let t=Ih(e.paths,e.name,e.kind,e.hash),r=Ge(e.paths,t);await G(r,t);try{let n=await sr(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return li(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await he(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await sr(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return li(e.kind,e.hash)}function vu(e){if(d0(e)>or)throw new Error(`Native evidence document exceeds ${or} bytes`)}function d0(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
233
|
+
`,"utf8")}function UN(e,t){return cu(e,t)}function p0(e,t){let r=uu(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function QN(e,t,r){let i=zN(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function Th(e,t,r){let i=xh(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}function f0(e){return{total:e.total,evidenced:e.evidenced,skipped:e.skipped}}function h0(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;let i=e;if(i.schema!=="comet.native.verification-evidence.v1")return null;if(i.change!==t||i.envelopeHash!==r)throw new Error("Legacy Native verification evidence ref/hash/change mismatch");let n=i.acceptanceTrace;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Legacy Native acceptance trace is invalid");let a=n,{total:o,evidenced:s,skipped:c}=a,l=typeof o=="number"?o:Number.NaN,u=typeof s=="number"?s:Number.NaN,p=typeof c=="number"?c:Number.NaN;if(a.schema!=="comet.native.acceptance-trace.v1"||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||!Number.isSafeInteger(p)||l<0||u<0||p<0||u+p>l)throw new Error("Legacy Native acceptance trace is invalid");return{total:l,evidenced:u,skipped:p}}async function $h(e,t,r,i=!1,n){let a=await ns(e,t,r.implementationScopeRef,void 0,n);if(i&&await is(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 jh(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 m0(e){let t=Qo(e.bundle),{baseline:r,current:i,scope:n}=t;return vu(r),vu(i),vu(n),await Ki({paths:e.paths,name:e.name,kind:"snapshots",hash:n.baselineProjectionHash,value:r}),await Ki({paths:e.paths,name:e.name,kind:"snapshots",hash:n.currentProjectionHash,value:i}),Ki({paths:e.paths,name:e.name,kind:"scopes",hash:n.scopeHash,value:n})}async function gu(e,t,r,i,n){let a=Ui(r,"scopes"),o=p0(await sr({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=Ui(o.baselineProjectionRef,"snapshots"),c=Ui(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([sr({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(p=>UN(p,s)),sr({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(p=>UN(p,c))]);return BN({baseline:l,current:u,scope:o})}async function ns(e,t,r,i,n){return(await gu(e,t,r,i,n)).scope}async function v0(e){let t=QN(e.allowance,e.name,e.allowance.allowanceHash),r=await ns(e.paths,e.name,li("scopes",t.scopeHash)),i=r.unresolvedScopes.map(n=>n.id).sort();if(r.complete||JSON.stringify(i)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return Ki({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function jh(e,t,r,i,n){let a=Ui(r,"allowances");return QN(await sr({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function ZN(e){let t=_h(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return Ki({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function wu(e,t,r,i,n){let a=Ui(r,"receipts"),o=_h(await sr({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 ek(e,t){let r=Dt.join(vt(e,t),"evidence","receipts");await G(Ge(e,r),r);let i;try{i=await Be.readdir(r,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isFile()).map(n=>/^([a-f0-9]{64})\.json$/u.exec(n.name)?.[1]).filter(n=>n!==void 0).sort().map(n=>li("receipts",n))}async function tk(e){let t=Th(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await $h(e.paths,e.name,t,!0),Ki({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function Oh(e,t,r,i,n){let a=Ui(r,"verifications"),o=Th(await sr({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await $h(e,t,o,!1,n),o}async function g0(e,t,r,i){let n=Ui(r,"verifications"),a=await sr({paths:e,name:t,kind:"verifications",hash:n,changeDir:i}),o=h0(a,t,n);if(o)return o;let s=Th(a,t,n);return await $h(e,t,s,!1,i),f0(s.acceptanceTrace)}var YN,or,o0,ui=T(()=>{"use strict";ne();ie();Jt();Xn();fu();mu();YN=/^[a-f0-9]{64}$/u,or=Ji,o0=3*or});var nk={};ed(nk,{executeNativeSupervisorChecks:()=>Bh,readNativeSupervisorCheckEvidence:()=>ea});import{createHash as w0,randomUUID as y0}from"node:crypto";import{promises as ik}from"node:fs";import Dh from"node:path";function os(e){return w0("sha256").update(e).digest("hex")}function Hh(e,t){if(I(t.projectRoot,["branch","--show-current"])!==`comet/supervisor/${e}/${t.child}`||I(t.projectRoot,["rev-parse","HEAD"])!==t.baseCommit||!tr(t.projectRoot))throw new Error("Native Supervisor checks require the clean current candidate in its bound worktree")}function as(e,t,r){let i=e?.children.find(n=>n.name===t)?.task;if(!i||i.role!=="verifier"||i.runId!==r)throw new Error("Native Supervisor check runId is not current");return i}async function b0(e,t){return Promise.all(t.map(async r=>{let i=eu(r),n=await G(e,Dh.resolve(e,...i.logRef.split(/[\\/]/u))),a=await ik.readFile(n,"utf8"),o=Ye(a);return{...i,logContent:o.slice(0,128*1024),logDigest:os(o)}}))}function N0(e,t){return typeof e.logContent=="string"&&typeof e.logDigest=="string"&&e.logDigest.length>0&&t.status===e.status&&t.id===e.id&&t.name===e.name&&JSON.stringify(t.argvDisplay)===JSON.stringify(e.argvDisplay)&&t.cwdRef===e.cwdRef&&t.exitCode===e.exitCode&&t.signal===e.signal&&t.timedOut===e.timedOut&&t.durationMs===e.durationMs&&t.startedAt===e.startedAt&&t.completedAt===e.completedAt&&t.repeatable===e.repeatable&&t.logRef===e.logRef}async function k0(e){try{let t=me(e.paths,e.parent);return(await Promise.all(e.checks.map(async i=>{if(typeof i.logContent!="string"||typeof i.logDigest!="string")return!1;let n=await G(t,Dh.resolve(t,...i.logRef.split(/[\\/]/u))),a=Ye(await ik.readFile(n,"utf8"));return os(a)===i.logDigest&&a.slice(0,128*1024)===i.logContent}))).every(Boolean)}catch{return!1}}function S0(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function E0(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}async function Bh(e){if(e.plans.length===0||new Set(e.plans.map(({id:l})=>l)).size!==e.plans.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(e.plans.some(({repeatable:l})=>!l))throw new Error("Native Supervisor checks must be repeatable for safe recovery");if(e.materials.some(({name:l,content:u})=>!l.trim()||Buffer.byteLength(u)>1024*1024))throw new Error("Native Supervisor external material name or size is invalid");let t=S0(e.retryCheckIds),r=await A(e.paths,"reserve Supervisor checks",async()=>{let l=await D(e.paths,e.parent),u=as(l,e.child,e.runId);Hh(e.parent,u),lt(u.projectRoot,e.plans);let p=ru(),d=await tu({kind:"child",parent:e.parent,child:e.child,runId:e.runId,projectRoot:u.projectRoot,candidateCommit:u.baseCommit,contractHash:u.contractHash??null,plans:e.plans,materials:e.materials}),f=$("comet.native.supervisor-check-plan.v2",{machineId:p,inputFingerprint:d}),h=u.checkExecution;if(h?.status==="running"){let w=await Fn(h.ownerPid,h.ownerIdentity),N=Date.parse(h.expiresAt??"")||Date.parse(h.startedAt)+3e4;if(w){if(!(Date.now()<N))throw new Error("Native Supervisor check lease expired while owner PID is alive; inspect the original execution before retrying");if(h.key!==f)throw new Error("Native Supervisor check plan is already running with different inputs");return{task:structuredClone(u),execute:!1}}let y=h.activeProcess;if(y===void 0||y?.status==="starting")throw new Error(`Native Supervisor check process registration is incomplete. Check logs in ${Dh.join(me(e.paths,e.parent),"logs","checks")} for operation ${h.operationId}; stop any remaining check process in ${u.projectRoot}, then submit supervisor-cancel for child ${e.child} and runId ${u.runId}, and dispatch a new Verifier for the preserved candidate.`);if(y&&await Fn(y.pid,y.identity)){if(!(Date.now()<N))throw new Error(`Native Supervisor check ${y.checkId} is still running as PID ${y.pid} after its owner exited and lease expired; stop that original check process, then retry supervisor-checks for ${e.child}.`);return{task:structuredClone(u),execute:!1}}if(h.checkStates?.length&&h.checkStates.every(({status:b})=>b==="passed"||b==="failed")&&h.receiptRef){h.status="completed";try{return await ea({...e,task:u,receiptRef:h.receiptRef}),l.stateVersion+=1,await q(e.paths,l),{task:structuredClone(u),execute:!1,key:h.key}}catch{h.status="interrupted"}}h.status="interrupted";for(let b of h.checkStates??[])(b.status==="planned"||b.status==="running")&&(b.status="interrupted")}let m=h?.key===f&&h.machineId===p&&h.inputFingerprint===d;if(t){if(!m||h?.status!=="interrupted")throw new Error("Native Supervisor check retry requires the interrupted current plan on the same candidate, machine and workspace");E0(h.checkStates,e.plans,t)}else if(h?.status==="interrupted"&&m)return{task:structuredClone(u),execute:!1,key:f};if(h?.status==="completed"&&m&&h.receiptRef)try{return await ea({...e,task:u,receiptRef:h.receiptRef}),{task:structuredClone(u),execute:!1,key:f}}catch{}let v=t&&h?.checkStates?h.checkStates.map(w=>t.has(w.id)?{...w,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{...w}):e.plans.map(Gn),g=e.plans.map(w=>v.find(N=>N.id===w.id)??Gn(w));return u.checkExecution={operationId:y0(),key:f,status:"running",ownerPid:process.pid,ownerIdentity:await ct(process.pid)??void 0,activeProcess:null,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+e.plans.reduce((w,N)=>w+N.timeoutMs,0)+3e4).toISOString(),machineId:p,inputFingerprint:d,checkStates:g},u.checksReason="running",l.stateVersion+=1,await q(e.paths,l),{task:structuredClone(u),execute:!0,key:f,plansToExecute:e.plans.filter(w=>!t||t.has(w.id))}}),{task:i}=r,n=i.checkExecution.operationId;if(!r.execute)return i.checkExecution.status==="completed"&&i.checkExecution.receiptRef&&await ea({...e,task:i,receiptRef:i.checkExecution.receiptRef}),{status:i.checkExecution.status==="completed"?"completed":i.checkExecution.status==="interrupted"?"interrupted":"running",operationId:n,...i.checkExecution.receiptRef?{receiptRef:i.checkExecution.receiptRef}:{}};let a=me(e.paths,e.parent),o=r.plansToExecute,s=async l=>{await A(e.paths,"register Supervisor check process",async()=>{let u=await D(e.paths,e.parent),p=as(u,e.child,e.runId);if(p.checkExecution?.operationId!==n||p.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");if(l?.status==="starting"){let d=p.checkExecution.checkStates?.find(({id:f})=>f===l.checkId);if(!d||d.status!=="planned")throw new Error(`Native Supervisor check ${l.checkId} is not planned`);d.status="running",d.executionCount+=1,d.startedAt=new Date().toISOString(),d.completedAt=null,d.logRef=null}p.checkExecution.activeProcess=l,u.stateVersion+=1,await q(e.paths,u)})},c=async l=>A(e.paths,"record Supervisor check result",async()=>{let u=await D(e.paths,e.parent),p=as(u,e.child,e.runId);if(p.checkExecution?.operationId!==n||p.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");let d=p.checkExecution.checkStates?.find(({id:f})=>f===l.id);if(!d)throw new Error(`Native Supervisor check state is missing: ${l.id}`);Object.assign(d,Zl(d,l)),p.checkExecution.activeProcess=null,u.stateVersion+=1,await q(e.paths,u)});try{for(let v of o){await s({status:"starting",checkId:v.id});let g=await Bi({projectRoot:i.projectRoot,runtimeDir:a,operationId:n,plan:v,onSpawn:async({pid:w})=>{await s({status:"running",checkId:v.id,pid:w,identity:await ct(w)??void 0})}});if(await c(g),g.status==="interrupted")throw new Error(`Native Supervisor check ${g.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let l=await D(e.paths,e.parent),u=as(l,e.child,e.runId);Hh(e.parent,u);let p=u.checkExecution?.checkStates;if(!p||p.some(({status:v})=>!["passed","failed"].includes(v)))throw new Error("Native Supervisor check plan remains incomplete; retry each interrupted check explicitly");let d=await b0(a,p),f={schema:"comet.native.supervisor-checks.v1",parent:e.parent,child:e.child,runId:e.runId,candidateCommit:i.baseCommit,contractHash:i.contractHash??null,operationId:n,planHash:r.key,machineId:u.checkExecution.machineId,inputFingerprint:u.checkExecution.inputFingerprint,checks:d,materials:e.materials.map(({name:v,content:g})=>{let w=Ye(g);return{name:v,content:w,hash:os(w)}})},h=JSON.stringify(f),m=await rs({paths:e.paths,name:e.parent,hash:os(h),text:h});return await A(e.paths,"complete Supervisor checks",async()=>{let v=await D(e.paths,e.parent),g=as(v,e.child,e.runId);if(g.checkExecution?.operationId!==n)throw new Error("Native Supervisor check operation is stale");Hh(e.parent,g),g.checkExecution.status="completed",g.checkExecution.receiptRef=m,g.checkExecution.activeProcess=null,g.checksReason="completed",v.stateVersion+=1,await q(e.paths,v)}),{status:"completed",operationId:n,receiptRef:m}}catch(l){throw await A(e.paths,"interrupt Supervisor checks",async()=>{let u=await D(e.paths,e.parent),p=u?.children.find(({name:d})=>d===e.child)?.task;if(p?.runId===e.runId&&p.checkExecution?.operationId===n){p.checkExecution.status="interrupted",p.checkExecution.activeProcess=null;for(let d of p.checkExecution.checkStates??[])(d.status==="planned"||d.status==="running")&&(d.status="interrupted");p.checksReason="not-run",u.stateVersion+=1,await q(e.paths,u)}}),l}}async function ea(e){let t=/^runtime\/evidence\/reports\/([a-f0-9]{64})\.json$/u.exec(e.receiptRef);if(!t)throw new Error("Native Supervisor receipt ref is invalid");let r=JSON.parse(await is(e.paths,e.parent,t[1])),i=e.task,n=i.checkExecution?.checkStates,a=n!==void 0&&Array.isArray(r.checks)&&r.checks.length===n.length&&r.checks.every((s,c)=>N0(s,n[c])),o=Array.isArray(r.checks)&&await k0({paths:e.paths,parent:e.parent,checks:r.checks});if(r.schema!=="comet.native.supervisor-checks.v1"||r.parent!==e.parent||r.child!==i.child||r.runId!==i.runId||r.candidateCommit!==i.baseCommit||r.contractHash!==(i.contractHash??null)||r.operationId!==i.checkExecution?.operationId||r.planHash!==i.checkExecution.key||r.machineId!==i.checkExecution.machineId||r.inputFingerprint!==i.checkExecution.inputFingerprint||i.checkExecution.status!=="completed"||i.checkExecution.receiptRef!==e.receiptRef||!Array.isArray(r.checks)||r.checks.length===0||!a||!o||!Array.isArray(r.materials)||r.materials.some(({content:s,hash:c})=>os(s)!==c))throw new Error("Native Supervisor receipt does not match the current candidate, runId, contract or execution");return r}var Lh=T(()=>{"use strict";Jn();We();Ao();pe();Mn();hh();ui();ve();ie();ii();kr()});var lk=hr(Gt(),1);import{promises as I0}from"node:fs";import Bt from"node:path";yn();bn();import{execFileSync as H_}from"child_process";import D_ from"fs";import Ri from"path";import{AsyncLocalStorage as Xw}from"node:async_hooks";Xa();var Ci=new Xw,Qw=new Xw;function Zw(e){return Ci.getStore()?e():Ci.run(new Map,e)}function B_(e){let t=Ci.getStore();for(let r of e)t?.set(Jr(r.root),e);return e}function Ur(e,t){return Ka(()=>H_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function Kr(e,t){return Jr(e)===Jr(t)}function Jr(e){let t=Ri.resolve(e);try{let r=D_.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function oe(e){try{let t=Qw.getStore()?.get(Jr(e)),r=Ci.getStore()?.get(t??Jr(e));if(r){let c=Yw(t??e,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=Ri.resolve(Ur(e,["rev-parse","--show-toplevel"])),n=Ci.getStore()?.get(Jr(i))??ey(e),a=Yw(i,n);if(Ci.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=Ur(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Kr(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Bc(e){try{let t=Ci.getStore()?.get(Qw.getStore()?.get(Jr(e))??Jr(e));return t?t.map(r=>({...r})):(Ur(e,["rev-parse","--is-inside-work-tree"]),ey(e))}catch{return[]}}function ey(e){let t=L_(Ur(e,["worktree","list","--porcelain","-z"]));return B_(t),t.map(r=>({...r}))}function L_(e){let t=e.split("\0"),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:Ri.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 gr(e){return Bc(e).map(t=>t.root)}function Yw(e,t){let r=t.find(a=>Kr(Ri.resolve(a.root),Ri.resolve(e)));if(!r)return null;let i=Ri.resolve(t[0].root),n=Ri.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!Kr(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function ty(e){try{return Ur(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function Nn(e,t){try{return Ur(e,["check-ref-format","--branch",t]),Ur(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function wr(e,t){try{let r=Ur(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}We();rt();pe();gt();ie();at();hl();hl();Hi();kr();import{randomUUID as R0}from"node:crypto";import yu from"node:path";We();Ao();ne();pe();Mn();ve();ie();hh();Hi();kr();Jn();We();import{promises as Go}from"node:fs";import Qe from"node:path";gt();Jn();Ho();ie();var ai=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function vN(e,t){let r=Qe.relative(e,t);return r===""||!Qe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Qe.sep}`)}function hN(e){return JSON.stringify(e.native)}async function au(e,t){let r=await Oe(e);if(r&&t){if(hN(r)!==hN(t))throw new Error(`Native worktree configuration differs from the source project: ${Qe.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await al(e,t),await fN(e),!0):!1}async function B$(e,t){if(!vN(e,t))return!1;let i=`/${Qe.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=I(e,["rev-parse","--git-common-dir"]),a=Qe.resolve(e,n),o=Qe.join(a,"info","exclude"),s="";try{s=await Go.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Go.mkdir(Qe.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
230
234
|
`)?"":`
|
|
231
|
-
`;return await
|
|
232
|
-
`,"utf8"),!0}function P$(e,t,r){let i=Qe.resolve(e,r??Qe.join(".worktrees",t)),n=Qe.resolve(e,I(e,["rev-parse","--git-common-dir"]));if(aN(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(gr(e).some(a=>Kr(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function _$(e){try{throw await zo.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function nN(e){try{return await zo.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function pf(e){let t=Qe.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=oe(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await ei(t,e.sourceConfig?.native.artifact_root??"docs");return rb([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=oe(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;Lp(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(Lp(t,o),!bn(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let h=!1;if(!a){if(!Hc(t))throw new Error("Native branch isolation requires a clean current working directory");if(bn(t,n))throw new Error(`Native change branch already exists: ${n}`);I(t,["switch","-c",n,o]),h=!0}let f;try{f=await ru(t,e.sourceConfig)}catch(m){throw new ai(`Native branch preparation is incomplete: ${m.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:f}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let h=e.worktreePath?Qe.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!Kr(h,i.currentWorktreeRoot))throw new Error(`Native worktree path ${h} does not match the current worktree ${i.currentWorktreeRoot}`);let f;try{f=await ru(t,e.sourceConfig)}catch(m){throw new ai(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:f}}}let s=Oc(i.primaryWorktreeRoot),c=s.find(h=>h.branch===n);if(c&&await nN(c.root)){let h=e.worktreePath?Qe.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!Kr(h,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let f;try{f=await ru(c.root,e.sourceConfig)}catch(m){throw new ai(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:f}}}c&&!await nN(c.root)&&(I(i.primaryWorktreeRoot,["worktree","prune"]),s=Oc(i.primaryWorktreeRoot));let l=bn(t,n);if(s.some(h=>h.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=P$(i.primaryWorktreeRoot,e.name,e.worktreePath);await _$(u);let d=await C$(i.primaryWorktreeRoot,u),p={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{I(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),p.createdBranch=!l,p.createdWorktree=!0,p.configInitialized=await ru(u,e.sourceConfig)}catch(h){throw new ai(`Native worktree preparation is incomplete: ${h.message}`,p,{cause:h})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:p}})}function gu(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}async function Df(e){let t=vu.join(".worktrees",`${e.parent}-integration`);return pf({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:gu(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function Bf(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return pf({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:vu.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function v0(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function g0(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}function UN(e,t,r){let i=oe(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!tr(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=I(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return I(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return I(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(I(e,["merge","--ff-only",r]),I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function os(e){if(!tr(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=I(e.integration.worktree,["rev-parse","--show-toplevel"]);if(vu.resolve(t)!==vu.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=I(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return I(e.integration.worktree,["rev-parse","HEAD"])}function KN(e,t,r){let i=oe(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!tr(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}async function Lf(e){let t=v0(e.retryCheckIds),r=await A(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let h=await D(e.paths,e.state.parent)??e.state,f=h.integration.checkExecution;if(f?.status==="running"){if(await Ln(f.ownerPid,f.ownerIdentity))throw new Error("Native Supervisor integration checks are already running; wait for the original execution");if(f.activeProcess===void 0||f.activeProcess?.status==="starting")throw new Error("Native Supervisor integration check launch was interrupted; inspect the original check process before retrying");if(f.activeProcess&&await Ln(f.activeProcess.pid,f.activeProcess.identity))throw new Error("Native Supervisor integration check process is still running after its owner stopped; wait for that process before retrying")}if(h.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let m=h.children.find(({name:E})=>E===e.name);if(!m)throw new Error(`Native Supervisor child ${e.name} does not exist`);let v=$y(h).find(({status:E})=>E!=="integrated"&&E!=="archived");if(v&&v.name!==e.name)throw new Error(`Native Supervisor integration order requires ${v.name} before ${e.name}`);if(m.status!=="verified"||!m.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);if(e.checkPlans){if(e.checkPlans.some(({repeatable:x})=>!x))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(e.checkPlans.length===0||new Set(e.checkPlans.map(({id:x})=>x)).size!==e.checkPlans.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(lt(h.integration.worktree,e.checkPlans),!m.verification?.receiptRef||!m.verification.execution)throw new Error("Native Supervisor integration requires current Runtime verification evidence; reverify the child");let{readNativeSupervisorCheckEvidence:E}=await Promise.resolve().then(()=>(Hf(),JN)),b=await E({paths:e.paths,parent:h.parent,task:m.verification.execution,receiptRef:m.verification.receiptRef});if(b.candidateCommit!==m.verifiedCommit||b.checks.some(({status:x})=>x!=="passed"))throw new Error("Native Supervisor integration verification evidence is stale or failed")}let g=os(h),w=e.checkPlans!==void 0&&f?.status==="interrupted"&&f.child===e.name&&f.candidateCommit===m.verifiedCommit&&g!==h.integration.headCommit&&g===f.integrationCommit;if(g!==h.integration.headCommit){let E=(()=>{try{return I(h.integration.worktree,["merge-base","--is-ancestor",h.integration.headCommit,g]),!0}catch{return!1}})(),b=(()=>{try{return I(h.integration.worktree,["merge-base","--is-ancestor",m.verifiedCommit,g]),!0}catch{return!1}})();if(!E||!b)throw new Error(`Native Supervisor integration head drifted: expected ${h.integration.headCommit}, got ${g}`)}try{I(h.integration.worktree,["cat-file","-e",`${m.verifiedCommit}^{commit}`])}catch(E){throw new Error(`Native Supervisor verified commit is unavailable: ${m.verifiedCommit}`,{cause:E})}if(g===h.integration.headCommit&&!w){try{I(h.integration.worktree,["merge","--no-ff","--no-edit",m.verifiedCommit])}catch(E){throw new Error(`Native Supervisor integration conflict preserved in ${h.integration.worktree}`,{cause:E})}g=I(h.integration.worktree,["rev-parse","HEAD"])}let N=g;if(e.checkPlans){let E=Zl(),b=await Ql({kind:"integration",parent:h.parent,child:e.name,runId:m.verification?.execution?.runId??`integration:${e.name}`,projectRoot:h.integration.worktree,candidateCommit:m.verifiedCommit,integrationCommit:N,contractHash:m.contractHash??null,plans:e.checkPlans,materials:[]}),x=$("comet.native.supervisor-integration-plan.v2",{machineId:E,inputFingerprint:b}),k=f?.key===x&&f.machineId===E&&f.inputFingerprint===b&&f.child===e.name&&f.candidateCommit===m.verifiedCommit&&f.integrationCommit===N;if(t){if(!k||f?.status!=="interrupted")throw new Error("Native Supervisor integration retry requires the interrupted current plan on the same candidate, machine and workspace");g0(f.checkStates,e.checkPlans,t)}else if(f?.status==="interrupted"&&k){let _=(f.checkStates??[]).filter(({status:j})=>j==="failed");if(_.length>0)throw new Error(`Native Supervisor integration checks already failed on the identical plan (${_.map(({id:j})=>j).join(", ")}); change the integration check plan or re-verify the child instead of rerunning the same integrate`);return{completed:h}}let S=t&&f?.checkStates?f.checkStates.map(_=>t.has(_.id)?{..._,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{..._}):e.checkPlans.map(zn),C=e.checkPlans.map(_=>S.find(j=>j.id===_.id)??zn(_)),P=m0();return h.integration.checkExecution={operationId:P,key:x,child:e.name,candidateCommit:m.verifiedCommit,integrationCommit:N,status:"running",ownerPid:process.pid,ownerIdentity:await ct(process.pid)??void 0,startedAt:new Date().toISOString(),activeProcess:null,machineId:E,inputFingerprint:b,checkStates:C},h.stateVersion+=1,await F(e.paths,h),{pending:{state:h,candidateCommit:m.verifiedCommit,integrationCommit:N,operationId:P,key:x,machineId:E,inputFingerprint:b,plansToExecute:e.checkPlans.filter(_=>!t||t.has(_.id))}}}let y=vl(h,{name:e.name,integrationCommit:N,checks:e.checks});return await F(e.paths,y),{completed:y}});if(r.completed)return r.completed;let{state:i,candidateCommit:n,integrationCommit:a,operationId:o,key:s}=r.pending,{writeNativeVerificationReportSnapshot:c}=await Promise.resolve().then(()=>(ui(),zN)),{createHash:l}=await import("node:crypto"),u=async p=>A(e.paths,"record Supervisor integration check process",async()=>{let h=await D(e.paths,i.parent),f=h?.integration.checkExecution;if(!h||f?.operationId!==o||f.key!==s||f.status!=="running")throw new Error("Native Supervisor integration check operation is stale");if(p?.status==="starting"){let m=f.checkStates?.find(({id:v})=>v===p.checkId);if(!m||m.status!=="planned")throw new Error(`Native Supervisor check ${p.checkId} is not planned`);m.status="running",m.executionCount+=1,m.startedAt=new Date().toISOString(),m.completedAt=null,m.logRef=null}f.activeProcess=p,h.stateVersion+=1,await F(e.paths,h)}),d=async p=>A(e.paths,"record Supervisor integration check result",async()=>{let h=await D(e.paths,i.parent),f=h?.integration.checkExecution;if(!h||f?.operationId!==o||f.key!==s||f.status!=="running")throw new Error("Native Supervisor integration check operation is stale");let m=f.checkStates?.find(({id:v})=>v===p.id);if(!m)throw new Error(`Native Supervisor check state is missing: ${p.id}`);Object.assign(m,Yl(m,p)),f.activeProcess=null,h.stateVersion+=1,await F(e.paths,h)});try{for(let y of r.pending.plansToExecute){await u({status:"starting",checkId:y.id});let E=await Bi({projectRoot:i.integration.worktree,runtimeDir:me(e.paths,i.parent),operationId:o,plan:y,onSpawn:async({pid:b})=>u({status:"running",checkId:y.id,pid:b,identity:await ct(b)??void 0})});if(await d(E),E.status==="interrupted")throw new Error(`Native Supervisor integration check ${E.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let p=await D(e.paths,i.parent),f=p?.integration.checkExecution?.checkStates;if(!p||!f||f.some(({status:y})=>!["passed","failed"].includes(y)))throw new Error("Native Supervisor integration check plan remains incomplete; retry each interrupted check explicitly");let m=f.map(Xl),v=JSON.stringify({schema:"comet.native.supervisor-integration-checks.v1",parent:i.parent,child:e.name,candidateCommit:n,integrationCommit:a,operationId:o,planHash:s,results:m}),g=await c({paths:e.paths,name:i.parent,hash:l("sha256").update(v).digest("hex"),text:v}),w=m.map(y=>({name:y.name,status:y.status==="interrupted"?"incomplete":y.status,reason:y.status==="passed"?null:y.timedOut?"timed out":`exit ${y.exitCode??y.signal??"interrupted"}`,receiptRef:g})),N=w.filter(({status:y})=>y!=="passed");return await A(e.paths,"complete Supervisor integration checks",async()=>{let y=await D(e.paths,i.parent),E=y?.children.find(({name:k})=>k===e.name),b=y?.integration.checkExecution;if(!y||!E||b?.operationId!==o||b.key!==s||b.status!=="running"||b.child!==e.name||b.candidateCommit!==n||b.integrationCommit!==a||E.verifiedCommit!==n||os(y)!==a)throw new Error("Native Supervisor integration changed during checks");if(b.receiptRef=g,b.checks=w,N.length>0){let k=`Native Supervisor integration checks did not pass (${N.map(({name:S,reason:C})=>`${S}: ${C}`).join("; ")}); receipt ${g}`;throw b.status="interrupted",b.error=k,E.blocker=k,y.stateVersion+=1,await F(e.paths,y),new Error(k)}b.status="completed";let x=vl(y,{name:e.name,integrationCommit:a,checks:w});return await F(e.paths,x),x})}catch(p){throw await A(e.paths,"interrupt Supervisor integration checks",async()=>{let h=await D(e.paths,i.parent),f=h?.integration.checkExecution;if(h&&f?.operationId===o&&f.key===s&&f.status==="running"){f.status="interrupted",f.error=p.message,f.activeProcess=null;for(let m of f.checkStates??[])(m.status==="planned"||m.status==="running")&&(m.status="interrupted");h.stateVersion+=1,await F(e.paths,h)}}),p}}import{randomUUID as w0}from"node:crypto";import y0 from"node:path";We();gt();ve();Hi();kr();async function ss(e){let t=gu(e.parent),r=wr(e.paths.projectRoot,t);if(!r)return null;let i=wr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=gr(e.paths.projectRoot).map(o=>y0.resolve(o)).find(o=>oe(o).currentBranch===t);if(!n)return null;let a=xo({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 ot(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}async function qf(e){return A(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await D(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await Oe(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let u=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!u)continue;let d;try{d=await Bf({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),u?KN(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):UN(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(h){let f=Ue(o),m=f.children.find(({name:v})=>v===l.name);m&&(m.blocker=h.message,ot(f,{kind:"task-blocked",child:l.name,runId:null,summary:m.blocker}),f.stateVersion+=1,o=f,c=!0);continue}let p=Ro(o,{role:u?"verifier":"builder",child:l.name,projectRoot:d.projectRoot,runId:w0()});o=p.state,s.push(p.task)}return(s.length>0||c)&&await F(e.paths,o),{state:o,tasks:s}})}function YN(e,t){if(Nt(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=Ue(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Ki(e){let t=os(e);if(t===e.integration.headCommit)return e;try{I(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=Ue(e);return r.integration.headCommit=t,ot(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Yi(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=os(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return YN(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function Ff(e,t){let r=Bt.normalize(Bt.resolve(e)),i=Bt.normalize(Bt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function N0(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 k0(e){let t=N0(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 cs(e){try{let t=await Z({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return k0(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ea(e){return $("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 S0(e){let t=gr(e.projectRoot);t.some(i=>Ff(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Bt.resolve(n)))]){let n=await Oe(i);n&&r.push({projectRoot:i,paths:await ei(i,n.native.artifact_root),parent:Ff(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function E0(e,t){let r=Bt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await yt(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function x0(e,t){let r;try{r=await b0.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=Bt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await yt(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function R0(e,t,r){let i=Bt.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Bt.sep}`))return null;let n=i.split(Bt.sep).join("/");try{let a=(0,QN.parseDocument)(I(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:B(a.toJS({mapAsMap:!1}))}catch{return null}}function C0(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 XN(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Le(e){let t=Bt.join(e.paths.changesDir,e.state.name),r=await cs(t),i=null,n;try{n=await Je({changeDir:t,validation:bt(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 D(e.paths,e.state.name,{diagnostics:!0});if(g){let w=gl(g);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(N=>({...N,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=ea({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===ti){let g=await D(e.paths,e.state.name,{diagnostics:!0});if(!g){let y=e.state.workspace.change_branch??e.state.workspace.target_branch;if(y){let E=await ss({paths:e.paths,parent:e.state.name,targetBranch:y,contract:n.contract});E&&(g=E,await F(e.paths,E))}}if(g){let y=gl(g);return e.state.children_contract_hash!==a||n.drift?{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(E=>({...E,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&y.confirmed}}let w=new Map(n.contract.children.map(y=>[y.name,y])),N=n.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:s&&y.depends_on.every(E=>n.contract.children.filter(({name:b})=>b!==y.name).every(({name:b})=>b!==E))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let y of N){if(y.status!=="ready")continue;w.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:N,readyChildren:N.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let c=await S0(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let w=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await x0(g,l)){let y={...N,source:g,committedState:R0(g,N.file,w)};u.set(N.state.name,[...u.get(N.state.name)??[],y])}for(let N of l){let y=await E0(g,N);y&&d.set(N,[...d.get(N)??[],{source:g,state:y}])}}let p=new Map;for(let g of n.contract.children){let w=(u.get(g.name)??[]).find(({source:E,committedState:b})=>E.parent&&b?.name===g.name&&XN(b,o));if(w){p.set(g.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let N=u.get(g.name)?.[0];if(N){p.set(g.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=d.get(g.name)??[];y.length>1?p.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):y[0]&&p.set(g.name,C0(y[0].state,y[0].source,o))}let h=new Map(n.contract.children.map(g=>[g.name,g])),f=new Map,m=g=>{let w=f.get(g);if(w)return w;let N=h.get(g),E=N.depends_on.map(m).every(({status:P})=>P==="done"),b=p.get(g),x=b?.kind==="active"&&E?N.depends_on.filter(P=>!(u.get(P)??[]).some(({source:_,committedState:j})=>Ff(_.projectRoot,b.projectRoot)&&j?.name===P&&XN(j,o))):[],k,S=b?.message??null;b?.kind==="done"?(k=E?"done":"blocked",E||(S=`Native child ${g} was merged before its dependencies`)):b?.kind==="active"?(k=E&&x.length===0?"active":"blocked",E?x.length>0&&(S=`Native child ${g} does not include merged dependencies: ${x.join(", ")}`):S=`Native child ${g} started before its dependencies merged`):b?.kind==="blocked"?k="blocked":(k=s&&E?"ready":"pending",s||(S="Parent Shape confirmation is required"));let C={name:g,summary:N.summary,dependsOn:[...N.depends_on],covers:[...N.covers],status:k,phase:b?.phase??null,projectRoot:b?.projectRoot??null,message:S};return f.set(g,C),C},v=n.contract.children.map(({name:g})=>m(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")}}jn();Hi();function Re(e,t,r){return e.language==="zh-CN"?r:t}function P0(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:Re(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:Re(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:Re(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(Re(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(Re(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"?Re(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):Re(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} ${Re(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:Re(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:Re(e,"Accept the result","接受结果"),agentInstruction:Re(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)>=Nr)??!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(Re(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(Re(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 _0(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 A0(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:Re(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Re(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function rk(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Xi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function ZN(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function I0(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function ek(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function T0(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function $0(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function cr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:rk({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Xi("summary","--summary"),I0(e.name,e.flag)]}}function tk(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:Re(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function j0(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function wu(e){return[cr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),cr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function O0(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 Y(e,t,r={}){let i=T0(t)&&e.coordination_mode===void 0,n=P0(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:[Xi("summary","--summary")],commandAlternatives:i?il.map(s=>{let c=cr({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,ek("coordination-mode","--coordination-mode",[s])]}}):[cr({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:[Xi("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=cr({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]}}):[],cr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...wu({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:[Xi("summary","--summary")],commandAlternatives:[cr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),cr({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:[Xi("summary","--summary")],commandAlternatives:[cr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...wu({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:[Xi("summary","--summary")],commandAlternatives:wu({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:wu({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?rk({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:$0({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:f})=>f),acceptance_review:e.acceptance.map(({id:f})=>({id:f,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[ZN()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:f})=>f==="verified");if(s){let f=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}],...f&&f.length>0?{retry_check_ids:[...f]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:f})=>f==="blocked"||f==="needs-reverify"),l=t.children.some(({status:f})=>f==="needs-reverify"),u=t.children.some(({status:f})=>f==="ready"||f==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(f=>f.status==="blocked"&&(f.builderFailureCount??0)>=Nr)??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:Re(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},h=c&&!l&&!u&&p===null;return{...a,disposition:h?"blocked":"continue",action:"advance-children",commandArgs:h?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:h?[]:p!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:h?[]:p!==null?[p]:[Xi("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=ZN();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} ${Re(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:O0([{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=tk(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>j0(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:tk(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:[ek("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...A0(e)],userCommunication:_0(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[cr({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")}}We();_o();pe();import{createHash as sS,randomUUID as cS}from"node:crypto";import{promises as ur}from"node:fs";import Tr from"node:os";import O from"node:path";We();br();ne();import{createHash as H0}from"node:crypto";import yu from"node:path";var ik=".comet/runtime/native/runner-input-artifacts.json",nk=256,ak=8*1024*1024;function ok(e){return H0("sha256").update(e).digest("hex")}function Qi(e){return process.platform==="win32"?e.toLowerCase():e}function bu(e,t){let r=yu.relative(e,yu.resolve(e,t)).replaceAll("\\","/");return r&&!yu.isAbsolute(r)&&r!==".."&&!r.startsWith("../")?r:null}async function D0(e){try{let t=await nt(e,ik,262144,{label:"Native Runner input registry"}),r=JSON.parse(t.bytes.toString("utf8"));if(!Array.isArray(r)||r.length>nk)throw new Error("Invalid Native Runner input registry");return r.map(i=>{let n=i;if(!n||typeof n.path!="string"||bu(e,n.path)!==n.path||typeof n.digest!="string"||!/^[a-f0-9]{64}$/u.test(n.digest))throw new Error("Invalid Native Runner input artifact");return{path:n.path,digest:n.digest}})}catch{return[]}}function sk(e){try{return new Set(I(e,["ls-files","-z"]).split("\0").filter(Boolean).map(Qi))}catch{return null}}async function ck(e){let t=await D0(e);if(!t.length)return[];let r=sk(e);if(!r)return[];let i=[];for(let n of t)if(!r.has(Qi(n.path)))try{let a=await nt(e,n.path,ak,{label:"Native Runner input artifact"}),o=bu(e,a.realPath);o&&!r.has(Qi(o))&&ok(a.bytes)===n.digest&&i.push({path:o,digest:n.digest})}catch{}return i}async function Mf(e){return new Set((await ck(e)).map(t=>t.path))}async function lk(e){let t=bu(e.paths.projectRoot,e.file);if(!t)return;let r=sk(e.paths.projectRoot);if(!r||r.has(Qi(t)))return;let i=await nt(e.paths.projectRoot,t,ak,{label:"Native Runner input artifact"});e.validateContent(i.bytes.toString("utf8"));let n=bu(e.paths.projectRoot,i.realPath);if(!n||r.has(Qi(n)))return;let a=(await ck(e.paths.projectRoot)).filter(o=>Qi(o.path)!==Qi(n));if(a.length>=nk)throw new Error("Too many retained Native Runner input files; remove unused protocol files before continuing");await fe(yu.join(e.paths.projectRoot,...ik.split("/")),[...a,{path:n,digest:ok(i.bytes)}],{containedRoot:e.paths.runtimeDir})}Fn();vo();at();ni();ji();ko();import{randomUUID as B0}from"node:crypto";var Vf=3,Wf=2;function qe(e){return e.state_version+1}function L0(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function uk(e){return e.map(t=>({...t,result:"pending",reason:null}))}function zf(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function q0(e){return(e??[]).map(t=>({name:J(t.name),result:t.result,note:t.note?J(t.note):null}))}function di(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:J(e.summary),completed_at:e.completedAt}}function dk(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,phase:"build",status:"active",state_version:qe(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function pk(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,status:"await-user",state_version:qe(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function hk(e){let t=B(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Iy(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(r.review){if(r.review.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}let i=L0(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=r.acceptanceReview===void 0?void 0:Tn(r.acceptanceReview);$n(t.acceptance,n);let a=uk(t.acceptance),o=(r.now??new Date).toISOString();return B({...t,phase:"verify",state_version:qe(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??B0(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:J(r.summary),addressed_acceptance_ids:i,acceptance_review:n,checks:q0(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>J(s)),known_limits_truncated:!1,review:r.review?{status:"passed",summary:J(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef}:null,submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function fk(e){let t=B(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt requires a current Builder candidate");return B({...t,state_version:qe(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function F0(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function M0(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Se?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:J(e.response.result.summary),risks:e.response.result.risks.map(t=>J(t)),risks_truncated:!1,completed_at:e.completedAt}}function mk(e){let t=B(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=zf(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=Ty({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,knownAcceptanceIds:t.acceptance.map(({id:v})=>v),previouslyPassedAcceptanceIds:t.acceptance.filter(({result:v})=>v==="passed").map(({id:v})=>v),requiredChecksPassed:e.checks.every(({status:v})=>v==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(v=>[v.id,v])),o=t.acceptance.map(v=>{let g=a.get(v.id);return g?{...v,result:g.result,reason:J(g.reason)}:v}),s=o.filter(({result:v})=>v==="failed"||v==="blocked").map(({id:v})=>v),c=M0({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){let v=ke({...t,acceptance:o,verification:c},di({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),g=t.builder_handoff.identity_provider===Se;return{response:i,state:B({...v,phase:g?"verify":"archive",status:g?"await-user":"active",state_version:qe(t),verification_result:"pass",verification_report:"verification.md",blockers:g?[{owner:"user",reason:J("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:g?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:g?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let v=ke({...t,acceptance:o,verification:c},di({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...v,status:"await-user",state_version:qe(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:J(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,u=F0(t,s),d=l>=e.maxVerifyFailures,p=u>=3,h=d||p,f=p?"stalled":d?"budget":void 0,m=ke({...t,acceptance:o,verification:c},di({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...m,phase:h?"verify":"build",status:h?"await-user":"active",state_version:qe(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:h?[{owner:"user",reason:J(f==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:u>=2?[{owner:"builder",reason:J("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:h?"await-user":"repairing",iteration:h?t.loop.iteration:t.loop.iteration+1,attempt:h?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:u,...f===void 0?{}:{stop_reason:f},execution_failure_count:0,previous_unresolved_ids:s,next_action:h?"await-user":"repair-failed-acceptance"}})}}function vk(e){let t=B(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Se||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return B({...t,phase:"archive",status:"active",state_version:qe(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function gk(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Se||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=zf(t),n=ke(t,di({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return B({...n,status:"await-user",state_version:qe(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:J(e.summary),risks:[J("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:J("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function wk(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=J(e.summary),n=ke(t,di({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return B({...n,phase:"archive",status:"active",state_version:qe(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:J(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function yk(e,t){let r=B(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=ke(r,di({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return B({...i,status:"active",state_version:qe(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function bk(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=Vf,a=ke(t,di({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return B({...a,status:n?"blocked":"active",state_version:qe(t),blockers:n?[{owner:"runtime",reason:J(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Nk(e){let t=B(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=zf(t),a=t.acceptance.some(({result:o})=>o==="passed");return B({...t,status:"active",state_version:qe(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function pi(e){let t=B(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,i=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,n=r!==void 0&&i>=r.maxVerifyFailures,a=(e.now??new Date).toISOString(),o=ke(t,di({state:t,outcome:"recovery",summary:e.reason,completedAt:a})),s=new Set(t.loop.previous_unresolved_ids),c=s.size===0?uk(t.acceptance):t.acceptance.map(l=>s.has(l.id)?{...l,result:"pending",reason:null}:l);return n?B({...o,phase:"verify",status:"await-user",state_version:qe(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:J(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:i,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):B({...o,phase:"build",status:"active",state_version:qe(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:c,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:i,stop_reason:void 0,next_action:"submit-builder-candidate"}})}ne();jn();import{promises as kk}from"node:fs";import V0 from"node:os";import ds from"node:path";function ls(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function us(e,t,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 Fe(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 ta(e,t){return e===null?null:Fe(e,t)}function ra(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 W0(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 z0(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ia(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Gf(e,t){if(e===null)return null;let r=Fe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function G0(e,t){let r=Fe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Jf(e,t){let r=Fe(e,t);if(!ds.isAbsolute(r))throw new Error(`${t} must be absolute`);return ds.resolve(r)}function J0(e,t){let r=`Native local checks[${t}]`,i=ls(e,r);if(us(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)=>Fe(u,`${r}.argv[${d}]`,!0)),a=ia(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Gf(i.startedAt,`${r}.startedAt`),s=Gf(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=ra(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=ls(i.activeProcess,`${r}.activeProcess`),d=ia(u.status,["starting","running"],`${r}.activeProcess.status`);if(us(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:ra(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:Fe(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:Fe(i.id,`${r}.id`),name:Fe(i.name,`${r}.name`),operationId:Fe(i.operationId,`${r}.operationId`),status:a,repeatable:z0(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:ra(i.executionCount,`${r}.executionCount`),argv:n,cwd:Jf(i.cwd,`${r}.cwd`),exitCode:W0(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Fe(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:ia(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:Fe(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function Uf(e){let t="Native local execution state",r=ls(e,t);if(us(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==go)throw new Error(`Native local execution schema must be ${go}`);let i=ls(r.workspace,"Native local workspace");us(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=ls(r.execution,"Native local execution");us(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Gf(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Fe(o.operationId,"Native local execution.operationId"),stage:ia(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:ia(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ta(o.executionId,"Native local execution.executionId"),status:ia(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ra(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:G0(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:ra(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:Fe(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(J0);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:go,change:Fe(r.change,"Native local change"),basedOnStateVersion:ra(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:ta(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:ta(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:ta(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:ta(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Jf(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Jf(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ta(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:Fe(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function ae(e){return Uf({schema:go,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,candidateId:e.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:ds.resolve(e.projectRoot),worktreeRoot:ds.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:V0.hostname()},execution:null,checks:[]})}async function Ce(e){let t;try{t=await kk.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 Uf(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 Sk(e,t){if(Kf(e,t)!==void 0)return t.execution.verifierStartedAt!=null||t.execution.requestCheckRounds>0?"confirmed":"unconfirmed"}async function M(e,t,r={}){let i=Uf(t);await kk.mkdir(ds.dirname(e),{recursive:!0}),await fe(e,i,r)}async function Nu(e){let t=null,r=null;try{t=await Ce(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=ae(e);return await M(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}ve();ni();ie();async function Yf(e,t,r){if(!Number.isInteger(t)||t<1)throw new Error("Concurrency must be a positive integer");let i=new Array(e.length),n=0,a=async()=>{for(;n<e.length;){let o=n;n+=1,i[o]=await r(e[o],o)}};return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>a())),i}import{promises as Ek}from"node:fs";import ku from"node:path";We();at();ie();var Xf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xk="comet-state.yaml",Rk="state.json";function le(e,t){if(!Xf.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ku.join(e.changesDir,t);if(!Ee(e.changesDir,r))throw new Error("Native change path escaped");return r}function dt(e,t){return ku.join(le(e,t),xk)}function L(e,t){return ku.join(me(e,t),Rk)}async function na(e,t){try{let r=await Ek.readFile(dt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function ge(e){return Yw(e)}function Su(e,t){let r=oe(t);if(!r.isGitWorktree||r.currentBranch===null||wr(t,r.currentBranch)===null)return null;if(!Hc(t))throw new Error("Native Supervisor Git binding requires a clean current working directory; commit or stash pending changes, then rerun the latest continuation");return{...e,change_branch:r.currentBranch,target_branch:r.currentBranch}}async function H(e,t){return yt(dt(e,t))}async function he(e){let t=await Dn({file:dt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=ku.join(le(e.paths,t.name),"verification.md");await G(e.paths.nativeRoot,r),await Ek.rm(r,{force:!0})}return t}async function Qf(e){let t=await H(e.paths,e.name),r=L(e.paths,e.name);try{let i=await Ce(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"}}}import{promises as Tu}from"node:fs";import rn from"node:path";function rm(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var tn=rm();function jk(e){tn=e}var Zi={exec:()=>null};function aa(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 V(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 U0=((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:aa(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:aa(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:aa(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:aa(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:aa(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:aa(e=>new RegExp(`^ {0,${e}}>`))},K0=/^(?:[ \t]*(?:\n|$))+/,Y0=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,X0=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,fs=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Q0=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,im=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ok=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Hk=V(Ok).replace(/bull/g,im).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(),Z0=V(Ok).replace(/bull/g,im).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(),nm=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,eO=/^[^\n]+/,am=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,tO=V(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",am).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),rO=V(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,im).getRegex(),Pu="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",om=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,iO=V("^ {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",om).replace("tag",Pu).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Dk=e=>V(nm).replace("hr",fs).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",Pu).getRegex(),nO=Dk(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),aO=Dk(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),oO=V(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",aO).getRegex(),sm={blockquote:oO,code:Y0,def:tO,fences:X0,heading:Q0,hr:fs,html:iO,lheading:Hk,list:rO,newline:K0,paragraph:nO,table:Zi,text:eO},Ck=V("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",fs).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",Pu).getRegex(),sO={...sm,lheading:Z0,table:Ck,paragraph:V(nm).replace("hr",fs).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Ck).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",Pu).getRegex()},cO={...sm,html:V(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",om).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:Zi,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:V(nm).replace("hr",fs).replace("heading",` *#{1,6} *[^
|
|
233
|
-
]`).replace("lheading",
|
|
235
|
+
`;return await Go.appendFile(o,`${c}${i}
|
|
236
|
+
`,"utf8"),!0}function L$(e,t,r){let i=Qe.resolve(e,r??Qe.join(".worktrees",t)),n=Qe.resolve(e,I(e,["rev-parse","--git-common-dir"]));if(vN(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(gr(e).some(a=>Kr(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function F$(e){try{throw await Go.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function mN(e){try{return await Go.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function mh(e){let t=Qe.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=oe(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await ei(t,e.sourceConfig?.native.artifact_root??"docs");return sb([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=oe(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;qp(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(qp(t,o),!Nn(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let f=!1;if(!a){if(!Lc(t))throw new Error("Native branch isolation requires a clean current working directory");if(Nn(t,n))throw new Error(`Native change branch already exists: ${n}`);I(t,["switch","-c",n,o]),f=!0}let h;try{h=await au(t,e.sourceConfig)}catch(m){throw new ai(`Native branch preparation is incomplete: ${m.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:f,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:f,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:h}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let f=e.worktreePath?Qe.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(f&&!Kr(f,i.currentWorktreeRoot))throw new Error(`Native worktree path ${f} does not match the current worktree ${i.currentWorktreeRoot}`);let h;try{h=await au(t,e.sourceConfig)}catch(m){throw new ai(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:h}}}let s=Bc(i.primaryWorktreeRoot),c=s.find(f=>f.branch===n);if(c&&await mN(c.root)){let f=e.worktreePath?Qe.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(f&&!Kr(f,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let h;try{h=await au(c.root,e.sourceConfig)}catch(m){throw new ai(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:h}}}c&&!await mN(c.root)&&(I(i.primaryWorktreeRoot,["worktree","prune"]),s=Bc(i.primaryWorktreeRoot));let l=Nn(t,n);if(s.some(f=>f.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=L$(i.primaryWorktreeRoot,e.name,e.worktreePath);await F$(u);let p=await B$(i.primaryWorktreeRoot,u),d={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:p,configInitialized:!1};try{I(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),d.createdBranch=!l,d.createdWorktree=!0,d.configInitialized=await au(u,e.sourceConfig)}catch(f){throw new ai(`Native worktree preparation is incomplete: ${f.message}`,d,{cause:f})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:d}})}function bu(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}async function Fh(e){let t=yu.join(".worktrees",`${e.parent}-integration`);return mh({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:bu(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function qh(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return mh({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:yu.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function C0(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function P0(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}function ak(e,t,r){let i=oe(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!tr(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=I(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return I(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return I(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(I(e,["merge","--ff-only",r]),I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function ss(e){if(!tr(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=I(e.integration.worktree,["rev-parse","--show-toplevel"]);if(yu.resolve(t)!==yu.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=I(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return I(e.integration.worktree,["rev-parse","HEAD"])}function ok(e,t,r){let i=oe(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!tr(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}async function Mh(e){let t=C0(e.retryCheckIds),r=await A(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let f=await D(e.paths,e.state.parent)??e.state,h=f.integration.checkExecution;if(h?.status==="running"){if(await Fn(h.ownerPid,h.ownerIdentity))throw new Error("Native Supervisor integration checks are already running; wait for the original execution");if(h.activeProcess===void 0||h.activeProcess?.status==="starting")throw new Error("Native Supervisor integration check launch was interrupted; inspect the original check process before retrying");if(h.activeProcess&&await Fn(h.activeProcess.pid,h.activeProcess.identity))throw new Error("Native Supervisor integration check process is still running after its owner stopped; wait for that process before retrying")}if(f.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let m=f.children.find(({name:E})=>E===e.name);if(!m)throw new Error(`Native Supervisor child ${e.name} does not exist`);let v=By(f).find(({status:E})=>E!=="integrated"&&E!=="archived");if(v&&v.name!==e.name)throw new Error(`Native Supervisor integration order requires ${v.name} before ${e.name}`);if(m.status!=="verified"||!m.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);if(e.checkPlans){if(e.checkPlans.some(({repeatable:x})=>!x))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(e.checkPlans.length===0||new Set(e.checkPlans.map(({id:x})=>x)).size!==e.checkPlans.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(lt(f.integration.worktree,e.checkPlans),!m.verification?.receiptRef||!m.verification.execution)throw new Error("Native Supervisor integration requires current Runtime verification evidence; reverify the child");let{readNativeSupervisorCheckEvidence:E}=await Promise.resolve().then(()=>(Lh(),nk)),b=await E({paths:e.paths,parent:f.parent,task:m.verification.execution,receiptRef:m.verification.receiptRef});if(b.candidateCommit!==m.verifiedCommit||b.checks.some(({status:x})=>x!=="passed"))throw new Error("Native Supervisor integration verification evidence is stale or failed")}let g=ss(f),w=e.checkPlans!==void 0&&h?.status==="interrupted"&&h.child===e.name&&h.candidateCommit===m.verifiedCommit&&g!==f.integration.headCommit&&g===h.integrationCommit;if(g!==f.integration.headCommit){let E=(()=>{try{return I(f.integration.worktree,["merge-base","--is-ancestor",f.integration.headCommit,g]),!0}catch{return!1}})(),b=(()=>{try{return I(f.integration.worktree,["merge-base","--is-ancestor",m.verifiedCommit,g]),!0}catch{return!1}})();if(!E||!b)throw new Error(`Native Supervisor integration head drifted: expected ${f.integration.headCommit}, got ${g}`)}try{I(f.integration.worktree,["cat-file","-e",`${m.verifiedCommit}^{commit}`])}catch(E){throw new Error(`Native Supervisor verified commit is unavailable: ${m.verifiedCommit}`,{cause:E})}if(g===f.integration.headCommit&&!w){try{I(f.integration.worktree,["merge","--no-ff","--no-edit",m.verifiedCommit])}catch(E){throw new Error(`Native Supervisor integration conflict preserved in ${f.integration.worktree}`,{cause:E})}g=I(f.integration.worktree,["rev-parse","HEAD"])}let N=g;if(e.checkPlans){let E=ru(),b=await tu({kind:"integration",parent:f.parent,child:e.name,runId:m.verification?.execution?.runId??`integration:${e.name}`,projectRoot:f.integration.worktree,candidateCommit:m.verifiedCommit,integrationCommit:N,contractHash:m.contractHash??null,plans:e.checkPlans,materials:[]}),x=$("comet.native.supervisor-integration-plan.v2",{machineId:E,inputFingerprint:b}),k=h?.key===x&&h.machineId===E&&h.inputFingerprint===b&&h.child===e.name&&h.candidateCommit===m.verifiedCommit&&h.integrationCommit===N;if(t){if(!k||h?.status!=="interrupted")throw new Error("Native Supervisor integration retry requires the interrupted current plan on the same candidate, machine and workspace");P0(h.checkStates,e.checkPlans,t)}else if(h?.status==="interrupted"&&k){let _=(h.checkStates??[]).filter(({status:j})=>j==="failed");if(_.length>0)throw new Error(`Native Supervisor integration checks already failed on the identical plan (${_.map(({id:j})=>j).join(", ")}); change the integration check plan or re-verify the child instead of rerunning the same integrate`);return{completed:f}}let S=t&&h?.checkStates?h.checkStates.map(_=>t.has(_.id)?{..._,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{..._}):e.checkPlans.map(Gn),C=e.checkPlans.map(_=>S.find(j=>j.id===_.id)??Gn(_)),P=R0();return f.integration.checkExecution={operationId:P,key:x,child:e.name,candidateCommit:m.verifiedCommit,integrationCommit:N,status:"running",ownerPid:process.pid,ownerIdentity:await ct(process.pid)??void 0,startedAt:new Date().toISOString(),activeProcess:null,machineId:E,inputFingerprint:b,checkStates:C},f.stateVersion+=1,await q(e.paths,f),{pending:{state:f,candidateCommit:m.verifiedCommit,integrationCommit:N,operationId:P,key:x,machineId:E,inputFingerprint:b,plansToExecute:e.checkPlans.filter(_=>!t||t.has(_.id))}}}let y=yl(f,{name:e.name,integrationCommit:N,checks:e.checks});return await q(e.paths,y),{completed:y}});if(r.completed)return r.completed;let{state:i,candidateCommit:n,integrationCommit:a,operationId:o,key:s}=r.pending,{writeNativeVerificationReportSnapshot:c}=await Promise.resolve().then(()=>(ui(),rk)),{createHash:l}=await import("node:crypto"),u=async d=>A(e.paths,"record Supervisor integration check process",async()=>{let f=await D(e.paths,i.parent),h=f?.integration.checkExecution;if(!f||h?.operationId!==o||h.key!==s||h.status!=="running")throw new Error("Native Supervisor integration check operation is stale");if(d?.status==="starting"){let m=h.checkStates?.find(({id:v})=>v===d.checkId);if(!m||m.status!=="planned")throw new Error(`Native Supervisor check ${d.checkId} is not planned`);m.status="running",m.executionCount+=1,m.startedAt=new Date().toISOString(),m.completedAt=null,m.logRef=null}h.activeProcess=d,f.stateVersion+=1,await q(e.paths,f)}),p=async d=>A(e.paths,"record Supervisor integration check result",async()=>{let f=await D(e.paths,i.parent),h=f?.integration.checkExecution;if(!f||h?.operationId!==o||h.key!==s||h.status!=="running")throw new Error("Native Supervisor integration check operation is stale");let m=h.checkStates?.find(({id:v})=>v===d.id);if(!m)throw new Error(`Native Supervisor check state is missing: ${d.id}`);Object.assign(m,Zl(m,d)),h.activeProcess=null,f.stateVersion+=1,await q(e.paths,f)});try{for(let y of r.pending.plansToExecute){await u({status:"starting",checkId:y.id});let E=await Bi({projectRoot:i.integration.worktree,runtimeDir:me(e.paths,i.parent),operationId:o,plan:y,onSpawn:async({pid:b})=>u({status:"running",checkId:y.id,pid:b,identity:await ct(b)??void 0})});if(await p(E),E.status==="interrupted")throw new Error(`Native Supervisor integration check ${E.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let d=await D(e.paths,i.parent),h=d?.integration.checkExecution?.checkStates;if(!d||!h||h.some(({status:y})=>!["passed","failed"].includes(y)))throw new Error("Native Supervisor integration check plan remains incomplete; retry each interrupted check explicitly");let m=h.map(eu),v=JSON.stringify({schema:"comet.native.supervisor-integration-checks.v1",parent:i.parent,child:e.name,candidateCommit:n,integrationCommit:a,operationId:o,planHash:s,results:m}),g=await c({paths:e.paths,name:i.parent,hash:l("sha256").update(v).digest("hex"),text:v}),w=m.map(y=>({name:y.name,status:y.status==="interrupted"?"incomplete":y.status,reason:y.status==="passed"?null:y.timedOut?"timed out":`exit ${y.exitCode??y.signal??"interrupted"}`,receiptRef:g})),N=w.filter(({status:y})=>y!=="passed");return await A(e.paths,"complete Supervisor integration checks",async()=>{let y=await D(e.paths,i.parent),E=y?.children.find(({name:k})=>k===e.name),b=y?.integration.checkExecution;if(!y||!E||b?.operationId!==o||b.key!==s||b.status!=="running"||b.child!==e.name||b.candidateCommit!==n||b.integrationCommit!==a||E.verifiedCommit!==n||ss(y)!==a)throw new Error("Native Supervisor integration changed during checks");if(b.receiptRef=g,b.checks=w,N.length>0){let k=`Native Supervisor integration checks did not pass (${N.map(({name:S,reason:C})=>`${S}: ${C}`).join("; ")}); receipt ${g}`;throw b.status="interrupted",b.error=k,E.blocker=k,y.stateVersion+=1,await q(e.paths,y),new Error(k)}b.status="completed";let x=yl(y,{name:e.name,integrationCommit:a,checks:w});return await q(e.paths,x),x})}catch(d){throw await A(e.paths,"interrupt Supervisor integration checks",async()=>{let f=await D(e.paths,i.parent),h=f?.integration.checkExecution;if(f&&h?.operationId===o&&h.key===s&&h.status==="running"){h.status="interrupted",h.error=d.message,h.activeProcess=null;for(let m of h.checkStates??[])(m.status==="planned"||m.status==="running")&&(m.status="interrupted");f.stateVersion+=1,await q(e.paths,f)}}),d}}import{randomUUID as _0}from"node:crypto";import A0 from"node:path";We();gt();ve();Hi();kr();async function cs(e){let t=bu(e.parent),r=wr(e.paths.projectRoot,t);if(!r)return null;let i=wr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=gr(e.paths.projectRoot).map(o=>A0.resolve(o)).find(o=>oe(o).currentBranch===t);if(!n)return null;let a=Ro({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 ot(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}async function Vh(e){return A(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await D(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await Oe(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let u=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!u)continue;let p;try{p=await qh({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),u?ok(p.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):ak(p.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(f){let h=Ue(o),m=h.children.find(({name:v})=>v===l.name);m&&(m.blocker=f.message,ot(h,{kind:"task-blocked",child:l.name,runId:null,summary:m.blocker}),h.stateVersion+=1,o=h,c=!0);continue}let d=Co(o,{role:u?"verifier":"builder",child:l.name,projectRoot:p.projectRoot,runId:_0()});o=d.state,s.push(d.task)}return(s.length>0||c)&&await q(e.paths,o),{state:o,tasks:s}})}function sk(e,t){if(Nt(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=Ue(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Yi(e){let t=ss(e);if(t===e.integration.headCommit)return e;try{I(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=Ue(e);return r.integration.headCommit=t,ot(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Xi(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=ss(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return sk(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function Wh(e,t){let r=Bt.normalize(Bt.resolve(e)),i=Bt.normalize(Bt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function T0(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 $0(e){let t=T0(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 ls(e){try{let t=await Z({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return $0(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ta(e){return $("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 j0(e){let t=gr(e.projectRoot);t.some(i=>Wh(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Bt.resolve(n)))]){let n=await Oe(i);n&&r.push({projectRoot:i,paths:await ei(i,n.native.artifact_root),parent:Wh(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function O0(e,t){let r=Bt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await yt(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function H0(e,t){let r;try{r=await I0.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=Bt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await yt(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function D0(e,t,r){let i=Bt.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Bt.sep}`))return null;let n=i.split(Bt.sep).join("/");try{let a=(0,lk.parseDocument)(I(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:B(a.toJS({mapAsMap:!1}))}catch{return null}}function B0(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 ck(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Le(e){let t=Bt.join(e.paths.changesDir,e.state.name),r=await ls(t),i=null,n;try{n=await Je({changeDir:t,validation:bt(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 D(e.paths,e.state.name,{diagnostics:!0});if(g){let w=bl(g);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(N=>({...N,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=ta({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===ti){let g=await D(e.paths,e.state.name,{diagnostics:!0});if(!g){let y=e.state.workspace.change_branch??e.state.workspace.target_branch;if(y){let E=await cs({paths:e.paths,parent:e.state.name,targetBranch:y,contract:n.contract});E&&(g=E,await q(e.paths,E))}}if(g){let y=bl(g);return e.state.children_contract_hash!==a||n.drift?{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(E=>({...E,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&y.confirmed}}let w=new Map(n.contract.children.map(y=>[y.name,y])),N=n.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:s&&y.depends_on.every(E=>n.contract.children.filter(({name:b})=>b!==y.name).every(({name:b})=>b!==E))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let y of N){if(y.status!=="ready")continue;w.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:N,readyChildren:N.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let c=await j0(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,p=new Map;for(let g of c){let w=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await H0(g,l)){let y={...N,source:g,committedState:D0(g,N.file,w)};u.set(N.state.name,[...u.get(N.state.name)??[],y])}for(let N of l){let y=await O0(g,N);y&&p.set(N,[...p.get(N)??[],{source:g,state:y}])}}let d=new Map;for(let g of n.contract.children){let w=(u.get(g.name)??[]).find(({source:E,committedState:b})=>E.parent&&b?.name===g.name&&ck(b,o));if(w){d.set(g.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let N=u.get(g.name)?.[0];if(N){d.set(g.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=p.get(g.name)??[];y.length>1?d.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):y[0]&&d.set(g.name,B0(y[0].state,y[0].source,o))}let f=new Map(n.contract.children.map(g=>[g.name,g])),h=new Map,m=g=>{let w=h.get(g);if(w)return w;let N=f.get(g),E=N.depends_on.map(m).every(({status:P})=>P==="done"),b=d.get(g),x=b?.kind==="active"&&E?N.depends_on.filter(P=>!(u.get(P)??[]).some(({source:_,committedState:j})=>Wh(_.projectRoot,b.projectRoot)&&j?.name===P&&ck(j,o))):[],k,S=b?.message??null;b?.kind==="done"?(k=E?"done":"blocked",E||(S=`Native child ${g} was merged before its dependencies`)):b?.kind==="active"?(k=E&&x.length===0?"active":"blocked",E?x.length>0&&(S=`Native child ${g} does not include merged dependencies: ${x.join(", ")}`):S=`Native child ${g} started before its dependencies merged`):b?.kind==="blocked"?k="blocked":(k=s&&E?"ready":"pending",s||(S="Parent Shape confirmation is required"));let C={name:g,summary:N.summary,dependsOn:[...N.depends_on],covers:[...N.covers],status:k,phase:b?.phase??null,projectRoot:b?.projectRoot??null,message:S};return h.set(g,C),C},v=n.contract.children.map(({name:g})=>m(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")}}On();Hi();function Re(e,t,r){return e.language==="zh-CN"?r:t}function L0(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:Re(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:Re(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:Re(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(Re(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(Re(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"?Re(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):Re(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} ${Re(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:Re(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:Re(e,"Accept the result","接受结果"),agentInstruction:Re(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)>=Nr)??!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(Re(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(Re(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 F0(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 q0(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:Re(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Re(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function fk(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Qi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function uk(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function M0(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function dk(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function V0(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function W0(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function cr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:fk({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Qi("summary","--summary"),M0(e.name,e.flag)]}}function pk(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:Re(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function z0(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function Nu(e){return[cr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),cr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function G0(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 Y(e,t,r={}){let i=V0(t)&&e.coordination_mode===void 0,n=L0(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:[Qi("summary","--summary")],commandAlternatives:i?ol.map(s=>{let c=cr({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,dk("coordination-mode","--coordination-mode",[s])]}}):[cr({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:[Qi("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=cr({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]}}):[],cr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Nu({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:[Qi("summary","--summary")],commandAlternatives:[cr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),cr({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:[Qi("summary","--summary")],commandAlternatives:[cr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Nu({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:[Qi("summary","--summary")],commandAlternatives:Nu({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:Nu({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?fk({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:W0({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:h})=>h),acceptance_review:e.acceptance.map(({id:h})=>({id:h,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[uk()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:h})=>h==="verified");if(s){let h=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}],...h&&h.length>0?{retry_check_ids:[...h]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:h})=>h==="blocked"||h==="needs-reverify"),l=t.children.some(({status:h})=>h==="needs-reverify"),u=t.children.some(({status:h})=>h==="ready"||h==="active"),p=t.supervisorStateVersion===void 0?null:t.children.find(h=>h.status==="blocked"&&(h.builderFailureCount??0)>=Nr)??null,d=p===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:p.name,stateVersion:t.supervisorStateVersion},description:Re(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},f=c&&!l&&!u&&d===null;return{...a,disposition:f?"blocked":"continue",action:"advance-children",commandArgs:f?null:d!==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?[]:d!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:f?[]:d!==null?[d]:[Qi("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=uk();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} ${Re(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:G0([{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=pk(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(p=>z0(p))?{...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:pk(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:[dk("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...q0(e)],userCommunication:F0(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[cr({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")}}We();Ao();pe();import{createHash as gS,randomUUID as wS}from"node:crypto";import{promises as ur}from"node:fs";import Tr from"node:os";import O from"node:path";We();br();ne();import{createHash as J0}from"node:crypto";import ku from"node:path";var hk=".comet/runtime/native/runner-input-artifacts.json",mk=256,vk=8*1024*1024;function gk(e){return J0("sha256").update(e).digest("hex")}function Zi(e){return process.platform==="win32"?e.toLowerCase():e}function Su(e,t){let r=ku.relative(e,ku.resolve(e,t)).replaceAll("\\","/");return r&&!ku.isAbsolute(r)&&r!==".."&&!r.startsWith("../")?r:null}async function U0(e){try{let t=await nt(e,hk,262144,{label:"Native Runner input registry"}),r=JSON.parse(t.bytes.toString("utf8"));if(!Array.isArray(r)||r.length>mk)throw new Error("Invalid Native Runner input registry");return r.map(i=>{let n=i;if(!n||typeof n.path!="string"||Su(e,n.path)!==n.path||typeof n.digest!="string"||!/^[a-f0-9]{64}$/u.test(n.digest))throw new Error("Invalid Native Runner input artifact");return{path:n.path,digest:n.digest}})}catch{return[]}}function wk(e){try{return new Set(I(e,["ls-files","-z"]).split("\0").filter(Boolean).map(Zi))}catch{return null}}async function yk(e){let t=await U0(e);if(!t.length)return[];let r=wk(e);if(!r)return[];let i=[];for(let n of t)if(!r.has(Zi(n.path)))try{let a=await nt(e,n.path,vk,{label:"Native Runner input artifact"}),o=Su(e,a.realPath);o&&!r.has(Zi(o))&&gk(a.bytes)===n.digest&&i.push({path:o,digest:n.digest})}catch{}return i}async function zh(e){return new Set((await yk(e)).map(t=>t.path))}async function bk(e){let t=Su(e.paths.projectRoot,e.file);if(!t)return;let r=wk(e.paths.projectRoot);if(!r||r.has(Zi(t)))return;let i=await nt(e.paths.projectRoot,t,vk,{label:"Native Runner input artifact"});e.validateContent(i.bytes.toString("utf8"));let n=Su(e.paths.projectRoot,i.realPath);if(!n||r.has(Zi(n)))return;let a=(await yk(e.paths.projectRoot)).filter(o=>Zi(o.path)!==Zi(n));if(a.length>=mk)throw new Error("Too many retained Native Runner input files; remove unused protocol files before continuing");await he(ku.join(e.paths.projectRoot,...hk.split("/")),[...a,{path:n,digest:gk(i.bytes)}],{containedRoot:e.paths.runtimeDir})}Mn();go();at();ni();ji();So();import{randomUUID as K0}from"node:crypto";var Gh=3,Jh=2;function Fe(e){return e.state_version+1}function Y0(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function Nk(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Uh(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function X0(e){return(e??[]).map(t=>({name:J(t.name),result:t.result,note:t.note?J(t.note):null}))}function di(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:J(e.summary),completed_at:e.completedAt}}function kk(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,phase:"build",status:"active",state_version:Fe(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Sk(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,status:"await-user",state_version:Fe(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Ek(e){let t=B(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Hy(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(r.review){if(r.review.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}let i=Y0(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=r.acceptanceReview===void 0?void 0:$n(r.acceptanceReview);jn(t.acceptance,n);let a=Nk(t.acceptance),o=(r.now??new Date).toISOString();return B({...t,phase:"verify",state_version:Fe(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??K0(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:J(r.summary),addressed_acceptance_ids:i,acceptance_review:n,checks:X0(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>J(s)),known_limits_truncated:!1,review:r.review?{status:"passed",summary:J(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef}:null,submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function xk(e){let t=B(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt requires a current Builder candidate");return B({...t,state_version:Fe(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function Q0(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function Z0(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Se?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:J(e.response.result.summary),risks:e.response.result.risks.map(t=>J(t)),risks_truncated:!1,completed_at:e.completedAt}}function Rk(e){let t=B(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=Uh(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=Dy({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,knownAcceptanceIds:t.acceptance.map(({id:v})=>v),previouslyPassedAcceptanceIds:t.acceptance.filter(({result:v})=>v==="passed").map(({id:v})=>v),requiredChecksPassed:e.checks.every(({status:v})=>v==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(v=>[v.id,v])),o=t.acceptance.map(v=>{let g=a.get(v.id);return g?{...v,result:g.result,reason:J(g.reason)}:v}),s=o.filter(({result:v})=>v==="failed"||v==="blocked").map(({id:v})=>v),c=Z0({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){let v=ke({...t,acceptance:o,verification:c},di({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),g=t.builder_handoff.identity_provider===Se;return{response:i,state:B({...v,phase:g?"verify":"archive",status:g?"await-user":"active",state_version:Fe(t),verification_result:"pass",verification_report:"verification.md",blockers:g?[{owner:"user",reason:J("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:g?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:g?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let v=ke({...t,acceptance:o,verification:c},di({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...v,status:"await-user",state_version:Fe(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:J(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,u=Q0(t,s),p=l>=e.maxVerifyFailures,d=u>=3,f=p||d,h=d?"stalled":p?"budget":void 0,m=ke({...t,acceptance:o,verification:c},di({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...m,phase:f?"verify":"build",status:f?"await-user":"active",state_version:Fe(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:f?[{owner:"user",reason:J(h==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:u>=2?[{owner:"builder",reason:J("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:f?"await-user":"repairing",iteration:f?t.loop.iteration:t.loop.iteration+1,attempt:f?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:u,...h===void 0?{}:{stop_reason:h},execution_failure_count:0,previous_unresolved_ids:s,next_action:f?"await-user":"repair-failed-acceptance"}})}}function Ck(e){let t=B(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Se||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return B({...t,phase:"archive",status:"active",state_version:Fe(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function Pk(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Se||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=Uh(t),n=ke(t,di({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return B({...n,status:"await-user",state_version:Fe(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:J(e.summary),risks:[J("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:J("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function _k(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=J(e.summary),n=ke(t,di({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return B({...n,phase:"archive",status:"active",state_version:Fe(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:J(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function Ak(e,t){let r=B(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=ke(r,di({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return B({...i,status:"active",state_version:Fe(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Ik(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=Gh,a=ke(t,di({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return B({...a,status:n?"blocked":"active",state_version:Fe(t),blockers:n?[{owner:"runtime",reason:J(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Tk(e){let t=B(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=Uh(t),a=t.acceptance.some(({result:o})=>o==="passed");return B({...t,status:"active",state_version:Fe(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function pi(e){let t=B(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,i=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,n=r!==void 0&&i>=r.maxVerifyFailures,a=(e.now??new Date).toISOString(),o=ke(t,di({state:t,outcome:"recovery",summary:e.reason,completedAt:a})),s=new Set(t.loop.previous_unresolved_ids),c=s.size===0?Nk(t.acceptance):t.acceptance.map(l=>s.has(l.id)?{...l,result:"pending",reason:null}:l);return n?B({...o,phase:"verify",status:"await-user",state_version:Fe(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:J(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:i,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):B({...o,phase:"build",status:"active",state_version:Fe(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:c,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:i,stop_reason:void 0,next_action:"submit-builder-candidate"}})}ne();On();import{promises as $k}from"node:fs";import eO from"node:os";import ps from"node:path";function us(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ds(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function qe(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function ra(e,t){return e===null?null:qe(e,t)}function ia(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 tO(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 rO(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function na(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Kh(e,t){if(e===null)return null;let r=qe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function iO(e,t){let r=qe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Yh(e,t){let r=qe(e,t);if(!ps.isAbsolute(r))throw new Error(`${t} must be absolute`);return ps.resolve(r)}function nO(e,t){let r=`Native local checks[${t}]`,i=us(e,r);if(ds(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,p)=>qe(u,`${r}.argv[${p}]`,!0)),a=na(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Kh(i.startedAt,`${r}.startedAt`),s=Kh(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=ia(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=us(i.activeProcess,`${r}.activeProcess`),p=na(u.status,["starting","running"],`${r}.activeProcess.status`);if(ds(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),p==="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:ia(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:qe(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:qe(i.id,`${r}.id`),name:qe(i.name,`${r}.name`),operationId:qe(i.operationId,`${r}.operationId`),status:a,repeatable:rO(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:ia(i.executionCount,`${r}.executionCount`),argv:n,cwd:Yh(i.cwd,`${r}.cwd`),exitCode:tO(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:qe(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:na(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:qe(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function Xh(e){let t="Native local execution state",r=us(e,t);if(ds(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==wo)throw new Error(`Native local execution schema must be ${wo}`);let i=us(r.workspace,"Native local workspace");ds(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=us(r.execution,"Native local execution");ds(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Kh(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:qe(o.operationId,"Native local execution.operationId"),stage:na(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:na(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ra(o.executionId,"Native local execution.executionId"),status:na(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ia(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:iO(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:ia(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:qe(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(nO);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:wo,change:qe(r.change,"Native local change"),basedOnStateVersion:ia(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:ra(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:ra(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:ra(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:ra(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Yh(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Yh(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ra(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:qe(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function ae(e){return Xh({schema:wo,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,candidateId:e.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:ps.resolve(e.projectRoot),worktreeRoot:ps.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:eO.hostname()},execution:null,checks:[]})}async function Ce(e){let t;try{t=await $k.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 Xh(r)}function Qh(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 jk(e,t){if(Qh(e,t)!==void 0)return t.execution.verifierStartedAt!=null||t.execution.requestCheckRounds>0?"confirmed":"unconfirmed"}async function M(e,t,r={}){let i=Xh(t);await $k.mkdir(ps.dirname(e),{recursive:!0}),await he(e,i,r)}async function Eu(e){let t=null,r=null;try{t=await Ce(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=ae(e);return await M(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}ve();ni();ie();async function Zh(e,t,r){if(!Number.isInteger(t)||t<1)throw new Error("Concurrency must be a positive integer");let i=new Array(e.length),n=0,a=async()=>{for(;n<e.length;){let o=n;n+=1,i[o]=await r(e[o],o)}};return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>a())),i}import{promises as Ok}from"node:fs";import xu from"node:path";We();at();ie();var em=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Hk="comet-state.yaml",Dk="state.json";function le(e,t){if(!em.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=xu.join(e.changesDir,t);if(!Ee(e.changesDir,r))throw new Error("Native change path escaped");return r}function dt(e,t){return xu.join(le(e,t),Hk)}function L(e,t){return xu.join(me(e,t),Dk)}async function aa(e,t){try{let r=await Ok.readFile(dt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function ge(e){return ty(e)}function Ru(e,t){let r=oe(t);if(!r.isGitWorktree||r.currentBranch===null||wr(t,r.currentBranch)===null)return null;if(!Lc(t))throw new Error("Native Supervisor Git binding requires a clean current working directory; commit or stash pending changes, then rerun the latest continuation");return{...e,change_branch:r.currentBranch,target_branch:r.currentBranch}}async function H(e,t){return yt(dt(e,t))}async function fe(e){let t=await Bn({file:dt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=xu.join(le(e.paths,t.name),"verification.md");await G(e.paths.nativeRoot,r),await Ok.rm(r,{force:!0})}return t}async function tm(e){let t=await H(e.paths,e.name),r=L(e.paths,e.name);try{let i=await Ce(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"}}}import{promises as ju}from"node:fs";import nn from"node:path";function am(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var rn=am();function zk(e){rn=e}var en={exec:()=>null};function oa(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 V(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 aO=((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:oa(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:oa(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:oa(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:oa(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:oa(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:oa(e=>new RegExp(`^ {0,${e}}>`))},oO=/^(?:[ \t]*(?:\n|$))+/,sO=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,cO=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ms=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,lO=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,om=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Gk=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Jk=V(Gk).replace(/bull/g,om).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(),uO=V(Gk).replace(/bull/g,om).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(),sm=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,dO=/^[^\n]+/,cm=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,pO=V(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",cm).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),fO=V(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,om).getRegex(),Iu="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",lm=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,hO=V("^ {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",lm).replace("tag",Iu).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Uk=e=>V(sm).replace("hr",ms).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",Iu).getRegex(),mO=Uk(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),vO=Uk(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),gO=V(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",vO).getRegex(),um={blockquote:gO,code:sO,def:pO,fences:cO,heading:lO,hr:ms,html:hO,lheading:Jk,list:fO,newline:oO,paragraph:mO,table:en,text:dO},Bk=V("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ms).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",Iu).getRegex(),wO={...um,lheading:uO,table:Bk,paragraph:V(sm).replace("hr",ms).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Bk).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",Iu).getRegex()},yO={...um,html:V(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",lm).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:en,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:V(sm).replace("hr",ms).replace("heading",` *#{1,6} *[^
|
|
237
|
+
]`).replace("lheading",Jk).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},bO=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,NO=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Kk=/^( {2,}|\\)\n(?!\s*$)/,kO=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ar=/[\p{P}\p{S}]/u,sa=/[\s\p{P}\p{S}]/u,vs=/[^\s\p{P}\p{S}]/u,SO=V(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,sa).getRegex(),EO=/[\p{Pi}\p{Ps}"']/u,Yk=/(?!~)[\p{P}\p{S}]/u,xO=/(?!~)[\s\p{P}\p{S}]/u,RO=/(?:[^\s\p{P}\p{S}]|~)/u,CO=V(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",aO?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Xk=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,PO=V(Xk,"u").replace(/punct/g,Ar).getRegex(),_O=V(Xk,"u").replace(/punct/g,Yk).getRegex(),AO=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,IO=V(AO,"u").replace(/openQuote/g,EO).replace(/punct/g,Ar).getRegex(),Qk="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",TO=V(Qk,"gu").replace(/notPunctSpace/g,vs).replace(/punctSpace/g,sa).replace(/punct/g,Ar).getRegex(),$O=V(Qk,"gu").replace(/notPunctSpace/g,RO).replace(/punctSpace/g,xO).replace(/punct/g,Yk).getRegex(),jO="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",OO=V(jO,"gu").replace(/notPunctSpace/g,vs).replace(/punctSpace/g,sa).replace(/punct/g,Ar).getRegex(),HO=V("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,vs).replace(/punctSpace/g,sa).replace(/punct/g,Ar).getRegex(),DO="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",BO=V(DO,"gu").replace(/notPunctSpace/g,vs).replace(/punctSpace/g,sa).replace(/punct/g,Ar).getRegex(),LO=V(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Ar).getRegex(),FO="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",qO=V(FO,"gu").replace(/notPunctSpace/g,vs).replace(/punctSpace/g,sa).replace(/punct/g,Ar).getRegex(),MO=V(/\\(punct)/,"gu").replace(/punct/g,Ar).getRegex(),VO=V(/^<(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(),WO=V(lm).replace("(?:-->|$)","-->").getRegex(),zO=V("^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",WO).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Pu=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,GO=V(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Pu).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Zk=V(/^!?\[(label)\]\[(ref)\]/).replace("label",Pu).replace("ref",cm).getRegex(),eS=V(/^!?\[(ref)\](?:\[\])?/).replace("ref",cm).getRegex(),JO=V("reflink|nolink(?!\\()","g").replace("reflink",Zk).replace("nolink",eS).getRegex(),Lk=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,dm={_backpedal:en,anyPunctuation:MO,autolink:VO,blockSkip:CO,br:Kk,code:NO,del:en,delLDelim:en,delRDelim:en,emStrongLDelim:PO,emStrongRDelimAst:TO,emStrongRDelimUnd:HO,escape:bO,link:GO,nolink:eS,punctuation:SO,reflink:Zk,reflinkSearch:JO,tag:zO,text:kO,url:en},UO={...dm,emStrongLDelim:IO,emStrongRDelimAst:OO,emStrongRDelimUnd:BO,link:V(/^!?\[(label)\]\((.*?)\)/).replace("label",Pu).getRegex(),reflink:V(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Pu).getRegex()},rm={...dm,emStrongRDelimAst:$O,emStrongLDelim:_O,delLDelim:LO,delRDelim:qO,url:V(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Lk).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:V(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Lk).getRegex()},KO={...rm,br:V(Kk).replace("{2,}","*").getRegex(),text:V(rm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Cu={normal:um,gfm:wO,pedantic:yO},fs={normal:dm,gfm:rm,breaks:KO,pedantic:UO},YO={"&":"&","<":"<",">":">",'"':""","'":"'"},Fk=e=>YO[e];function lr(e,t){if(t){if($e.escapeTest.test(e))return e.replace($e.escapeReplace,Fk)}else if($e.escapeTestNoEncode.test(e))return e.replace($e.escapeReplaceNoEncode,Fk);return e}function qk(e){try{e=encodeURI(e).replace($e.percentDecode,"%")}catch{return null}return e}function Mk(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 fi(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 Vk(e){let t=e.split(`
|
|
234
238
|
`),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(`
|
|
235
|
-
`)}function
|
|
239
|
+
`)}function XO(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 QO(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 Wk(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 p=i.inlineTokens(s),d=i.state.linkEmitted;if(i.state.linkEmitted=l,i.state.inLink=!1,!c){if(d){i.state.inRawBlock=u;return}i.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:a,title:o,text:s,tokens:p}}function ZO(e,t,r){let i=e.match(r.other.indentCodeCompensation);if(i===null)return t;let n=i[1];return t.split(`
|
|
236
240
|
`).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(`
|
|
237
|
-
`)}var
|
|
238
|
-
`),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:
|
|
239
|
-
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=
|
|
241
|
+
`)}var _u=class{options;rules;lexer;constructor(e){this.options=e||rn}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]:Vk(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=ZO(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=fi(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:fi(t[0],`
|
|
242
|
+
`),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:fi(t[0],`
|
|
243
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=fi(t[0],`
|
|
240
244
|
`).split(`
|
|
241
245
|
`),i="",n="",a=[];for(;r.length>0;){let o=!1,s=[],c;for(c=0;c<r.length;c++)if(this.rules.other.blockquoteStart.test(r[c]))s.push(r[c]),o=!0;else if(!o)s.push(r[c]);else break;r=r.slice(c);let l=s.join(`
|
|
242
246
|
`),u=l.replace(this.rules.other.blockquoteSetextReplace,`
|
|
243
247
|
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
|
|
244
248
|
${l}`:l,n=n?`${n}
|
|
245
|
-
${u}`:u;let
|
|
246
|
-
`),m=
|
|
247
|
-
`+
|
|
248
|
-
${
|
|
249
|
+
${u}`:u;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,a,!0),this.lexer.state.top=p,r.length===0)break;let d=a.at(-1);if(d?.type==="code")break;if(d?.type==="blockquote"){let f=d,h=r.join(`
|
|
250
|
+
`),m=f.raw+`
|
|
251
|
+
`+h.replace(this.rules.other.blockquoteSetextReplace2,""),v=this.blockquote(m);a[a.length-1]=v,i=`${i}
|
|
252
|
+
${h}`,n=n.substring(0,n.length-f.text.length)+v.text;break}else if(d?.type==="list"){let f=d,h=f.raw+`
|
|
249
253
|
`+r.join(`
|
|
250
|
-
`),m=this.list(
|
|
251
|
-
`);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
|
|
252
|
-
`,1)[0],t[1].length),
|
|
253
|
-
`,1)[0],
|
|
254
|
-
`,e=e.substring(
|
|
255
|
-
`,1)[0],b;if(
|
|
256
|
-
`+b.slice(
|
|
257
|
-
`+
|
|
258
|
-
`,e=e.substring(E.length+1),
|
|
259
|
-
`),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=
|
|
260
|
-
`):[],a={type:"table",raw:
|
|
261
|
-
`),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(
|
|
254
|
+
`),m=this.list(h);a[a.length-1]=m,i=i.substring(0,i.length-d.raw.length)+m.raw,n=n.substring(0,n.length-f.raw.length)+m.raw,r=h.substring(a.at(-1).raw.length).split(`
|
|
255
|
+
`);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 p=QO(t[2].split(`
|
|
256
|
+
`,1)[0],t[1].length),d=e.split(`
|
|
257
|
+
`,1)[0],f=!p.trim(),h=0;if(this.options.pedantic?(h=2,u=p.trimStart()):f?h=t[1].length+1:(h=p.search(this.rules.other.nonSpaceChar),h=h>4?1:h,u=p.slice(h),h+=t[1].length),f&&this.rules.other.blankLine.test(d)&&(l+=d+`
|
|
258
|
+
`,e=e.substring(d.length+1),c=!0),!c){let m=this.rules.other.nextBulletRegex(h),v=this.rules.other.hrRegex(h),g=this.rules.other.fencesBeginRegex(h),w=this.rules.other.headingBeginRegex(h),N=this.rules.other.htmlBeginRegex(h),y=this.rules.other.blockquoteBeginRegex(h);for(;e;){let E=e.split(`
|
|
259
|
+
`,1)[0],b;if(d=E,this.options.pedantic?(d=d.replace(this.rules.other.listReplaceNesting," "),b=d):b=d.replace(this.rules.other.tabCharGlobal," "),g.test(d)||w.test(d)||N.test(d)||y.test(d)||m.test(d)||v.test(d))break;if(b.search(this.rules.other.nonSpaceChar)>=h||!d.trim())u+=`
|
|
260
|
+
`+b.slice(h);else{if(f||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||g.test(p)||w.test(p)||v.test(p))break;u+=`
|
|
261
|
+
`+d}f=!d.trim(),l+=E+`
|
|
262
|
+
`,e=e.substring(E.length+1),p=b.slice(h)}}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(p=>p.type==="space"),u=l.length>0&&l.some(p=>this.rules.other.anyLine.test(p.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 p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let p={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=p.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=p.raw+c.tokens[0].raw,c.tokens[0].text=p.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(p)):c.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):c.tokens.unshift(p)}}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=Vk(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:fi(t[0],`
|
|
263
|
+
`),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=Mk(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
264
|
+
`):[],a={type:"table",raw:fi(t[0],`
|
|
265
|
+
`),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(Mk(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:fi(t[0],`
|
|
262
266
|
`),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)===`
|
|
263
|
-
`?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=
|
|
267
|
+
`?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=fi(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=XO(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)),Wk(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 Wk(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,p=l==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+n);(i=p.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 d=[...i[0]][0].length,f=e.slice(0,n+i.index+d+o);if(Math.min(n,o)%2){let m=f.slice(1,-1);return{type:"em",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}let h=f.slice(2,-2);return{type:"strong",raw:f,text:h,tokens:this.lexer.inlineTokens(h)}}}}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),p=u.slice(n,-n);return{type:"del",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}}}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}}}},pt=class im{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||rn,this.options.tokenizer=this.options.tokenizer||new _u,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:Cu.normal,inline:fs.normal};this.options.pedantic?(r.block=Cu.pedantic,r.inline=fs.pedantic):this.options.gfm&&(r.block=Cu.gfm,this.options.breaks?r.inline=fs.breaks:r.inline=fs.gfm),this.tokenizer.rules=r}static get rules(){return{block:Cu,inline:fs}}static lex(t,r){return new im(r).lex(t)}static lexInline(t,r){return new im(r).inlineTokens(t)}lex(t){t=t.replace($e.carriageReturn,`
|
|
264
268
|
`),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+=`
|
|
265
269
|
`: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(`
|
|
266
270
|
`)?"":`
|
|
@@ -274,7 +278,7 @@ ${f}`,n=n.substring(0,n.length-h.text.length)+v.text;break}else if(p?.type==="li
|
|
|
274
278
|
`+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(`
|
|
275
279
|
`)?"":`
|
|
276
280
|
`)+a.raw,s.text+=`
|
|
277
|
-
`+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
|
|
281
|
+
`+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 p=l.slice(1,u-1);if(this.linkInText(p))return"["+p.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),p;this.options.extensions.startInline.forEach(d=>{p=d.call({lexer:this},u),typeof p=="number"&&p>=0&&(l=Math.min(l,p))}),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)}},Au=class{options;parser;constructor(e){this.options=e||rn}space(e){return""}code({text:e,lang:t,escaped:r}){let i=(t||"").match($e.notSpaceStart)?.[0],n=e.replace($e.endingNewline,"")+`
|
|
278
282
|
`;return i?'<pre><code class="language-'+lr(i)+'">'+(r?n:lr(n,!0))+`</code></pre>
|
|
279
283
|
`:"<pre><code>"+(r?n:lr(n,!0))+`</code></pre>
|
|
280
284
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
@@ -292,17 +296,20 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
292
296
|
`}tablerow({text:e}){return`<tr>
|
|
293
297
|
${e}</tr>
|
|
294
298
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
|
|
295
|
-
`}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>${lr(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=
|
|
296
|
-
Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+lr(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},
|
|
297
|
-
`).trim())};for(let
|
|
298
|
-
`).trim()}function
|
|
299
|
-
`)
|
|
300
|
-
`)
|
|
301
|
-
`),s=
|
|
302
|
-
`):""
|
|
303
|
-
`),
|
|
304
|
-
`),
|
|
305
|
-
`),
|
|
299
|
+
`}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>${lr(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=qk(e);if(n===null)return i;e=n;let a='<a href="'+e+'"';return t&&(a+=' title="'+lr(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=qk(e);if(n===null)return lr(r);e=n;let a=`<img src="${e}" alt="${lr(r)}"`;return t&&(a+=` title="${lr(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:lr(e.text)}},pm=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}},Lt=class nm{options;renderer;textRenderer;constructor(t){this.options=t||rn,this.options.renderer=this.options.renderer||new Au,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new pm}static parse(t,r){return new nm(r).parse(t)}static parseInline(t,r){return new nm(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}},hs=class{options;block;constructor(e){this.options=e||rn}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?pt.lex:pt.lexInline}provideParser(e=this.block){return e?Lt.parse:Lt.parseInline}},eH=class{defaults=am();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Lt;Renderer=Au;TextRenderer=pm;Lexer=pt;Tokenizer=_u;Hooks=hs;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 Au(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 _u(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 hs;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];hs.passThroughHooks.has(a)?n[o]=l=>{if(this.defaults.async&&hs.passThroughHooksRespectAsync.has(a))return(async()=>{let p=await s.call(n,l);return c.call(n,p)})();let u=s.call(n,l);return c.call(n,u)}:n[o]=(...l)=>{if(this.defaults.async)return(async()=>{let p=await s.apply(n,l);return p===!1&&(p=await c.apply(n,l)),p})();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 pt.lex(e,t??this.defaults)}parser(e,t){return Lt.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?pt.lex:pt.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?Lt.parse:Lt.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?pt.lex:pt.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?Lt.parse:Lt.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+=`
|
|
300
|
+
Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+lr(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},tn=new eH;function re(e,t){return tn.parse(e,t)}re.options=re.setOptions=function(e){return tn.setOptions(e),re.defaults=tn.defaults,zk(re.defaults),re};re.getDefaults=am;re.defaults=rn;function tH(...e){return tn.use(...e),re.defaults=tn.defaults,zk(re.defaults),re}re.use=tH;re.walkTokens=function(e,t){return tn.walkTokens(e,t)};re.parseInline=tn.parseInline;re.Parser=Lt;re.parser=Lt.parse;re.Renderer=Au;re.TextRenderer=pm;re.Lexer=pt;re.lexer=pt.lex;re.Tokenizer=_u;re.Hooks=hs;re.parse=re;var Wz=re.options,zz=re.setOptions,Gz=re.walkTokens,Jz=re.parseInline;var Uz=Lt.parse,Kz=pt.lex;ne();Wi();var hm=hr(Gt(),1);import ys from"path";rt();ne();Wi();gt();ve();ie();Zt();Jo();ve();ie();Pn();Qr();var sH=hr(Gt(),1);Pn();Qr();br();br();Cn();cf();Pn();br();var g2=4*1024*1024;import{AsyncLocalStorage as cH}from"node:async_hooks";var lH=new cH;function uH(){let e=lH.getStore();return e?.active?e:null}function dH(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function tS(e,t){return(...r)=>{let i=uH();if(i===null)return t(...r);let n=dH(`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 S2=tS("hookWritePolicy",async e=>(await Xp(e))?.hook??{allow_paths:[]});lo();var pH=16*1024;of();to();var SG=Number.MAX_SAFE_INTEGER;ne();Jt();var HG={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};import ca from"node:path";ne();rt();ve();ie();var gs=/^[a-f0-9]{64}$/u,iS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,yH=16*1024,XG=process.platform;function bH(e,t){let r=ca.relative(e,t);return ca.isAbsolute(r)||r===".."||r.startsWith(`..${ca.sep}`)?null:r.replaceAll("\\","/")||"."}function nS(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function aS(e,t){if(e.length===0||nS(e)||e.includes("\\")||ca.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=ca.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function NH(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 fm(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||nS(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function kH(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(fm(e.changeBranch,"Native workspace change branch"),fm(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 SH(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"||!iS.test(t.baseCommit)||typeof t.targetCommit!="string"||!iS.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");fm(t.targetBranch,"Native workspace Git target branch")}function EH(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"||!gs.test(String(t.projectRootId))||!gs.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");NH(t.capturedAt),aS(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&&!gs.test(String(t.projectRootPathId))||a&&!gs.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!gs.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&SH(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(kH(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 xH(e,t){return ca.join(vt(e,t),"workspace.json")}function RH(e,t){let r=xH(e,t),i=Ge(e,r),n=bH(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:aS(n,"Native workspace file ref")}}async function CH(e,t){try{let r=RH(e,t),i=await Z({root:r.root,ref:r.ref,maxBytes:yH});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ws(e,t){let r=await CH(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(EH(r),r)}Bo();jl();jl();var Tu=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"},bs=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"},$u=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"},EJ=Hl("en");function Ft(e,t){Mo(t);let r=ys.join(e.changesDir,t);if(!Ee(e.changesDir,r))throw new Error("Native change path escaped");return r}async function IH(e,t=ys.dirname(e)){let r=ys.relative(t,e).split(ys.sep).join("/"),i=await Z({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,hm.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 oS(e,t){let r=ys.join(Ft(e,t),xr);await G(e.nativeRoot,r);let i=Yf(await IH(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}rt();rr();ie();var mm=["outcome","scope","nonGoals","acceptanceExamples"],sS=[...mm,"constraints","decisions","openQuestions","verificationExpectations"];var $H=new Set(["nonGoals","decisions","openQuestions"]),la=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change},jH={maxFileBytes:Vp};function OH(e){let t=new Map,r=null,i=[],n={marker:null,length:0},a=()=>{r!==null&&t.set(r,i.join(`
|
|
301
|
+
`).trim())};for(let o of e.split(/\r?\n/u)){let c=ks(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}function vm(e){return{valid:e.length===0,findings:e}}function gm(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 wm(e){return gm(e).trim()}function Ns(e){let t=wm(e).split(/\r?\n/u),r=[],i={marker:null,length:0};for(let n of t)ks(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(`
|
|
302
|
+
`).trim()}function HH(e){let t=Ns(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 ym(e){let t=Ns(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 cS(e,t){let r=[];return Ns(e).length===0?r.push({code:"spec-document-empty",message:`Native target Spec is empty: ${t}. Add the complete target requirements or use an explicit no-product-behavior exemption in brief.md.`,path:t}):ym(e)&&r.push({code:"spec-document-placeholder",message:`Native target Spec contains only template placeholder content: ${t}. Replace it with complete target requirements.`,path:t}),vm(r)}function bm(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(ks(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 ks(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 DH(e){let t=wm(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(ks(a,r)!==null||r.marker!==null)continue;let o=/^##\s+(.+)$/u.exec(a);if(o!==null){if(i===-1){jb(o[1]??"")&&(i=n+1);continue}return t.slice(i,n).join(`
|
|
303
|
+
`)}}return i===-1?null:t.slice(i).join(`
|
|
304
|
+
`)}function BH(e){let t=new Map,r=null,i=[],n={marker:null,length:0},a=()=>{r!==null&&t.set(r,i.join(`
|
|
305
|
+
`).trim())};for(let o of wm(e).split(/\r?\n/u)){if(ks(o,n)!==null){r!==null&&i.push(o);continue}let s=n.marker===null?/^###\s+(.+)$/u.exec(o):null;s!==null?(a(),r=Ob(s[1]??""),i=[]):r!==null&&i.push(o)}return a(),t}function LH(e,t){let r=[],i=DH(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=BH(i),a=[];for(let o of Qf){let s=n.get(o);(s===void 0||Ns(s).length===0||ym(s))&&a.push($b(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 Nm(e,t,r={}){let i=[],n;try{n=(await Z({root:e,ref:t,maxBytes:jH.maxFileBytes})).text}catch(s){return vm([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,c]of OH(n))a.set(Ol(s)??s,c);for(let s of r.compact?mm:sS)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?sS.filter(s=>!r.compact||a.has(s)):mm;for(let s of o){let c=a.get(s)??"";Ns(c).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):ym(c)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!$H.has(s)&&HH(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(...LH(a.get("scope")??"",t)),bm(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),vm(i)}rt();pe();ve();Fl();Gf();at();ni();ne();Wi();ji();import{promises as FH}from"node:fs";function qt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
306
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Ir(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function qH(e){return e.archived?Xe(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Xe(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Xe(e.language,"Verification passed; ready to archive","验收通过,可归档"):Xe(e.language,"Verification passed","验收通过")}function MH(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Xe(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?qH(e):e.verification_result==="blocked"?Xe(t,"Blocked","已阻塞"):e.verification_result==="fail"?Xe(t,"Failed","未通过"):Xe(t,"Pending","待处理")}function VH(e){if(e.verification?.assurance==="semantic-verification-unavailable")return Xe(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return Xe(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return Xe(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Se?Se:"host-attested"),r=t===Se&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function WH(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=d=>Zf(r,d),n=(d,f)=>Xe(r,d,f),a=e.acceptance.map(d=>`| ${Ir(d.id)} | ${Ir(d.result)} | ${Ir(d.source)} | ${Ir(d.text)} | ${Ir(qt(d.reason))} |`).join(`
|
|
307
|
+
`),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let f=d.argv_display.map(qt).join(" ");return`| ${Ir(qt(d.name))} | ${Ir(f||"—")} | ${Ir(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
|
|
308
|
+
`),s=e.builder_handoff?[`### ${n("Builder-reported evidence","Builder 报告的证据")}`,"",n("These are Builder reports, not Runtime check receipts or independent verification results.","以下为 Builder 报告,不等同于 Runtime 检查凭据或独立验收结果。"),"",...e.builder_handoff.checks.map(d=>`- ${qt(d.name)}: ${d.result} — ${qt(d.note)}`),...e.builder_handoff.checks_truncated?[n("Check list was truncated.","检查列表已截断。")]:[],...e.builder_handoff.known_limits.map(d=>`- ${n("Known limitation","已知限制")}: ${qt(d)}`),...e.builder_handoff.known_limits_truncated?[n("Limitations list was truncated.","限制列表已截断。")]:[]].join(`
|
|
309
|
+
`):"",c=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${qt(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
|
|
310
|
+
`),l=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${qt(d)}`).join(`
|
|
311
|
+
`),u=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${Ir(qt(d.summary))} | ${d.completed_at} |`)].join(`
|
|
312
|
+
`),p=t?.finalVerification.layers?`
|
|
306
313
|
## ${n("Supervisor evidence layers","Supervisor 分层证据")}
|
|
307
314
|
|
|
308
315
|
- ${n("Child verification","Child 验证")}: ${t.finalVerification.layers.childVerification}
|
|
@@ -318,13 +325,13 @@ generated_from_state_version: ${e.state_version}
|
|
|
318
325
|
|
|
319
326
|
## ${i("currentResult")}
|
|
320
327
|
|
|
321
|
-
- ${n("Result","结果")}: **${
|
|
322
|
-
- ${n("Verification status","验证情况")}: **${
|
|
328
|
+
- ${n("Result","结果")}: **${MH(e)}**
|
|
329
|
+
- ${n("Verification status","验证情况")}: **${VH(e)}**
|
|
323
330
|
- ${n("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
|
|
324
331
|
- ${n("Iteration","迭代")}: ${e.verification.iteration}
|
|
325
332
|
- ${n("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
|
|
326
333
|
- ${n("Completed","完成时间")}: ${e.verification.completed_at}
|
|
327
|
-
- ${n("Summary","摘要")}: ${
|
|
334
|
+
- ${n("Summary","摘要")}: ${qt(e.verification.summary)}
|
|
328
335
|
|
|
329
336
|
## ${i("acceptance")}
|
|
330
337
|
|
|
@@ -350,39 +357,39 @@ ${l}
|
|
|
350
357
|
|
|
351
358
|
${u}
|
|
352
359
|
|
|
353
|
-
${
|
|
360
|
+
${p}
|
|
354
361
|
|
|
355
362
|
${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into summary","更早的历史记录已折叠到摘要中")}: ${e.history_overflow.dropped_entries}.
|
|
356
363
|
|
|
357
364
|
`:""}## ${i("conclusion")}
|
|
358
365
|
|
|
359
|
-
${
|
|
360
|
-
`}function
|
|
366
|
+
${qt(e.verification.summary)}
|
|
367
|
+
`}function zH(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function lS(e){let t;try{t=await FH.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=zH(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function hi(e){await mt(e.file,WH(e.state,e.supervisor))}ie();Wi();ui();gt();var Sm=hr(Gt(),1);br();var LJ=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 uS=5,GH=600,zJ=256*1024,JH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,UH=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;var KH=/^[a-f0-9]{64}$/iu;function dS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mi(e,t,r=4096){if(typeof e!="string"||e.trim().length===0||e.length>r)throw new Error(`${t} must be a non-empty string within the association limit`);return e}function km(e,t){let r=mi(e,t).replaceAll("\\","/");if(r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a project-relative path`);return r}function YH(e,t){let r=mi(e,t,64).toLowerCase();if(!KH.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function XH(e,t){let r=`Capability association evidence[${t}]`,i=dS(e,r),n=Object.keys(i).filter(a=>!new Set(["source","kind","title","snippet"]).has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return{source:km(i.source,`${r}.source`),kind:mi(i.kind,`${r}.kind`,128),...i.title===void 0?{}:{title:mi(i.title,`${r}.title`)},...i.snippet===void 0?{}:{snippet:mi(i.snippet,`${r}.snippet`,GH)}}}function pS(e){let t=typeof e=="string"?(()=>{if(e.length>65536)throw new Error("Capability association exceeds the size limit");let l=(0,Sm.parseDocument)(e,{uniqueKeys:!0});if(l.errors.length>0)throw new Error(l.errors[0].message);return l.toJS({mapAsMap:!1})})():e,r=dS(t,"Capability association"),i=Object.keys(r).filter(l=>!new Set(["schema","status","workflow","capability","current_spec","current_hash","confidence","query","reason","historical_sources","evidence"]).has(l));if(i.length>0)throw new Error(`Capability association has unknown field(s): ${i.join(", ")}`);if(r.schema!=="comet.capability-association.v1")throw new Error("Unsupported capability association schema");let n=r.workflow;if(n!=="native"&&n!=="classic")throw new Error("Capability association workflow is invalid");let a=QH(mi(r.capability,"Capability association capability"),n);if(!Array.isArray(r.historical_sources))throw new Error("Capability association historical_sources must be an array");let o=r.historical_sources.map((l,u)=>km(l,`Capability association historical_sources[${u}]`));if(!Array.isArray(r.evidence)||r.evidence.length>uS)throw new Error(`Capability association evidence must contain at most ${uS} entries`);let s=r.status;if(s!=="suggested"&&s!=="explicit")throw new Error("Capability association status is invalid");let c=r.confidence;if(c!=="high"&&c!=="medium"&&c!=="low")throw new Error("Capability association confidence is invalid");return{schema:"comet.capability-association.v1",status:s,workflow:n,capability:a,current_spec:km(r.current_spec,"Capability association current_spec"),current_hash:YH(r.current_hash,"Capability association current_hash"),confidence:c,...r.query===void 0?{}:{query:mi(r.query,"Capability association query")},reason:mi(r.reason,"Capability association reason",2048),historical_sources:o,evidence:r.evidence.map(XH)}}function QH(e,t){let r=e.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),i=r.split("/"),n=t==="native"?JH:UH;if(!r||i.some(a=>!n.test(a)))throw new Error(`Invalid ${t} capability: ${e}`);return i.join("/")}at();ni();async function ua(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...ke(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await fe({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}kr();var ZH=Hl("en",{compact:!0}),fS="capability-association.yaml";function Ou(e,t=!1){if(t){let i=n=>{if(Array.isArray(n))return n.filter(a=>a?.type!=="space").map(i);if(n&&typeof n=="object"){let a=n;return Object.fromEntries(Object.entries(a).filter(([o])=>o!=="raw"&&!(o==="text"&&Array.isArray(a.tokens))).map(([o,s])=>[o,o==="text"&&a.type==="text"&&typeof s=="string"?s.replace(/[\t ]*\n[\t ]*/gu," "):i(s)]))}return n};return JSON.stringify(i(pt.lex(e.replace(/\r\n?/gu,`
|
|
361
368
|
`))))}let r=e.replace(/\r\n?/gu,`
|
|
362
369
|
`).split(`
|
|
363
370
|
`);for(;r.length>0&&r.at(-1)?.trim().length===0;)r.pop();return`${r.map(i=>i.replace(/[\t ]+$/gu,"")).join(`
|
|
364
371
|
`)}
|
|
365
|
-
`}function
|
|
372
|
+
`}function eD(e){let t=e.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/u,"").replace(/\s+/gu," ").trim();if(t.length===0||/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!:: -]*$/iu.test(t))return!0;let r=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:todo|tbd|fixme)(?:\s*[::-]|\s*$)/iu.test(r)||/^(?:fill(?:\s+this\s+in)?|placeholder)\b/iu.test(r)||/^(?:待填写|待补充)/u.test(r)?!0:/^(?:(?:todo|tbd|fixme)\b|fill(?:\s+this\s+in)?\b|placeholder\b|documentation[- ]only\b|no\s+product\s+behavior\s+change\b|待填写|待补充|仅文档|不改变产品行为|不涉及产品行为)[.!。;;::,,、 -]*$/iu.test(r)}function tD(e){let t=[],r=!1;for(let i of gm(e).split(/\r?\n/u)){if(/^\s*(?:```|~~~)/u.test(i)){r=!r;continue}!r&&!/^\s*#{1,6}\s+/u.test(i)&&t.push(i)}return t.some(i=>{let n=/(?:no\s+product\s+behavior\s+change|documentation[- ]only|不改变产品行为|不涉及产品行为|仅文档)\s*[::]\s*(.*)$/iu.exec(i);return n!==null&&!eD(n[1]??"")})}function hS(e,t){let r=e.map(({code:i,message:n,path:a})=>`- ${i}${a?` (${a})`:""}: ${n}`).join(`
|
|
366
373
|
`);return[`Native ${t.phase} document checks failed for ${t.change}.`,r,"Recovery: edit the reported formal file in the configured Native change directory, then rerun the latest continuation command. The current state and existing work are preserved; do not edit comet-state.yaml or bypass the Hook."].join(`
|
|
367
|
-
`)}async function ym(e){let t=le(e.paths,e.state.name),r=[...(await vm(t,e.state.brief,{strict:!0,compact:e.state.document_constraints_version===2})).findings],i="";try{i=(await Z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let n=e.specChanges??e.state.spec_changes,a=n.filter(({operation:l})=>l!=="remove"),o=e.state.spec_changes.filter(({operation:l})=>l!=="remove"),s=new Set(a.map(({capability:l})=>l));if(e.specChanges!==void 0)for(let l of o)s.has(l.capability)||r.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${l.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${l.capability}/spec.md`});let c=n.length>0&&n.every(({operation:l})=>l==="remove");a.length===0&&o.length===0&&!c&&!MH(i)&&r.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:e.state.brief});for(let l of a){let u=`specs/${l.capability}/spec.md`;if(l.source!==u){r.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${u}.`,path:l.source??u});continue}try{let d=(await Z({root:t,ref:u,maxBytes:null,includeHash:!1})).text;r.push(...Qk(d,u).findings)}catch(d){r.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${d.message}. Restore the complete file at ${u}.`,path:u})}}return{valid:r.length===0,findings:r}}async function ju(e){let t=await ym(e);if(!t.valid)throw new ca(nS(t.findings,{change:e.state.name,phase:e.state.phase}),t.findings,e.state.name)}function Mt(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale: the change moved on since the referenced response (current phase ${e.state.phase}, next action ${e.state.loop.next_action}, state version ${e.state.state_version}). Run comet native status ${e.state.name} --json and execute its commandAlternatives with --expected-state-version ${e.state.state_version} --expected-action ${e.state.loop.next_action}.`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}async function Ou(e){let t=le(e.paths,e.state.name),r=rn.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Tu.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Xf.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=rn.join(t,...s.split("/")),l=await Tu.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=rn.join(e.paths.specsDir,o.name,"spec.md"),d="create",p=null;try{let v=await Tu.lstat(u);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify",p=Sr((await Z({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(v){if(v.code!=="ENOENT")throw v}let h=`specs/${o.name}/${cb}`,f=rn.join(t,...h.split("/")),m={};try{let v=await Tu.lstat(f);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${h}`);let g=await Z({root:t,ref:h,maxBytes:null,includeHash:!1}),w=Ho(g.text);if(w.capability!==o.name)throw new Error(`Native delta capability ${w.capability} does not match directory ${o.name}`);let N=p??Sr(""),y=e.state.spec_changes.find(E=>E.capability===o.name);if(y?.delta_source!==void 0){if(y.base_hash!==w.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(w.base_hash!==N)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);m={delta_source:h,base_hash:w.base_hash}}catch(v){if(v.code!=="ENOENT")throw v}a.push({capability:o.name,operation:d,source:s,...m})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Hu(e){let t=le(e.paths,e.state.name),r=await Z({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(mm(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of e.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await Z({root:t,ref:o.source,maxBytes:null,includeHash:!1}),c=s.text,l=null;if(o.delta_source){let u=await Z({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),d=Ho(u.text);c=pb(s.text,d);let p="";try{p=(await Z({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(h){if(h.code!=="ENOENT")throw h}if(Sr(p)===d.base_hash){let h=fb({baselineMarkdown:p,delta:d,allowAlreadyApplied:!0});if(Sr(s.text)!==h.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}l=$("comet.native.shape-artifact-content.v1",$u(u.text))}i.push({capability:o.capability,source:s.ref,markdown:c}),n.push({...o,contentHash:$("comet.native.shape-artifact-content.v1",$u(s.text,e.state.document_constraints_version===2)),...l===null?{}:{deltaContentHash:l}})}let a=null;try{let o=await Z({root:t,ref:iS,maxBytes:65536,includeHash:!1}),s=rS(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!e.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let l=rn.relative(e.paths.projectRoot,rn.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll(rn.sep,"/");if(s.current_spec!==l)throw new Error(`Native capability association points to ${s.current_spec}, expected ${l}`);a=$("comet.native.shape-artifact-content.v1",$u(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:Hl({briefMarkdown:r.text,specs:i,resolveBriefReferences:e.state.document_constraints_version===2}),formalHash:$("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:$("comet.native.shape-artifact-content.v1",$u(r.text,e.state.document_constraints_version===2))},specs:n,association:{source:iS,contentHash:a}})}}function bs(e){return $("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function bm(e){return A(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"prepare-shape-confirmation"}),t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");let r=e.enforceDocumentConstraints===!0?{...t,document_constraints_version:2}:t,i=await Ou({paths:e.paths,state:t});e.enforceDocumentConstraints===!0&&await ju({paths:e.paths,state:r,specChanges:i});let n=await Hu({paths:e.paths,state:r,specChanges:i}),{acceptance:a}=n,o=await Je({changeDir:le(e.paths,t.name),acceptanceIds:a.map(({id:h})=>h),validation:bt({...t,acceptance:a})}),s=t;if(o&&t.workspace.change_branch===null){await wl(e.paths,t.name);let h=Su(t.workspace,e.paths.projectRoot);if(h===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");s=ke({...t,workspace:h},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${h.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let c=await cs(le(e.paths,t.name))||o?.contract.schema==="comet.native.children.v2"&&o.contract.children.length>=2;if(c&&!o)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let l=c?e.coordinationMode??t.coordination_mode:void 0;if(!c&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let u={...s,...r.document_constraints_version===void 0?{}:{document_constraints_version:r.document_constraints_version},spec_changes:i,shape_confirmation_hash:bs({formalHash:n.formalHash,childrenHash:o?.hash??null,coordinationMode:l})};delete u.children_contract_hash,delete u.coordination_mode,c&&(u.coordination_mode=l);let d=pk({state:u,acceptance:a.map(h=>({...h}))});o&&(d.children_contract_hash=ea({acceptance:d.acceptance,children:o.contract}));let p=await he({paths:e.paths,previous:t,next:d});return await M(L(e.paths,t.name),ae({portableState:p,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),p})}async function Ns(e){if(e.state.document_constraints_version!==void 0){let l=await ym(e);if(!l.valid){let u=l.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let t=await Ou(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,u)=>{let d=e.state.spec_changes[u];return d!==void 0&&l.capability===d.capability&&l.source===d.source&&l.delta_source===d.delta_source&&l.base_hash===d.base_hash&&(l.operation===d.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await Hu({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:u})=>({source:l,text:u}));if(!$b(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Je({changeDir:le(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:bt({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&bs({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?ea({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Ze(e){let t=await Ns(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Ss({paths:e.paths,state:e.state,reason:r,keepFailureBudget:!0}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function ks(e){return A(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:Ss({paths:e.paths,state:t,reason:e.reason,...e.keepFailureBudget?{keepFailureBudget:!0}:{}})})}async function Ss(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...ke(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:e.keepFailureBudget?t.loop.failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await he({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}function qu(e,t){let r=O.relative(O.resolve(e),O.resolve(t));if(O.isAbsolute(r)||r===".."||r.startsWith(`..${O.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(O.sep).join("/");return Io(e,i),i}function VH(e){return e.split("\0").some(t=>t.startsWith("160000 "))}function Du(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return qn({id:e.id,name:e.name,executable:r,argv:i,cwdRef:qu(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function lS(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:qu(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function uS(e,t,r,i,n,a){return e.candidateId!==i.builder_handoff?.candidate_id||e.inputFingerprint!==n||O.resolve(e.workspace.projectRoot)!==O.resolve(r)||O.resolve(e.workspace.worktreeRoot)!==O.resolve(r)||e.workspace.branch!==a||e.workspace.machineId!==Tr.hostname()||e.checks.length!==t.length?!1:e.checks.every((o,s)=>Du(o,r)===qn(t[s]))}function km(e,t,r){return e.checks.length===t.length&&e.checks.every((i,n)=>Du(i,r)===qn(t[n]))}async function Bu(e){let t=e.execution;if(t===null||t.status!=="running")return"not-running";if(t.ownerPid===void 0)return"unknown";let r=await Bn(t.ownerPid,t.ownerIdentity);if(r==="alive")return"running";let i=r==="unknown";for(let n of e.checks){if(n.status!=="running")continue;let a=n.activeProcess;if(!a||a.status==="starting"){i=!0;continue}let o=await Bn(a.pid,a.identity);if(o==="alive")return"running";o==="unknown"&&(i=!0)}return i?"unknown":"orphaned"}function aS(e){return{...e,execution:e.execution===null?null:{...e.execution,status:"interrupted"},checks:e.checks.map(t=>t.status==="planned"||t.status==="running"?{...t,status:"interrupted",activeProcess:null}:t)}}function Lu(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:Io(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`,activeProcess:null}}function WH(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return Em(e,t,r,i)}function Em(e,t,r,i){return{...Lu(t,r,i),executionCount:e.executionCount}}function dS(e){return sS("sha256").update(e).digest("hex")}async function Rs(e){let t=await ur.lstat(e);if(!t.isFile())throw new Error("Native check input must be a regular file");let r=sS("sha256"),i=await ur.open(e,"r"),n=0;try{let o=Buffer.allocUnsafe(zH);for(;;){let{bytesRead:s}=await i.read(o,0,o.length,null);if(s===0)break;n+=s,r.update(o.subarray(0,s).toString("base64"))}}finally{await i.close()}let a=await ur.lstat(e);if(a.size!==t.size||a.mtimeMs!==t.mtimeMs)throw new Error("Native check input changed while reading");return{digest:r.digest("hex"),size:n}}var pS=2e4,hS=1024*1024*1024,zH=65535,fS=["build","dist","gen","generated","out","target",".next",".nuxt",".output",".svelte-kit"],GH=new Set([".agents",".cache",".claude",".codex",".comet",".git",".idea",".next",".nuxt",".output",".parcel-cache",".svelte-kit",".tmp",".turbo",".vscode",".worktrees","coverage","logs","node_modules","temp","tmp"]),Nm=[":(exclude).comet/runtime/**",":(exclude).comet/current-change.json"],mS=new Set(["comet-state.yaml","children.yaml","verification.md"]);function vS(e,t){if(!t)return[...Nm];let r=O.relative(e,t).replaceAll("\\","/");if(O.isAbsolute(r)||r===".."||r.startsWith("../"))return[...Nm];let i=r===""?"":`${r}/`;return[...Nm,...["changes","archive"].flatMap(n=>[...mS].map(a=>`:(exclude)${i}comet/${n}/**/${a}`))]}function xm(e,t,r){let i=e.replaceAll("\\","/").replace(/^\.\//u,"");if(i===".comet/current-change.json"||i.startsWith(".comet/runtime/"))return!0;if(!t||!r||!mS.has(O.basename(i)))return!1;let n=O.resolve(t,...i.split("/")),a=O.relative(O.resolve(r),n);if(O.isAbsolute(a)||a===".."||a.startsWith(`..${O.sep}`))return!1;let[,o]=a.split(O.sep);return a.startsWith(`comet${O.sep}`)&&(o==="changes"||o==="archive")}function ua(){return{complete:!1,files:[]}}function JH(e){let t=e==="."?"":`${e}/`;return fS.flatMap(r=>[`:(glob)${t}${r}/**`,`:(glob)${t}**/${r}/**`])}function gS(e){return/(?:^|\/)(?:\.env(?:\..*)?|[^/]+\.(?:key|pem|p12|pfx))$/iu.test(e)}async function wS(e,t,r,i=new Set){let n=[...new Set(t.map(({cwdRef:c})=>c))];if(n.length===0)return{complete:!0,files:[]};let a;try{a=[...new Set(I(e,["ls-files","--others","--ignored","--exclude-standard","-z","--",...n.flatMap(JH)]).split("\0").filter(Boolean).map(c=>c.replaceAll("\\","/")))].sort()}catch{return ua()}if(a.length>pS)return ua();let o=[],s=0;for(let c of a){if(i.has(c)||xm(c,e,r))continue;let l=O.resolve(e,...c.split("/"));if(!Ee(e,l)||gS(c))return ua();try{let u=await ur.lstat(l);if(!u.isFile()||s+u.size>hS)return ua();let{digest:d,size:p}=await Rs(l);s+=p,o.push({path:c,digest:d,size:p})}catch{return ua()}}return{complete:!0,files:o}}async function UH(e,t,r,i=new Set){let n=[...new Set(t.map(({cwdRef:l})=>l))],a=new Map,o=0,s=l=>fS.includes(l),c=async(l,u,d)=>{let p;try{p=await ur.readdir(l,{withFileTypes:!0})}catch{return!1}p.sort((h,f)=>h.name.localeCompare(f.name,"en"));for(let h of p){let f=u?`${u}/${h.name}`:h.name;if(i.has(f)||xm(f,e,r)||h.isDirectory()&&GH.has(h.name))continue;let m=O.join(l,h.name);if(h.isDirectory()){if(!await c(m,f,d||s(h.name)))return!1;continue}if(d){if(gS(f)||!h.isFile())return!1;try{let v=await ur.lstat(m);if(o+v.size>hS)return!1;let{digest:g,size:w}=await Rs(m);if(o+=w,a.set(f,{path:f,digest:g,size:w}),a.size>pS)return!1}catch{return!1}}}return!0};for(let l of n){let u=Io(e,l);if(!await c(u,l==="."?"":l,s(O.basename(u))))return ua()}return{complete:!0,files:[...a.values()].sort((l,u)=>l.path.localeCompare(u.path,"en"))}}function Rm(e,t){return $("comet.native.local-check-evidence.v1",{id:e.id,name:e.name,status:e.status,repeatable:e.repeatable,timeoutMs:e.timeoutMs,argv:e.argv,cwd:O.resolve(e.cwd),exitCode:e.exitCode,startedAt:e.startedAt,completedAt:e.completedAt,log:e.log,logDigest:dS(t)})}async function yS(e){let t=await Mf(e.projectRoot),r=[...vS(e.projectRoot,e.managedArtifactRoot),...[...t].map(a=>`:(exclude,literal)${a}`)],i={complete:!0,capture:"git",head:null,branch:null,status:null,diff:null,stagedDiff:null,submodules:null,untracked:[],ignored:{complete:!0,files:[]},physical:{complete:!0,files:[]},reuseNonce:null},n=!1;try{i.head=I(e.projectRoot,["rev-parse","HEAD"]),n=!0,i.branch=I(e.projectRoot,["branch","--show-current"]),i.status=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...r]);let a=I(e.projectRoot,["diff","--name-only","-z","HEAD","--",...r]).split("\0").filter(Boolean).sort();i.diff=await Yf(a,4,async c=>{let l=O.resolve(e.projectRoot,...c.split("/"));try{let{digest:u}=await Rs(l);return{path:c,digest:u}}catch{return{path:c,digest:null}}}),i.diff.some(({digest:c})=>c===null)&&(i.complete=!1);let o=I(e.projectRoot,["ls-files","--stage","-z","--",...r]);i.stagedDiff=dS(o),i.submodules=VH(o)?I(e.projectRoot,["submodule","status","--recursive"]):"";let s=I(e.projectRoot,["ls-files","--others","--exclude-standard","-z","--",...r]).split("\0").filter(Boolean).sort();i.untracked=await Yf(s,4,async c=>{let l=O.resolve(e.projectRoot,...c.split("/"));try{let{digest:u,size:d}=await Rs(l);return{path:c,digest:u,size:d}}catch{return{path:c,digest:null,size:null}}}),i.untracked.some(({digest:c})=>c===null)&&(i.complete=!1),i.ignored=await wS(e.projectRoot,e.plans,e.managedArtifactRoot,t),i.ignored.complete||(i.complete=!1)}catch{n?i.complete=!1:(i.capture="physical-tree",i.physical=await UH(e.projectRoot,e.plans,e.managedArtifactRoot,t),i.complete=i.physical.complete)}return $("comet.native.check-input.v1",{candidateId:e.state.builder_handoff?.candidate_id??null,shapeConfirmationHash:e.state.shape_confirmation_hash??null,acceptance:e.state.acceptance.map(({id:a,source:o,text:s})=>({id:a,source:o,text:s})),git:i,projectRoot:O.resolve(e.projectRoot),machineId:Tr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,path:process.env.PATH??null,pathext:process.env.PATHEXT??null,boundEnvironment:Object.entries(process.env).filter(([a])=>bS.has(a.toUpperCase())).map(([a,o])=>[a,o??null]).sort(([a],[o])=>a.localeCompare(o))})}var bS=new Set(["PATH","PATHEXT","NODE_OPTIONS","NODE_ENV","NODE_PATH","LANG","LC_ALL","HOME","USERPROFILE","SYSTEMROOT","COMSPEC","SHELL","TMPDIR","TEMP","TMP","HTTP_PROXY","HTTPS_PROXY","NO_PROXY"]);function KH(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function YH(){return Object.entries(process.env).filter(([e])=>bS.has(e.toUpperCase())).map(([e,t])=>[e,t??null]).sort(([e],[t])=>e.localeCompare(t))}async function NS(e){try{let t=await Mf(e.projectRoot),r=[...vS(e.projectRoot,e.managedArtifactRoot),...[...t].map(c=>`:(exclude,literal)${c}`)],i=I(e.projectRoot,["rev-parse","HEAD"]),n=I(e.projectRoot,["branch","--show-current"]),a=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...r]),o=I(e.projectRoot,["ls-files","--stage","-z","--",...r]);if(i===null||a===null)return null;let s=[];for(let c of Qa(e.projectRoot).filter(l=>!t.has(l)&&!xm(l,e.projectRoot,e.managedArtifactRoot))){let l=O.resolve(e.projectRoot,...c.split("/")),u=null;try{u=(await Rs(l)).digest}catch{return null}s.push({path:c,digest:u})}return s.sort((c,l)=>c.path.localeCompare(l.path,"en")),{runnerInputs:t,binding:{candidateId:e.candidateId,head:i,branch:n,status:a,staged:o,workingTree:s,projectRoot:O.resolve(e.projectRoot),machineId:Tr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,boundEnvironment:YH()}}}catch{return null}}async function Sm(e,t){if(t===null)return null;try{let r=await wS(e.projectRoot,e.plans??[],e.managedArtifactRoot,t.runnerInputs);return r.complete?$("comet.native.check-input-gate.v1",{...t.binding,ignored:r}):null}catch{return null}}async function oS(e){return Sm(e,await NS(e))}async function kS(e){let t=await NS(e);return{branch:t===null?ge(e.projectRoot):t.binding.branch||null,gate:await Sm(e,t),candidateGate:await Sm({...e,plans:[]},t)}}function vi(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);if(r.status==="passed"&&(r.evidence!=="runtime"||!r.evidenceDigest))throw new Error(`Native Runtime check ${r.id} has no Runtime execution evidence`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:J(i),argv_display:To(r.argv.slice(1)).map(n=>J(n)),argv_truncated:!1,cwd_ref:qu(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:KH(r)}})}function XH(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function gi(e){if(e.local===null||e.local.change!==e.state.name)return ae({portableState:e.state,projectRoot:e.projectRoot,branch:ge(e.projectRoot)});let t=e.local.execution?.operationId??cS();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function $r(e){try{let t=await Ce(L(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}async function Cm(e){let t=await $r({paths:e.paths,state:e.state}),r=bk({state:e.state,summary:e.summary}),i=await he({paths:e.paths,previous:e.state,next:r});return await M(L(e.paths,e.state.name),gi({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}async function SS(e,t){for(let r of e.checks)if(r.status==="passed"){if(r.evidence!=="runtime")return!1;try{let i=await G(t,O.resolve(t,...r.log.split(/[\\/]/u)));if(!(await ur.stat(i)).isFile())return!1;let n=await ur.readFile(i,"utf8");if(!r.evidenceDigest||r.evidenceDigest!==Rm(r,n))return!1}catch{return!1}}return!0}async function ES(e){let{local:t,previous:r,next:i,plans:n,paths:a}=e;if(!t||!t.checks.length||t.checks.some(({status:s})=>s!=="passed")||t.basedOnStateVersion!==r.state_version||t.candidateId!==r.builder_handoff?.candidate_id||t.workspace.machineId!==Tr.hostname()||t.inputFingerprint==null||t.inputFingerprintGate==null||t.execution?.stage==="checking"&&t.execution.status==="running"||r.shape_confirmation_hash!==i.shape_confirmation_hash||JSON.stringify(r.acceptance.map(({id:s,source:c,text:l})=>({id:s,source:c,text:l})))!==JSON.stringify(i.acceptance.map(({id:s,source:c,text:l})=>({id:s,source:c,text:l}))))return null;let o=t.workspace.worktreeRoot;if(O.resolve(t.workspace.projectRoot)!==O.resolve(e.projectRoot??a.projectRoot)||O.resolve(o)!==O.resolve(e.projectRoot??a.projectRoot))return null;try{if(t.workspace.branch!==ge(o)||!km(t,n,o)||!await SS(t,me(a,i.name)))return null;let s={projectRoot:o,candidateId:t.candidateId??null,plans:n,managedArtifactRoot:a.artifactRoot},c=await oS(s);if(c===null||c!==t.inputFingerprintGate)return null;let l=await yS({state:i,projectRoot:o,plans:n,managedArtifactRoot:a.artifactRoot}),u=await kS({...s,candidateId:i.builder_handoff.candidate_id});return u.gate===null||u.candidateGate===null||await oS(s)!==c?null:{...gi({local:t,state:i,projectRoot:a.projectRoot}),candidateId:i.builder_handoff.candidate_id,inputFingerprint:l,inputFingerprintGate:u.gate,candidateInputFingerprintGate:u.candidateGate}}catch{return null}}async function QH(e){return A(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let{gate:r,candidateGate:i,branch:n}=await kS({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),a=n,o=L(e.paths,t.name),s=(await Nu({file:o,portableState:t,projectRoot:e.projectRoot,branch:a,containedRoot:e.paths.runtimeDir})).state;a!==null&&s.workspace.branch===`heads/${a}`&&(a=ge(e.projectRoot));let c=r===null,u=r!==null&&s.inputFingerprint!==null&&s.inputFingerprintGate===r&&s.candidateInputFingerprintGate===i&&s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.machineId===Tr.hostname()?s.inputFingerprint:await yS({state:t,projectRoot:e.projectRoot,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),d=me(e.paths,t.name),p=await SS(s,d),h=s.checks.every(S=>S.status==="passed"),f=e.retryCheckIds===void 0?null:new Set(e.retryCheckIds),m=s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.branch===a&&s.workspace.machineId===Tr.hostname()&&s.inputFingerprint===u,v=i!==null&&s.candidateInputFingerprintGate===i&&s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.branch===a&&s.workspace.machineId===Tr.hostname(),g=v&&s.inputFingerprint!==null&&s.inputFingerprint!==u,w=uS(s,e.plans,e.projectRoot,t,u,a)||v&&km(s,e.plans,e.projectRoot),N=s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.branch===a&&s.workspace.machineId===Tr.hostname(),y=m&&h&&!p;if(f&&f.size===0)throw new Error("Native check retry list must contain at least one ID");if(!m&&s.execution?.stage==="checking"&&s.execution.actor==="runtime"&&s.execution.status==="running"){let S=await Bu(s);if(S!=="orphaned")throw new Error(S==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before changing its binding":"Native check plan is already in progress on another workspace binding");s=aS(s),await M(o,s,{containedRoot:e.paths.runtimeDir})}if(!m&&N&&s.inputFingerprint!==null&&(s.execution!==null||s.checks.length>0)){let S=s.inputFingerprint!==u;if(!(c&&!S||g)){let C=pi({state:t,reason:"Native check input changed after the candidate was built; a new Builder candidate is required before checks can run again."}),P=await he({paths:e.paths,previous:t,next:C});throw await M(o,ae({portableState:P,projectRoot:e.paths.projectRoot,branch:a}),{containedRoot:e.paths.runtimeDir}),new Error("Native check input changed after the candidate was built; the change returned to Build for a new candidate")}}if(!m&&!v){let S=ae({portableState:t,projectRoot:e.projectRoot,branch:a});await M(o,S,{containedRoot:e.paths.runtimeDir}),s=S}let E=km(s,e.plans,e.projectRoot);if(s.execution?.stage==="checking"&&s.execution.actor==="runtime"&&E&&w){let S=s.execution;if(S.status==="running"){let P=await Bu(s);if(P!=="orphaned")throw new Error(P==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before retrying":"Native check plan is already in progress");s=aS(s),await M(o,s,{containedRoot:e.paths.runtimeDir}),S=s.execution}let C=s.checks.filter(P=>P.status==="interrupted");if(C.length===0&&S.status==="completed"&&h&&!y&&!g){let P=new Map(e.plans.map(({id:_,name:j})=>[_,j]));return{kind:"reuse",state:t,checks:vi({local:s,projectRoot:e.projectRoot,supplied:[],requestedNames:P})}}if(C.length===0&&S.status==="completed"&&!h&&!y&&!g)throw new Error(`Native check plan contains a failed check (${s.checks.filter(({status:P})=>P==="failed").map(({id:P})=>P).join(", ")}); submit a new Builder candidate`);if(C.length>0&&C.some(P=>!P.repeatable)&&!y){let P=pi({state:t,reason:`A non-repeatable Runtime check was interrupted (${C.filter(j=>!j.repeatable).map(({id:j})=>j).join(", ")}); a new Builder candidate is required before it can run again.`}),_=await he({paths:e.paths,previous:t,next:P});throw await M(L(e.paths,t.name),ae({portableState:_,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${C.find(j=>!j.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}if(C.length>0&&f===null&&!y&&!g){let P=new Map(e.plans.map(({id:_,name:j})=>[_,j]));return{kind:"reuse",state:t,checks:vi({local:s,projectRoot:e.projectRoot,supplied:[],requestedNames:P})}}if(f){let P=[...f].filter(j=>!C.some(ue=>ue.id===j));if(P.length>0)throw new Error(`Native check retry IDs must refer to interrupted checks: ${P.join(", ")}`);let _=C.filter(j=>f.has(j.id)&&j.executionCount>=3);if(_.length>0)throw new Error(`Native check retry limit (3) reached: ${_.map(({id:j})=>j).join(", ")}`)}}if(s.execution!==null&&s.checks.length>0){if(!(s.execution.stage==="checking"&&s.execution.actor==="runtime"&&s.checks.some(C=>C.status==="interrupted")&&E)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan")}else if((s.execution!==null||s.checks.length>0)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan");let b=cS(),x=await ct(process.pid),k={...s,candidateId:t.builder_handoff?.candidate_id??null,inputFingerprint:u,inputFingerprintGate:r,candidateInputFingerprintGate:i,workspace:{...s.workspace,projectRoot:O.resolve(e.projectRoot),worktreeRoot:O.resolve(e.projectRoot),branch:ge(e.projectRoot),machineId:Tr.hostname()},execution:{operationId:b,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0,ownerPid:process.pid,...x?{ownerIdentity:x}:{}},checks:e.plans.map(S=>{let C=s.checks.find(P=>P.id===S.id);return g&&C?Lu(S,b,e.projectRoot):y&&C?Em(C,S,b,e.projectRoot):C?.status==="interrupted"&&(f===null||f.has(C.id))?WH(C,S,b,e.projectRoot):C?{...C,operationId:b,activeProcess:null}:Lu(S,b,e.projectRoot)})};return await M(o,k,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:k,plans:e.plans.filter(S=>{let C=s.checks.find(P=>P.id===S.id);return y||g||C===void 0||C.status==="interrupted"&&(f===null||f.has(C.id))})}})}async function Es(e){return A(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await H(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=L(e.paths,t.name),i=await Ce(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await M(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function Cs(e){let t=e.projectRoot??e.paths.projectRoot;lt(t,e.plans);let r=[],i=new Set;for(let c of e.plans){$o(t,c);let l=qn(c);i.has(l)||(i.add(l),r.push(c))}let n=await QH({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return{...n,disposition:"reused"};let a=n.local.execution.operationId,o=me(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await Es({paths:e.paths,state:n.state,operationId:a,update:p=>({...p,checks:p.checks.map(h=>h.id===c.id?{...h,status:"running",executionCount:h.executionCount+1,startedAt:l,activeProcess:{status:"starting"}}:h)})});let u=await Bi({projectRoot:t,runtimeDir:o,operationId:a,plan:c,onSpawn:async({pid:p})=>{let h=await ct(p);await Es({paths:e.paths,state:n.state,operationId:a,update:f=>({...f,checks:f.checks.map(m=>m.id===c.id?{...m,activeProcess:{status:"running",pid:p,...h?{identity:h}:{}}}:m)})})}}),d=await ur.readFile(O.resolve(o,...u.logRef.split("/")),"utf8");await Es({paths:e.paths,state:n.state,operationId:a,update:p=>({...p,checks:p.checks.map(h=>{if(h.id!==c.id)return h;let f={...h,status:u.status,exitCode:u.exitCode,startedAt:u.startedAt,completedAt:u.completedAt,log:u.logRef,activeProcess:null,evidence:"runtime"};return{...f,evidenceDigest:Rm(f,d)}})})})}await Es({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await Es({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted",activeProcess:null}:u)})})}catch{}throw c}let s=await Ce(L(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:vi({local:s,projectRoot:t,supplied:[]}),disposition:"executed"}}async function Pm(e){if(e.checkIds.length===0)throw new Error("Native check retry list must contain at least one ID");let t=e.projectRoot??e.paths.projectRoot,r=await H(e.paths,e.name);if(r.phase!=="verify"||r.status!=="active"||r.loop.stage!=="verify-ready"||r.builder_handoff===null)throw new Error("Native check retry requires an active Verify-ready candidate");let i=await Ce(L(e.paths,e.name));if(i===null||i.change!==r.name||i.basedOnStateVersion!==r.state_version||i.execution===null||i.execution.stage!=="checking"||i.execution.actor!=="runtime")throw new Error("Native check retry has no current Runtime check execution");let n=new Set(e.checkIds);if(n.size!==e.checkIds.length)throw new Error("Native check retry list contains duplicate IDs");let a=i.checks.filter(c=>n.has(c.id)),o=e.checkIds.filter(c=>!a.some(l=>l.id===c));if(o.length>0)throw new Error(`Native check retry IDs are unknown: ${o.join(", ")}`);for(let c of a){if(c.status!=="interrupted")throw new Error(`Native check ${c.id} is not interrupted and cannot be retried`);if(!c.repeatable)throw new Error(`Native check ${c.id} is not repeatable and cannot be retried`);if(c.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${c.id}`)}let s=i.checks.map(c=>{let[l,...u]=c.argv;if(!l)throw new Error(`Native local check ${c.id} has no executable`);return{id:c.id,name:c.name,executable:l,argv:u,cwdRef:qu(t,c.cwd),timeoutMs:c.timeoutMs,repeatable:c.repeatable}});return Cs({paths:e.paths,name:e.name,plans:s,projectRoot:t,retryCheckIds:e.checkIds})}async function xS(e){let t=L(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=Wf)throw new Error(`Native Verifier request-checks exceeded ${Wf} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let h of r.checks){let f=Du(h,e.projectRoot);n.set(f,h),h.status==="passed"&&i.set(f,h),a.set(h.id,f)}let o=new Map,s=new Map;for(let h of e.response.checks){let f=XH(h);$o(e.projectRoot,f);let m=qn(f),v=s.get(f.id);if(v!==void 0&&v!==m)throw new Error(`Native Verifier check ID ${f.id} refers to conflicting commands`);let g=a.get(f.id);if(g!==void 0&&g!==m)throw new Error(`Native Verifier check ID ${f.id} conflicts with a Runtime check`);s.set(f.id,m);let w=n.get(m);if(w&&w.status!=="passed"&&!w.repeatable)throw new Error(`Native check ${w.id} did not pass and is not repeatable; user resolution is required`);if(w&&w.status!=="passed"&&w.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${w.id}`);o.has(m)||o.set(m,f)}lt(e.projectRoot,[...o.values()]);let c=[...o.entries()],l=c.filter(([h])=>!i.has(h));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let u=r.execution.requestCheckRounds+1,d=new Map(c.map(([,h])=>[h.id,h.name])),p={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...r.checks.map(h=>{let f=Du(h,e.projectRoot),m=o.get(f);return m&&h.status!=="passed"?Em(h,m,r.execution.operationId,e.projectRoot):h}),...l.filter(([h])=>!n.has(h)).map(([,h])=>Lu(h,r.execution.operationId,e.projectRoot))]};return await M(t,p,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:p,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,h])=>h),requestedNames:d,reusedCheckIds:c.filter(([h])=>i.has(h)).map(([,h])=>h.id),suppliedChecks:e.suppliedChecks}}async function xs(e){return A(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await H(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=L(e.paths,t.name),i=await Ce(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await M(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function RS(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await xs({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>c.id===r.id?{...c,status:"running",executionCount:c.executionCount+1,startedAt:i,activeProcess:{status:"starting"}}:c)})});let n=me(e.paths,e.reservation.state.name),a=await Bi({projectRoot:e.projectRoot,runtimeDir:n,operationId:e.reservation.local.execution.operationId,plan:r,onSpawn:async({pid:s})=>{let c=await ct(s);await xs({paths:e.paths,reservation:e.reservation,update:l=>({...l,checks:l.checks.map(u=>u.id===r.id?{...u,activeProcess:{status:"running",pid:s,...c?{identity:c}:{}}}:u)})})}}),o=await ur.readFile(await G(n,O.resolve(n,...a.logRef.split(/[\\/]/u))),"utf8");t=await xs({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>{if(c.id!==r.id)return c;let l={...c,status:a.status,exitCode:a.exitCode,startedAt:a.startedAt,completedAt:a.completedAt,log:a.logRef,activeProcess:null,evidence:"runtime"};return{...l,evidenceDigest:Rm(l,o)}})})})}t=await xs({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await xs({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted",activeProcess:null}:n)})})}catch{}throw r}return{checks:vi({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}import{accessSync as f6,constants as m6,promises as AS}from"node:fs";import pa from"node:path";ne();var ZH=fr(Gt(),1);We();pe();rt();at();yn();We();gt();ve();gt();ve();Hi();kr();at();ni();async function _m(e){return A(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"confirm-shape"}),t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native Shape can only be confirmed from the persisted user confirmation boundary");if(e.coordinationMode!==void 0&&t.coordination_mode!==void 0&&e.coordinationMode!==t.coordination_mode)throw new Error("--coordination-mode is already bound to this Shape confirmation; revise Shape before changing it");await Ze({paths:e.paths,state:t});let r=await Ou({paths:e.paths,state:t}),i=await Hu({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Je({changeDir:le(e.paths,t.name),acceptanceIds:n.map(({id:g})=>g),validation:bt({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await wl(e.paths,t.name);let g=Su(t.workspace,e.paths.projectRoot);if(g===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");o=ke({...t,workspace:g},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${g.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await cs(le(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,c=e.coordinationMode??t.coordination_mode;if(!s&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");if(s&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(s&&c===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let l=bs({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:t.coordination_mode});if(t.shape_confirmation_hash===void 0||l!==t.shape_confirmation_hash){let g=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await Ss({paths:e.paths,state:t,reason:g,keepFailureBudget:!0}),new Error(`${g}; Native change returned to Shape and requires confirmation`)}let u=dk({state:{...o,spec_changes:r,shape_confirmation_hash:bs({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c})},acceptance:n.map(g=>({...g}))});if(delete u.children_contract_hash,delete u.coordination_mode,a){u.children_contract_hash=ea({acceptance:u.acceptance,children:a.contract}),s&&(u.coordination_mode=c);let g=[...t.history].reverse().find(({outcome:w})=>w==="pass"||w==="fail");if(g?.outcome==="fail"&&g.unresolved_ids.length>0){let w=await Le({paths:e.paths,state:u}),N=new Map((w?.children??[]).map(({name:b,status:x})=>[b,x])),y=new Set(a.contract.children.filter(({name:b})=>{let x=N.get(b);return x!=="done"&&x!=="integrated"&&x!=="archived"}).flatMap(({covers:b})=>b)),E=g.unresolved_ids.filter(b=>!y.has(b));if(E.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${E.join(", ")}`)}}let d=null,p=a?.contract.schema==="comet.native.children.v2"?await D(e.paths,t.name):null,h=null,f=null;if(a?.contract.schema==="comet.native.children.v2"){if(h=o.workspace.change_branch??o.workspace.target_branch,!h)throw new Error("Native Supervisor v2 requires a target branch");if(f=wr(e.paths.projectRoot,h),!f)throw new Error(`Native Supervisor target branch has no commit: ${h}`);p||(p=await ss({paths:e.paths,parent:t.name,targetBranch:h,contract:a.contract})),p||(d=await Df({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:h,sourceConfig:await Oe(e.paths.projectRoot)}))}let m=a?.contract.schema==="comet.native.children.v2"&&h&&f?p?Nh({state:p,contract:a.contract}):d?xo({parent:u.name,targetBranch:h,targetCommit:f,integrationBranch:d.binding.changeBranch,integrationWorktree:d.projectRoot,contract:a.contract}):null:null;if(a?.contract.schema==="comet.native.children.v2"&&!m)throw new Error("Native Supervisor integration state is unavailable");let v=await he({paths:e.paths,previous:t,next:u});return await M(L(e.paths,t.name),ae({portableState:v,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),m&&await F(e.paths,m),v})}import{randomUUID as eD}from"node:crypto";import Fu from"node:path";ve();ko();ji();function CS(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function tD(e){let{state:t,local:r,envelope:i}=e;if(!pl(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function rD(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Am(e){return A(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),await Je({changeDir:le(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:o})=>o),validation:bt(t)})||t.children_contract_hash){let o=await Le({paths:e.paths,state:t});if(!o?.confirmed||!o.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=hk({state:t,input:e.input}),n=e.verificationChecks===void 0?null:await ES({paths:e.paths,previous:t,next:i,plans:e.verificationChecks,projectRoot:e.projectRoot,local:await $r({paths:e.paths,state:t})}),a=await he({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),n??ae({portableState:a,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a})}async function Im(e){return A(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Ze({paths:e.paths,state:t});let i=(await Nu({file:L(e.paths,t.name),portableState:t,projectRoot:r,branch:ge(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");vi({local:i,projectRoot:r,supplied:e.checks});let n=fk(t),a=await he({paths:e.paths,previous:t,next:n}),o=L(e.paths,t.name),s=eD();return await M(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function Tm(e){return A(e.paths,`confirm portable verifier start ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier start confirmation requires an active Verifier attempt");let r=L(e.paths,e.name),i=await Ce(r),n=i?.execution;if(i===null||i.change!==t.name||i.basedOnStateVersion!==t.state_version||!n||n.stage!=="verifying"||n.actor!=="verifier"||n.status!=="running"||n.executionId===null||n.executionId!==e.verifierExecutionRef)throw new Error("Native Verifier start confirmation is stale for the current attempt");if(t.builder_handoff?.candidate_id!==e.candidateId)throw new Error("Native Verifier start confirmation is stale for the current candidate");return n.verifierStartedAt===void 0&&await M(r,{...i,execution:{...n,verifierStartedAt:new Date().toISOString()}},{containedRoot:e.paths.runtimeDir}),t})}async function $m(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await A(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await H(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Ze({paths:e.paths,state:r});let n=await $r({paths:e.paths,state:r}),a=tD({state:r,local:n,envelope:e.envelope}),o;try{o=No(a.payload)}catch(d){throw new Error(`Native Verifier response was rejected: ${d.message}; correct the response and continue the same active Verifier`,{cause:d})}let s=rD(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=vi({local:n,projectRoot:i,supplied:e.checks}));let d=mk({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(d.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let p=await xS({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:d.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:d.response,reservation:p}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=d}catch(d){throw new Error(`Native Verifier response was rejected: ${d.message}; correct the response or request missing checks using the same active Verifier`,{cause:d})}let u=await he({paths:e.paths,previous:r,next:l.state});return await M(L(e.paths,r.name),gi({local:n,state:u,projectRoot:i}),{containedRoot:e.paths.runtimeDir}),u.verification!==null&&await fi({file:Fu.join(le(e.paths,r.name),"verification.md"),state:u}),{kind:"final-result",result:{state:u,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await RS({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier-requested check execution failed: ${r.message}`,n=await A(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await H(e.paths,e.name);return a.state_version!==t.state.state_version?null:Cm({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Vf} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function jm(e){return A(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await H(e.paths,e.name),r=await $r({paths:e.paths,state:t});if(CS({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return Cm({paths:e.paths,state:t,summary:e.summary})})}async function Om(e){return A(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let r=await $r({paths:e.paths,state:t}),i=CS({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=vi({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=gk({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await he({paths:e.paths,previous:t,next:a});return await M(L(e.paths,t.name),gi({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await fi({file:Fu.join(le(e.paths,t.name),"verification.md"),state:o}),o})}async function Hm(e){return A(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);Mt({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Ze({paths:e.paths,state:t});let r=wk({state:t,summary:e.summary}),i=await he({paths:e.paths,previous:t,next:r});return await M(L(e.paths,t.name),ae({portableState:i,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await fi({file:Fu.join(le(e.paths,t.name),"verification.md"),state:i}),i})}async function Dm(e){return A(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await H(e.paths,e.name);Mt({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Ze({paths:e.paths,state:t});let r=await $r({paths:e.paths,state:t}),i=yk(t,{reason:e.reason}),n=await he({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),gi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Bm(e){return A(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);Mt({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await $r({paths:e.paths,state:t}),i=Nk(t),n=await he({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),gi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function nn(e){return A(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=e.preserveLocalChecks!==!1,i=r?await $r({paths:e.paths,state:t}):null,n=pi({state:t,reason:e.reason,...e.failureBudget?{failureBudget:e.failureBudget}:{}}),a=await he({paths:e.paths,previous:t,next:n});return await M(L(e.paths,t.name),r?gi({local:i,state:a,projectRoot:e.paths.projectRoot}):ae({portableState:a,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a})}async function Ps(e){if(e.state.verification===null)return"not-applicable";let t=Fu.join(le(e.paths,e.state.name),"verification.md");return await Zk({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await fi({file:t,state:e.state}),"rebuilt")}import iD from"node:path";kr();ve();async function Lm(e){return A(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Ze({paths:e.paths,state:t}),e.finish!==void 0&&!["keep","merge","push","pull-request"].includes(e.finish))throw new Error("Native workspace finish must be keep, merge, push, or pull-request");if(e.finish!==void 0&&t.workspace.isolation==="current")throw new Error("A workspace finish choice requires an isolated Native workspace");let r=await D(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(Ki(r).stateVersion!==r.stateVersion)return la({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await F(e.paths,Yi(r,t))}let i=vk(t);e.finish!==void 0&&(i.workspace={...i.workspace,finish:e.finish});let n=await he({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await fi({file:iD.join(le(e.paths,t.name),"verification.md"),state:n}),n})}import{promises as PS}from"node:fs";kr();ve();Ml();async function _s(e){let t=await H(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await Le({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选可以提交并进入验证":"All Children are complete; the Supervisor parent candidate can be submitted for verification.";return{state:t,parentAdvance:{...r,message:n}}}async function _S(e){let t=await H(e.paths,e.name),r=await Fl(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await D(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await PS.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=Ki(n);if(i||a.stateVersion!==n.stateVersion){let o=await la({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await PS.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await F(e.paths,Yi(n,t)),{state:t,action:"recorded-final-verification"}}async function Mu(e){return A(e.paths,`recover Supervisor final verification ${e.name}`,()=>_S(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}var n6=16*1024;Gn();yn();var IS="comet.native.workspace-finish.v1",aD="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",jS=new RegExp(`^${aD}$`,"u"),oD=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,As=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function TS(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function sD(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==IS||typeof t.name!="string"||!jS.test(t.name)||typeof t.transactionId!="string"||!oD.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!pa.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"&&pa.isAbsolute(i))||![r.changeBranch,r.targetBranch].every(i=>typeof i=="string"&&i.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!pa.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");TS(r.commitMessage,"commit-message"),r.mergeMessage!==null&&TS(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||!As.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(i=>typeof i=="string"&&i.length>0&&!pa.posix.isAbsolute(i)&&!pa.win32.isAbsolute(i)&&!i.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(i=>typeof i=="string")||r.sha!==null&&!As.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!As.test(r.target)||!As.test(r.source)||r.sha!==null&&!As.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:IS,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 cD(e,t){if(!jS.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return pa.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function OS(e,t,r={}){let i=cD(e,t);try{let n=await AS.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=sD(JSON.parse(await AS.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}}import{randomUUID as lD}from"node:crypto";import{promises as Is}from"node:fs";import uD from"node:path";ne();rt();ve();ef();Ml();Dl();at();ie();var HS=["evidence.md","repair.md","archive.md","checkpoint.md"],dD="verification.md";async function pD(e,t){let r=await Fl(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function DS(e,t){await Is.mkdir(e.transactionsDir,{recursive:!0}),await fe(ql(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function BS(e,t,r={}){let i=r.removeVerificationReport===!1?HS:[...HS,dD];await Promise.all([Is.rm(me(e,t),{recursive:!0,force:!0}),Is.rm(ch(e,t),{recursive:!0,force:!0}),...i.map(n=>Is.rm(uD.join(qt(e,t),n),{force:!0}))])}async function LS(e,t){await M(L(e,t.name),ae({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function qS(e,t){try{let r=await gs(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function FS(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=oe(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function hD(e){let t=qt(e.paths,e.state.name),r=await Z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Hl({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function MS(e,t){let r=await Kk(e,t);if(r.status==="runtime-incompatible")throw new Qt(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function VS(e){return A(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await pD(e.paths,e.name),r=await na(e.paths,e.name)?await yt(dt(e.paths,e.name)):null;if(!t&&r)return await BS(e.paths,e.name,{removeVerificationReport:!1}),await LS(e.paths,r),r;let i=null,n=null;for(t||(i=await MS(e.paths,e.name),n=await qS(e.paths,e.name),FS(e.paths,n),t={schema:Bl,id:lD(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await DS(e.paths,t));;){let a=Ob(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await MS(e.paths,e.name),n??=await qS(e.paths,e.name),FS(e.paths,n),r=jb({state:i,acceptance:await hD({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await yo(dt(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await BS(e.paths,e.name):a.action==="commit-transaction"&&(r??=await yt(dt(e.paths,e.name)),await LS(e.paths,r)),t={...t,status:a.nextStatus},await DS(e.paths,t)}return await Is.rm(ql(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??yt(dt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as zS}from"node:fs";import GS from"node:path";ve();import{promises as qm}from"node:fs";import fD from"node:path";pe();var mD=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),vD=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),gD=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),wD=new Set(["status","summary"]);function Vu(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Wu(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 yD(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function an(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function bD(e,t,r,i){let n=Vu(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Wu(n,mD,"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=Vu(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Wu(o,vD,"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=Vu(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Wu(c,wD,"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=Vu(d,`Native Supervisor child ${u}`);if(!p)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:h,contractHash:f,...m}=p,v=Wu(m,gD,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],w=g.covers.length>0?g.covers.map(y=>({id:y,source:r.acceptance_index?.[y]?.source??"brief.md",text:r.acceptance_index?.[y]?.text??y})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(h!==void 0&&JSON.stringify(h)!==JSON.stringify(w)||f!==void 0&&f!==$("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||!yD(p.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let N=g.depends_on.length===0?"ready":"pending";if(p.status!==N)return`Native Supervisor child ${g.name} has progressed beyond its initial ${N} 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 ha(e){let t=Di(e.paths,e.state.name),r;try{let c=await qm.lstat(t);if(!c.isFile()||c.isSymbolicLink())return an(t,"","Native Supervisor overlay is not a regular file");r=await qm.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:an(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return an(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=fD.join(e.paths.changesDir,e.state.name),a;try{a=await Je({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return an(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 D(e.paths,e.state.name)}catch(c){return an(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return an(t,r,"Native Supervisor overlay disappeared during inspection");let s=bD(i,e.state,a.contract,o);return s?an(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function WS(e){let t=await ha({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await qm.rm(t.file,{force:!1})}at();ni();function Fm(e,t){let r=oe(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function ND(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function kD(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:ke(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(t),completed_at:i});return B({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?ND(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function SD(e){try{let t=await Ce(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Mm(e){return A(e.paths,`recover portable change ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.status==="done")return await Ps({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=Fm(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await ha({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await WS({paths:e.paths,state:t,expected:i}),n=!0);let a=L(e.paths,e.name),o=await SD(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason,c=s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed";if(c&&o.local?.execution?.status==="running"){let m=o.local.execution,v=await Bu(o.local),g=m.stage==="verifying"&&m.actor==="verifier"&&m.executionId!==null,w=v==="unknown"&&e.recoverUnknownRuntimeCheck===!0&&m.stage==="checking"&&m.actor==="runtime";if(g||v!=="orphaned"&&!w)return{state:t,local:o.local,action:"await-user",reason:"execution-active",message:g?m.verifierStartedAt===void 0&&m.requestCheckRounds===0?`Native Verifier execution ${m.executionId} is registered but never confirmed startup; if the task did not start, record an explicit Verifier failure before retrying it.`:`Native Verifier execution ${m.executionId} remains owned by its host task; record an explicit Verifier failure before retrying it.`:v==="unknown"?"The Native Runtime check owner could not be proven to have exited; inspect the overlay or run Doctor with --repair to take over explicitly.":"The Native Runtime check operation is still owned by a live process; wait for it to finish before recovering it."}}if(c&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(m=>m.status==="planned"||m.status==="running"?{...m,status:"interrupted"}:m)},await M(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Ps({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(m=>m.status==="interrupted"&&!m.repeatable):void 0;if(l){let m=pi({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Dn({file:dt(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot}),await zS.rm(GS.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let v=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await M(a,v,{containedRoot:e.paths.runtimeDir}),{state:t,local:v,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let u=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",d=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",p=u||d;if(p){let m=kD(t,d?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",d);t=await Dn({file:dt(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot})}let h=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:oe(e.paths.projectRoot).currentBranch});await zS.mkdir(GS.dirname(L(e.paths,t.name)),{recursive:!0}),await M(a,h,{containedRoot:e.paths.runtimeDir}),await Ps({paths:e.paths,state:t});let f=s==="stale"&&o.local?`Local execution overlay was recorded for state version ${String(o.local.basedOnStateVersion)} of ${o.local.change} but the current state version is ${String(t.state_version)} of ${t.name}; a state transition moved on, so the overlay was rebuilt from the stable boundary.`:null;return{state:t,local:h,action:p?"reverify":"resume-stable-boundary",reason:s,message:f??(p?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`)}})}import JS from"node:path";function US(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Pe(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:US(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:US(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=>JS.relative(t.projectRoot,JS.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}mo();vo();function zu(e){return e.charCodeAt(0)===65279?e.slice(1):e}Vo();Gn();pe();import{randomUUID as ZS}from"node:crypto";import{promises as KS}from"node:fs";import Ts from"node:path";We();Fn();Hf();ko();ve();ji();function va(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function W(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function fa(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>W(r,`${t}[${i}]`))}function ED(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=va(t,`Native Builder check ${r}`);if(ee(i,["name","result","note"],`Native Builder check ${r}`,`/checks/${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:W(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function Gu(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=va(t,`Native Runtime check ${r}`);if(ee(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`,`/checks/${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:W(i.id,`Native Runtime check ${r} id`),name:W(i.name,`Native Runtime check ${r} name`),executable:W(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:W(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function YS(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:W(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function xD(e){let t=va(e,"Native Supervisor evidence");return ee(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence","/evidence"),{summary:W(t.summary,"Native Supervisor evidence summary"),checks:fa(t.checks,"Native Supervisor evidence checks"),acceptance:fl(t.acceptance,"/evidence/acceptance"),...t.receiptRef===null?{}:{receiptRef:W(t.receiptRef,"Native Supervisor receipt ref")}}}function eE(e){let t=va(e,"Native Runner input");if(t.kind==="builder-handoff"){let r=["kind","summary","addressed_acceptance_ids","checks","known_limits"];Object.hasOwn(t,"acceptance_review")&&r.push("acceptance_review"),Object.hasOwn(t,"verification_checks")&&r.push("verification_checks"),ee(t,Object.hasOwn(t,"review")?[...r,"review"]:r,"Native Runner Builder input");let i=null;if(t.review!==void 0&&t.review!==null){let n=va(t.review,"Native Builder review");if(ee(n,["status","summary","reviewer_execution_ref"],"Native Builder review","/review"),n.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");i={status:"passed",summary:W(n.summary,"Native Builder review summary"),reviewer_execution_ref:W(n.reviewer_execution_ref,"Native Builder reviewer execution ref")}}return{kind:"builder-handoff",summary:W(t.summary,"Native Builder summary"),...Object.hasOwn(t,"acceptance_review")?{acceptance_review:Tn(t.acceptance_review)}:{},addressed_acceptance_ids:fa(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:ED(t.checks),...Object.hasOwn(t,"verification_checks")?{verification_checks:Gu(t.verification_checks)}:{},known_limits:fa(t.known_limits,"Native Builder known limits"),review:i}}if(t.kind==="dispatch-verifier")return ee(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:Gu(t.checks)};if(t.kind==="retry-checks")return ee(t,["kind","check_ids"],"Native Runner check retry input"),{kind:"retry-checks",check_ids:fa(t.check_ids,"Native check retry IDs")};if(t.kind==="verifier-response")return ee(t,["kind","candidateId","verifierExecutionRef","response"],"Native Runner Verifier input"),{kind:"verifier-response",candidateId:W(t.candidateId,"Native Runner Verifier candidateId"),verifierExecutionRef:W(t.verifierExecutionRef,"Native Runner Verifier verifierExecutionRef"),response:No(t.response,"/response")};if(t.kind==="verifier-started")return ee(t,["kind","candidateId","verifierExecutionRef"],"Native Runner started input"),{kind:"verifier-started",candidateId:W(t.candidateId,"Native Runner started candidateId"),verifierExecutionRef:W(t.verifierExecutionRef,"Native Runner started verifierExecutionRef")};if(t.kind==="verifier-execution-error")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:W(t.summary,"Native Verifier execution error summary"),...YS(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:W(t.summary,"Native unavailable Verifier summary"),...YS(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return ee(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),candidateCommit:W(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return ee(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),reason:W(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-retry-builder"){if(ee(t,["kind","child","stateVersion"],"Native Supervisor Builder retry input"),!Number.isSafeInteger(t.stateVersion)||t.stateVersion<1)throw new Error("Native Supervisor Builder retry stateVersion is invalid");return{kind:"supervisor-retry-builder",child:W(t.child,"Native Supervisor child"),stateVersion:t.stateVersion}}if(t.kind==="supervisor-reconnect")return ee(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return ee(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),reason:W(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(ee(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:xD(t.evidence)}}if(t.kind==="supervisor-checks"){let r=["kind","child","runId","checks","materials"];if(ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor checks"),!Array.isArray(t.materials))throw new Error("Native Supervisor materials must be an array");return{kind:"supervisor-checks",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),checks:Gu(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:fa(t.retry_check_ids,"Native Supervisor retry IDs")},materials:t.materials.map((i,n)=>{let a=va(i,"Native Supervisor material");return ee(a,["name","content"],"Native Supervisor material",`/materials/${n}`),{name:W(a.name,"Native Supervisor material name"),content:W(a.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate"){let r=["kind","child","checks"];return ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor integration input"),{kind:"supervisor-integrate",child:W(t.child,"Native Supervisor child"),checks:Gu(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:fa(t.retry_check_ids,"Native Supervisor retry IDs")}}}throw new Error("Native Runner input kind is invalid")}async function Jm(e,t){let r=Ts.resolve(t,e),i=await KS.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(zu(await KS.readFile(r,"utf8")))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return eE(n)}async function Um(e){await A(e.paths,"register-runner-input",async()=>{await lk({paths:e.paths,file:e.file,validateContent:t=>{let r=eE(JSON.parse(zu(t)));if($("comet.native.runner-input.v1",r)!==$("comet.native.runner-input.v1",e.input))throw new Error("Native Runner input changed after parsing")}})})}function RD(e){return e.kind==="builder-handoff"||e.kind==="dispatch-verifier"||e.kind==="retry-checks"||e.kind==="verifier-response"||e.kind==="verifier-started"||e.kind==="verifier-execution-error"||e.kind==="verifier-unavailable"}function CD(e){return e.kind.startsWith("supervisor-")}function PD(e){return e.response.kind!=="request-checks"?[]:e.response.checks.map(({id:t,name:r,executable:i,argv:n,cwdRef:a,timeoutMs:o,repeatable:s})=>({id:t,name:r,executable:i,argv:[...n],cwdRef:a,timeoutMs:o,repeatable:s}))}function XS(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.stage!=="verify-ready")throw new Error("Native Runner check input requires an active Verify-ready candidate")}function Vm(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result")throw new Error("Native Runner Verifier input requires an active Verifier attempt")}function _D(e,t){if(new Set(t).size!==t.length)throw new Error("Native Builder addressed acceptance IDs contain duplicates");let r=new Set(e.acceptance.map(({id:n})=>n)),i=t.filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native Builder addressed acceptance IDs contain unknown IDs: ${i.join(", ")}`)}async function Wm(e){let t=await Ce(L(e.paths,e.state.name)),r=t?.execution;if(t===null||t.basedOnStateVersion!==e.state.state_version||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null)throw new Error("Native Runner Verifier input requires an active Runtime Verifier execution");return r}async function Km(e){let t=await ha({paths:e.paths,state:e.state});if(t.status==="incompatible")throw new Error(t.message);let r=t.status==="repairable-legacy-overlay"?null:await D(e.paths,e.name),i=r!==null&&e.state.phase==="verify"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),n=r!==null&&e.state.phase==="build"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),a=await Le({paths:e.paths,state:e.state}),o=(i||n)&&r?r.integration.worktree:e.projectRoot;if(CD(e.input)&&r===null)throw new Error("Native Supervisor Runner input requires a current Supervisor state");if(r&&RD(e.input)&&!i&&!(e.input.kind==="builder-handoff"&&n))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(e.input.kind==="builder-handoff"){if(e.state.phase!=="build"||e.state.status!=="active")throw new Error("Native Builder input requires an active Build boundary");if(_D(e.state,e.input.addressed_acceptance_ids),$n(e.state.acceptance,e.input.acceptance_review),a&&(!a.confirmed||!a.allDone))throw new Error("Native parent Build advances child changes and does not accept a Builder handoff");if(n&&e.state.loop.stage==="repairing"&&e.state.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first");e.input.verification_checks!==void 0&<(o,e.input.verification_checks);return}if(e.input.kind==="dispatch-verifier"){if(XS(e.state),i&&e.input.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");lt(o,e.input.checks);return}if(e.input.kind==="retry-checks"){if(XS(e.state),e.input.check_ids.length===0||new Set(e.input.check_ids).size!==e.input.check_ids.length)throw new Error("Native check retry list must contain unique IDs");let c=await Ce(L(e.paths,e.name));for(let l of e.input.check_ids){let u=c?.checks.find(d=>d.id===l);if(!u||u.status!=="interrupted")throw new Error(`Native check retry ID is not an interrupted current check: ${l}`);if(!u.repeatable)throw new Error(`Native check ${l} is not repeatable and cannot be retried`);if(u.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${l}`)}return}if(e.input.kind==="verifier-response"){Vm(e.state);let c=await Wm({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");lt(o,PD(e.input));return}if(e.input.kind==="verifier-started"){Vm(e.state);let c=await Wm({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner started input is stale for the current candidate or execution");return}if(e.input.kind==="verifier-execution-error"||e.input.kind==="verifier-unavailable"){Vm(e.state);let c=await Wm({paths:e.paths,state:e.state});if(e.input.stateVersion!==e.state.state_version||e.input.iteration!==e.state.loop.iteration||e.input.attempt!==e.state.loop.attempt||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current attempt");return}let s=e.input;if(s.kind==="supervisor-retry-builder"){if(!r)throw new Error("Native Supervisor Builder retry requires a current Supervisor state");let c=r.children.find(({name:l})=>l===s.child);if(!c)throw new Error(`Native Supervisor child ${s.child} does not exist`);if(s.stateVersion!==r.stateVersion||c.status!=="blocked"||c.task!==null||(c.builderFailureCount??0)<Nr)throw new Error("Native Supervisor Builder retry input is stale or not currently required");return}if(e.input.kind==="supervisor-checks"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:u})=>u)).size!==c.checks.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(c.checks.some(({repeatable:u})=>!u))throw new Error("Native Supervisor checks must be repeatable for safe recovery");let l=r?.children.find(({name:u})=>u===c.child)?.task;if(!l||l.role!=="verifier"||l.runId!==c.runId)throw new Error("Native Supervisor check runId is not current");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");lt(l.projectRoot,c.checks);return}if(e.input.kind==="supervisor-integrate"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:l})=>l)).size!==c.checks.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(c.checks.some(({repeatable:l})=>!l))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");lt(r.integration.worktree,c.checks)}}function tE(e){return`${Se}:${e}:${ZS()}`}function QS(e,t,r,i){if(Ts.resolve(I(e.projectRoot,["rev-parse","--show-toplevel"]))!==Ts.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(I(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!tr(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(I(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function AD(e,t){let r=oe(e.projectRoot),i=Ts.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Ts.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=I(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!tr(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function ma(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Se)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");return e.builder_handoff}function ID(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function rE(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=ma(r),s=ID(r),c=r.acceptance.filter(({result:d})=>d==="pending").map(({id:d})=>d),l=r.acceptance.filter(({id:d})=>c.includes(d)).map(({id:d,source:p,text:h})=>({id:d,source:p,text:h})),u=l.length<=Yh.maxItems&&Buffer.byteLength(JSON.stringify(l),"utf8")<=Yh.maxSerializedBytes;return{coordination:Se,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:le(t,r.name),supervisorStateRef:a?Di(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:d,operation:p,source:h})=>({capability:d,operation:p,ref:h})),acceptanceCount:r.acceptance.length,scopeCount:c.length,scopeIds:c,...u?{acceptance:l}:{},startupInput:{kind:"verifier-started",candidateId:o.candidate_id,verifierExecutionRef:n},detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:o.review?{status:o.review.status,summary:o.review.summary}:null,builderSummary:o.summary.text,runtimeChecks:i.map(d=>({...d})),builderReportedChecks:o.checks.map(d=>({...d})),builderKnownLimits:o.known_limits.map(d=>({...d})),startupInstruction:"As this Verifier, submit the startup receipt first: copy startupInput into a temporary JSON file and run comet native next <change> --runner-input <file> --project-root <projectRoot above>. It records that this Verifier actually started; a repeat submission is accepted without side effects. Read acceptance when included; otherwise follow detailsPageArgs until every scopeId has been read. Then inspect the linked brief and Spec and proceed.",evidenceInstruction:"Independently inspect the current candidate against every scenario in scopeIds exactly once. Runtime checks are bound evidence; Builder-reported checks and review are claims to corroborate, not Runtime receipts. Reuse applicable completed evidence, request only missing or invalidated checks, and do not repeat full suites by default. Use one Verifier for this dispatch; keep it running across wait-tool timeouts. Return the actual scoped findings, risks, and incomplete checks without omitting limitations. Keep using the same CLI executable that produced this dispatch; do not switch to a different PATH installation.",responseInstruction:"Return one acceptance entry for each ID in scopeIds and no other acceptance IDs. Runtime safely filters a known already-passed superset only when every extra entry still reports passed; nonexistent IDs and conflicting out-of-scope results remain invalid."}}async function zm(e){let t=tE("verifier"),r=await Im({paths:e.paths,name:e.name,checks:e.checks,verifierExecutionId:t,...e.supervisor?{projectRoot:e.supervisor.integration.worktree}:{}});return{state:r,checks:e.checks,runtimeCheckExecution:{disposition:e.disposition},requestChecks:null,verifierDispatch:rE({paths:e.paths,state:r,checks:e.checks,verifierExecutionRef:t,supervisor:e.supervisor}),continuation:Y(r,void 0,{verifierExecutionRef:t,verifierStartup:"unconfirmed"})}}async function Gm(e){ma(e.state);let t=await Ce(L(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function iE(e){let t=e.input;e.inputFile&&await Um({paths:e.paths,file:e.inputFile,input:t});let r=await H(e.paths,e.name),i=await ha({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await D(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:f})=>f==="integrated"||f==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:f})=>f==="integrated"||f==="archived");if(n&&t.kind==="supervisor-checks"){let f=await Of({paths:e.paths,parent:e.name,child:t.child,runId:t.runId,plans:t.checks,materials:t.materials,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),m=await D(e.paths,e.name),v=m?.children.find(({name:g})=>g===t.child)?.task;return{state:r,supervisorState:m,supervisorTask:v&&v.runId===t.runId?ri(v,e.name,e.paths.projectRoot):null,checks:[],checkExecution:f,requestChecks:null,verifierDispatch:null,continuation:Y(r)}}if(n&&t.kind==="supervisor-builder-result")return A(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let f=await D(e.paths,e.name);if(!f)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=f.children.find(({name:y})=>y===t.child);if(!m?.task||m.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{QS(m.task,t.candidateCommit,"builder",`comet/supervisor/${f.parent}/${t.child}`)}catch(y){throw await F(e.paths,Co(f,{child:t.child,runId:t.runId,reason:y.message})),y}let v=m.task.projectRoot,g=Sh(f,t),w=Ro(g,{role:"verifier",child:t.child,projectRoot:v,runId:ZS()});await F(e.paths,w.state);let N=await H(e.paths,e.name);return{state:N,supervisorTask:ri(w.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(N)}});if(n&&t.kind==="supervisor-builder-failure")return A(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let f=await D(e.paths,e.name);if(!f)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=f.children.find(({name:w})=>w===t.child);if(!m?.task||m.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let v=ml(f,{child:t.child,runId:t.runId,reason:t.reason});await F(e.paths,v);let g=await H(e.paths,e.name);return{state:g,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(g)}});if(n&&t.kind==="supervisor-retry-builder")return A(e.paths,`retry Native Supervisor Builder task ${t.child}`,async()=>{let f=await D(e.paths,e.name);if(!f)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=xh(f,{child:t.child,expectedStateVersion:t.stateVersion});await F(e.paths,m);let v=await H(e.paths,e.name);return{state:v,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(v)}});if(n&&t.kind==="supervisor-reconnect")return A(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let f=await D(e.paths,e.name);if(!f)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=f.children.find(({name:w})=>w===t.child)?.task;if(!m||m.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{AD(m,`comet/supervisor/${f.parent}/${t.child}`)}catch(w){throw await F(e.paths,Co(f,{child:t.child,runId:t.runId,reason:w.message})),w}let v=kh(f,{child:t.child,runId:t.runId});await F(e.paths,v.state);let g=await H(e.paths,e.name);return{state:g,supervisorState:v.state,supervisorTask:ri(v.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(g)}});if(n&&t.kind==="supervisor-cancel")return A(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let f=await D(e.paths,e.name);if(!f)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=ml(f,{child:t.child,runId:t.runId,reason:t.reason});await F(e.paths,m);let v=await H(e.paths,e.name);return{state:v,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(v)}});if(n&&t.kind==="supervisor-verifier-result")return A(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let f=await D(e.paths,e.name);if(!f)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=f.children.find(({name:N})=>N===t.child);if(!m?.task||m.task.role!=="verifier"||!m.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{QS(m.task,m.candidateCommit,"verifier",`comet/supervisor/${f.parent}/${t.child}`)}catch(N){throw await F(e.paths,Co(f,{child:t.child,runId:t.runId,reason:N.message})),N}let v=t.evidence.receiptRef||t.verdict==="pass"?await Zn({paths:e.paths,parent:e.name,task:m.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!v||v.checks.some(({status:N,exitCode:y})=>N!=="passed"||y!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let g=Eh(f,{...t,evidence:{...t.evidence,checks:v?.checks.map(({name:N,status:y})=>`${N}: ${y}`)??[],execution:structuredClone(m.task)}});await F(e.paths,g);let w=await H(e.paths,e.name);return{state:w,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(w)}});if(n&&t.kind==="supervisor-integrate"){let f=await Lf({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),m=await _s({paths:e.paths,name:e.name,trigger:"v2-integrate"}),v=m.state;return{state:v,supervisorState:f,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:m.parentAdvance,continuation:Y(v)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="retry-checks"||t.kind==="verifier-response"||t.kind==="verifier-started"||t.kind==="verifier-execution-error"||t.kind==="verifier-unavailable"||t.kind==="supervisor-builder-result"||t.kind==="supervisor-builder-failure"||t.kind==="supervisor-reconnect"||t.kind==="supervisor-cancel"||t.kind==="supervisor-verifier-result")&&!a&&!(t.kind==="builder-handoff"&&o))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(t.kind==="builder-handoff"){if(o&&t.verification_checks?.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let m=wh().captureExecutionIdentity({identityProvider:Se,executionRef:tE("builder")}),v=await Am({paths:e.paths,name:e.name,verificationChecks:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{},input:{identity:m,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,acceptanceReview:t.acceptance_review,checks:t.checks,knownLimits:t.known_limits,review:t.review?{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}:null}});if(t.verification_checks!==void 0){let g=await Cs({paths:e.paths,name:e.name,plans:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{}}),w=g.checks.filter(({status:E})=>E==="failed").map(({id:E})=>E),N=g.checks.filter(({status:E})=>E==="interrupted").map(({id:E})=>E),y=t.verification_checks.filter(({id:E,repeatable:b})=>N.includes(E)&&!b).map(({id:E})=>E);if(w.length>0||y.length>0){let E=w.length>0?`Builder handoff Runtime checks failed: ${w.join(", ")}`:`Builder handoff Runtime checks were interrupted and cannot be repeated: ${y.join(", ")}`,b=await nn({paths:e.paths,name:e.name,reason:E,failureBudget:{maxVerifyFailures:e.maxVerifyFailures}});return{state:b,checks:g.checks,runtimeCheckExecution:{disposition:g.disposition},requestChecks:null,verifierDispatch:null,continuation:Y(b)}}return N.length===0?zm({paths:e.paths,name:e.name,checks:g.checks,disposition:g.disposition,supervisor:o?n:null}):{state:g.state,checks:g.checks,runtimeCheckExecution:{disposition:g.disposition},continuationCheckPlans:t.verification_checks,...N.length>0?{continuationRetryCheckIds:N}:{},requestChecks:null,verifierDispatch:null,continuation:Y(g.state,void 0,{...N.length>0?{retryCheckIds:N}:{verificationCheckPlans:t.verification_checks}})}}return{state:v,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(v)}}if(t.kind==="retry-checks"){if(n&&!a)throw new Error("Native Supervisor check retry is only valid after every Child is integrated");let f=await H(e.paths,e.name);ma(f);let m=await Pm({paths:e.paths,name:e.name,checkIds:t.check_ids,...a&&n?{projectRoot:n.integration.worktree}:{}}),v=m.checks.filter(({status:g})=>g==="interrupted").map(({id:g})=>g);if(v.length>0){let w=((await Ce(L(e.paths,e.name)))?.checks??[]).filter(({id:N,status:y,executionCount:E})=>v.includes(N)&&y==="interrupted"&&E>=3).map(({id:N})=>N);if(w.length>0){let N=await nn({paths:e.paths,name:e.name,reason:`Native Runtime checks reached the retry limit after repeated interruptions: ${w.join(", ")}`,failureBudget:{maxVerifyFailures:e.maxVerifyFailures},preserveLocalChecks:!0});return{state:N,checks:m.checks,requestChecks:null,verifierDispatch:null,continuation:Y(N)}}}return v.length===0&&m.checks.every(({status:g})=>g==="passed")?zm({paths:e.paths,name:e.name,checks:m.checks,disposition:"executed",supervisor:a?n:null}):{state:m.state,checks:m.checks,...v.length>0?{continuationRetryCheckIds:v}:{},requestChecks:null,verifierDispatch:null,continuation:Y(m.state,void 0,{retryCheckIds:v.length>0?v:void 0})}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let f=await H(e.paths,e.name);if(f.builder_handoff!==null&&f.builder_handoff.identity_provider!==Se){let w=await nn({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:w,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(w)}}ma(f);let m=await Cs({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}}),v=m.checks,g=v.filter(({status:w})=>w==="interrupted").map(({id:w})=>w);if(g.length>0){let w=t.checks.filter(({id:y,repeatable:E})=>g.includes(y)&&!E).map(({id:y})=>y);if(w.length>0)throw new Error(`Native non-repeatable checks were interrupted and require a new Builder candidate: ${w.join(", ")}`);let N=await H(e.paths,e.name);return{state:N,checks:v,runtimeCheckExecution:{disposition:m.disposition},continuationRetryCheckIds:g,requestChecks:null,verifierDispatch:null,continuation:Y(N,void 0,{retryCheckIds:g})}}return zm({paths:e.paths,name:e.name,checks:v,disposition:m.disposition,supervisor:a?n:null})}if(t.kind==="verifier-started"){let f=await Tm({paths:e.paths,name:e.name,candidateId:t.candidateId,verifierExecutionRef:t.verifierExecutionRef});return{state:f,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(f,void 0,{verifierExecutionRef:t.verifierExecutionRef,verifierStartup:"confirmed"})}}if(t.kind==="verifier-execution-error"){let f=await H(e.paths,e.name);ma(f),await Gm({paths:e.paths,state:f});let m=await jm({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(m)}}if(t.kind==="verifier-unavailable"){let f=await Om({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:f,checks:f.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:Y(f)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await H(e.paths,e.name),c=ma(s),l=await Gm({paths:e.paths,state:s});if(t.candidateId!==c.candidate_id||t.verifierExecutionRef!==l)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");let u=wh(),d=u.captureExecutionIdentity({identityProvider:Se,executionRef:l}),p=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let f=await D(e.paths,e.name);if(!f)throw new Error("Native Supervisor state disappeared before final verification");p=Ki(f)}let h=await $m({paths:e.paths,name:e.name,envelope:u.envelopeVerifierResponse({candidateId:c.candidate_id,identity:d,payload:t.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...a&&n?{projectRoot:n.integration.worktree}:{}});if(a&&h.response.kind==="final-result"){if(h.state.verification_result==="pass"&&(h.checks.length===0||h.checks.some(({status:v})=>v!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let f=p??await D(e.paths,e.name);if(!f)throw new Error("Native Supervisor state disappeared during verification");let m=Yi(f,h.state);return await F(e.paths,m),{...h,supervisorState:m,verifierDispatch:null,continuation:Y(h.state)}}return{...h,verifierDispatch:h.requestChecks===null?null:rE({paths:e.paths,state:h.state,checks:h.checks,verifierExecutionRef:await Gm({paths:e.paths,state:h.state}),supervisor:a?n:null}),continuation:Y(h.state,void 0,{verifierExecutionRef:l,verifierStartup:"confirmed"})}}ji();jn();co();import js from"path";import{realpathSync as vB}from"fs";function nE(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 jr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function aE(e){return e?e.command?`${jr.next} ${e.command}`:e.ask_user?`${jr.next} ${e.ask_user}`:null:null}function oE(e,t){let r=[e.summary],i=aE(e.next);return i&&r.push(i),e.user_message&&r.push("",jr.relay,e.user_message),t!==void 0&&r.push("",jr.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
374
|
+
`)}async function Em(e){let t=le(e.paths,e.state.name),r=e.state.document_constraints_version,i=r===2||r===3,n=r===3,a=[...(await Nm(t,e.state.brief,{strict:!0,compact:i,structure:n})).findings],o="";try{o=(await Z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let s=e.specChanges??e.state.spec_changes,c=s.filter(({operation:d})=>d!=="remove"),l=e.state.spec_changes.filter(({operation:d})=>d!=="remove"),u=new Set(c.map(({capability:d})=>d));if(e.specChanges!==void 0)for(let d of l)u.has(d.capability)||a.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${d.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${d.capability}/spec.md`});let p=s.length>0&&s.every(({operation:d})=>d==="remove");c.length===0&&l.length===0&&!p&&!tD(o)&&a.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:e.state.brief});for(let d of c){let f=`specs/${d.capability}/spec.md`;if(d.source!==f){a.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${f}.`,path:d.source??f});continue}try{let h=(await Z({root:t,ref:f,maxBytes:null,includeHash:!1})).text;a.push(...cS(h,f).findings)}catch(h){a.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${h.message}. Restore the complete file at ${f}.`,path:f})}}return{valid:a.length===0,findings:a}}async function Hu(e){let t=await Em(e);if(!t.valid)throw new la(hS(t.findings,{change:e.state.name,phase:e.state.phase}),t.findings,e.state.name)}function Mt(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale: the change moved on since the referenced response (current phase ${e.state.phase}, next action ${e.state.loop.next_action}, state version ${e.state.state_version}). Run comet native status ${e.state.name} --json and execute its commandAlternatives with --expected-state-version ${e.state.state_version} --expected-action ${e.state.loop.next_action}.`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}async function Du(e){let t=le(e.paths,e.state.name),r=nn.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await ju.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!em.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=nn.join(t,...s.split("/")),l=await ju.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=nn.join(e.paths.specsDir,o.name,"spec.md"),p="create",d=null;try{let v=await ju.lstat(u);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);p="modify",d=Sr((await Z({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(v){if(v.code!=="ENOENT")throw v}let f=`specs/${o.name}/${fb}`,h=nn.join(t,...f.split("/")),m={};try{let v=await ju.lstat(h);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${f}`);let g=await Z({root:t,ref:f,maxBytes:null,includeHash:!1}),w=Do(g.text);if(w.capability!==o.name)throw new Error(`Native delta capability ${w.capability} does not match directory ${o.name}`);let N=d??Sr(""),y=e.state.spec_changes.find(E=>E.capability===o.name);if(y?.delta_source!==void 0){if(y.base_hash!==w.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(w.base_hash!==N)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);m={delta_source:f,base_hash:w.base_hash}}catch(v){if(v.code!=="ENOENT")throw v}a.push({capability:o.name,operation:p,source:s,...m})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Bu(e){let t=le(e.paths,e.state.name),r=await Z({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(bm(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of e.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await Z({root:t,ref:o.source,maxBytes:null,includeHash:!1}),c=s.text,l=null;if(o.delta_source){let u=await Z({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),p=Do(u.text);c=gb(s.text,p);let d="";try{d=(await Z({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(f){if(f.code!=="ENOENT")throw f}if(Sr(d)===p.base_hash){let f=yb({baselineMarkdown:d,delta:p,allowAlreadyApplied:!0});if(Sr(s.text)!==f.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}l=$("comet.native.shape-artifact-content.v1",Ou(u.text))}i.push({capability:o.capability,source:s.ref,markdown:c}),n.push({...o,contentHash:$("comet.native.shape-artifact-content.v1",Ou(s.text,e.state.document_constraints_version!==void 0&&e.state.document_constraints_version!==1)),...l===null?{}:{deltaContentHash:l}})}let a=null;try{let o=await Z({root:t,ref:fS,maxBytes:65536,includeHash:!1}),s=pS(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!e.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let l=nn.relative(e.paths.projectRoot,nn.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll(nn.sep,"/");if(s.current_spec!==l)throw new Error(`Native capability association points to ${s.current_spec}, expected ${l}`);a=$("comet.native.shape-artifact-content.v1",Ou(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:Ll({briefMarkdown:r.text,specs:i,resolveBriefReferences:e.state.document_constraints_version!==void 0&&e.state.document_constraints_version!==1}),formalHash:$("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:$("comet.native.shape-artifact-content.v1",Ou(r.text,e.state.document_constraints_version!==void 0&&e.state.document_constraints_version!==1))},specs:n,association:{source:fS,contentHash:a}})}}function Ss(e){return $("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function xm(e){return A(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"prepare-shape-confirmation"}),t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");let r=e.enforceDocumentConstraints===!0?{...t,document_constraints_version:3}:t,i=await Du({paths:e.paths,state:t});e.enforceDocumentConstraints===!0&&await Hu({paths:e.paths,state:r,specChanges:i});let n=await Bu({paths:e.paths,state:r,specChanges:i}),{acceptance:a}=n,o=await Je({changeDir:le(e.paths,t.name),acceptanceIds:a.map(({id:f})=>f),validation:bt({...t,acceptance:a})}),s=t;if(o&&t.workspace.change_branch===null){await Nl(e.paths,t.name);let f=Ru(t.workspace,e.paths.projectRoot);if(f===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");s=ke({...t,workspace:f},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${f.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let c=await ls(le(e.paths,t.name))||o?.contract.schema==="comet.native.children.v2"&&o.contract.children.length>=2;if(c&&!o)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let l=c?e.coordinationMode??t.coordination_mode:void 0;if(!c&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let u={...s,...r.document_constraints_version===void 0?{}:{document_constraints_version:r.document_constraints_version},spec_changes:i,shape_confirmation_hash:Ss({formalHash:n.formalHash,childrenHash:o?.hash??null,coordinationMode:l})};delete u.children_contract_hash,delete u.coordination_mode,c&&(u.coordination_mode=l);let p=Sk({state:u,acceptance:a.map(f=>({...f}))});o&&(p.children_contract_hash=ta({acceptance:p.acceptance,children:o.contract}));let d=await fe({paths:e.paths,previous:t,next:p});return await M(L(e.paths,t.name),ae({portableState:d,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),d})}async function Es(e){if(e.state.document_constraints_version!==void 0){let l=await Em(e);if(!l.valid){let u=l.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let t=await Du(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,u)=>{let p=e.state.spec_changes[u];return p!==void 0&&l.capability===p.capability&&l.source===p.source&&l.delta_source===p.delta_source&&l.base_hash===p.base_hash&&(l.operation===p.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await Bu({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:u})=>({source:l,text:u}));if(!Wb(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Je({changeDir:le(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:bt({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&Ss({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?ta({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Ze(e){let t=await Es(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Rs({paths:e.paths,state:e.state,reason:r,keepFailureBudget:!0}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function xs(e){return A(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:Rs({paths:e.paths,state:t,reason:e.reason,...e.keepFailureBudget?{keepFailureBudget:!0}:{}})})}async function Rs(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...ke(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:e.keepFailureBudget?t.loop.failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await fe({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}function Mu(e,t){let r=O.relative(O.resolve(e),O.resolve(t));if(O.isAbsolute(r)||r===".."||r.startsWith(`..${O.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(O.sep).join("/");return To(e,i),i}function rD(e){return e.split("\0").some(t=>t.startsWith("160000 "))}function Lu(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return qn({id:e.id,name:e.name,executable:r,argv:i,cwdRef:Mu(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function yS(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:Mu(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function bS(e,t,r,i,n,a){return e.candidateId!==i.builder_handoff?.candidate_id||e.inputFingerprint!==n||O.resolve(e.workspace.projectRoot)!==O.resolve(r)||O.resolve(e.workspace.worktreeRoot)!==O.resolve(r)||e.workspace.branch!==a||e.workspace.machineId!==Tr.hostname()||e.checks.length!==t.length?!1:e.checks.every((o,s)=>Lu(o,r)===qn(t[s]))}function Cm(e,t,r){return e.checks.length===t.length&&e.checks.every((i,n)=>Lu(i,r)===qn(t[n]))}async function Fu(e){let t=e.execution;if(t===null||t.status!=="running")return"not-running";if(t.ownerPid===void 0)return"unknown";let r=await Ln(t.ownerPid,t.ownerIdentity);if(r==="alive")return"running";let i=r==="unknown";for(let n of e.checks){if(n.status!=="running")continue;let a=n.activeProcess;if(!a||a.status==="starting"){i=!0;continue}let o=await Ln(a.pid,a.identity);if(o==="alive")return"running";o==="unknown"&&(i=!0)}return i?"unknown":"orphaned"}function mS(e){return{...e,execution:e.execution===null?null:{...e.execution,status:"interrupted"},checks:e.checks.map(t=>t.status==="planned"||t.status==="running"?{...t,status:"interrupted",activeProcess:null}:t)}}function qu(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:To(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`,activeProcess:null}}function iD(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return _m(e,t,r,i)}function _m(e,t,r,i){return{...qu(t,r,i),executionCount:e.executionCount}}function NS(e){return gS("sha256").update(e).digest("hex")}async function _s(e){let t=await ur.lstat(e);if(!t.isFile())throw new Error("Native check input must be a regular file");let r=gS("sha256"),i=await ur.open(e,"r"),n=0;try{let o=Buffer.allocUnsafe(nD);for(;;){let{bytesRead:s}=await i.read(o,0,o.length,null);if(s===0)break;n+=s,r.update(o.subarray(0,s).toString("base64"))}}finally{await i.close()}let a=await ur.lstat(e);if(a.size!==t.size||a.mtimeMs!==t.mtimeMs)throw new Error("Native check input changed while reading");return{digest:r.digest("hex"),size:n}}var kS=2e4,SS=1024*1024*1024,nD=65535,ES=["build","dist","gen","generated","out","target",".next",".nuxt",".output",".svelte-kit"],aD=new Set([".agents",".cache",".claude",".codex",".comet",".git",".idea",".next",".nuxt",".output",".parcel-cache",".svelte-kit",".tmp",".turbo",".vscode",".worktrees","coverage","logs","node_modules","temp","tmp"]),Rm=[":(exclude).comet/runtime/**",":(exclude).comet/current-change.json"],xS=new Set(["comet-state.yaml","children.yaml","verification.md"]);function RS(e,t){if(!t)return[...Rm];let r=O.relative(e,t).replaceAll("\\","/");if(O.isAbsolute(r)||r===".."||r.startsWith("../"))return[...Rm];let i=r===""?"":`${r}/`;return[...Rm,...["changes","archive"].flatMap(n=>[...xS].map(a=>`:(exclude)${i}comet/${n}/**/${a}`))]}function Am(e,t,r){let i=e.replaceAll("\\","/").replace(/^\.\//u,"");if(i===".comet/current-change.json"||i.startsWith(".comet/runtime/"))return!0;if(!t||!r||!xS.has(O.basename(i)))return!1;let n=O.resolve(t,...i.split("/")),a=O.relative(O.resolve(r),n);if(O.isAbsolute(a)||a===".."||a.startsWith(`..${O.sep}`))return!1;let[,o]=a.split(O.sep);return a.startsWith(`comet${O.sep}`)&&(o==="changes"||o==="archive")}function da(){return{complete:!1,files:[]}}function oD(e){let t=e==="."?"":`${e}/`;return ES.flatMap(r=>[`:(glob)${t}${r}/**`,`:(glob)${t}**/${r}/**`])}function CS(e){return/(?:^|\/)(?:\.env(?:\..*)?|[^/]+\.(?:key|pem|p12|pfx))$/iu.test(e)}async function PS(e,t,r,i=new Set){let n=[...new Set(t.map(({cwdRef:c})=>c))];if(n.length===0)return{complete:!0,files:[]};let a;try{a=[...new Set(I(e,["ls-files","--others","--ignored","--exclude-standard","-z","--",...n.flatMap(oD)]).split("\0").filter(Boolean).map(c=>c.replaceAll("\\","/")))].sort()}catch{return da()}if(a.length>kS)return da();let o=[],s=0;for(let c of a){if(i.has(c)||Am(c,e,r))continue;let l=O.resolve(e,...c.split("/"));if(!Ee(e,l)||CS(c))return da();try{let u=await ur.lstat(l);if(!u.isFile()||s+u.size>SS)return da();let{digest:p,size:d}=await _s(l);s+=d,o.push({path:c,digest:p,size:d})}catch{return da()}}return{complete:!0,files:o}}async function sD(e,t,r,i=new Set){let n=[...new Set(t.map(({cwdRef:l})=>l))],a=new Map,o=0,s=l=>ES.includes(l),c=async(l,u,p)=>{let d;try{d=await ur.readdir(l,{withFileTypes:!0})}catch{return!1}d.sort((f,h)=>f.name.localeCompare(h.name,"en"));for(let f of d){let h=u?`${u}/${f.name}`:f.name;if(i.has(h)||Am(h,e,r)||f.isDirectory()&&aD.has(f.name))continue;let m=O.join(l,f.name);if(f.isDirectory()){if(!await c(m,h,p||s(f.name)))return!1;continue}if(p){if(CS(h)||!f.isFile())return!1;try{let v=await ur.lstat(m);if(o+v.size>SS)return!1;let{digest:g,size:w}=await _s(m);if(o+=w,a.set(h,{path:h,digest:g,size:w}),a.size>kS)return!1}catch{return!1}}}return!0};for(let l of n){let u=To(e,l);if(!await c(u,l==="."?"":l,s(O.basename(u))))return da()}return{complete:!0,files:[...a.values()].sort((l,u)=>l.path.localeCompare(u.path,"en"))}}function Im(e,t){return $("comet.native.local-check-evidence.v1",{id:e.id,name:e.name,status:e.status,repeatable:e.repeatable,timeoutMs:e.timeoutMs,argv:e.argv,cwd:O.resolve(e.cwd),exitCode:e.exitCode,startedAt:e.startedAt,completedAt:e.completedAt,log:e.log,logDigest:NS(t)})}async function _S(e){let t=await zh(e.projectRoot),r=[...RS(e.projectRoot,e.managedArtifactRoot),...[...t].map(a=>`:(exclude,literal)${a}`)],i={complete:!0,capture:"git",head:null,branch:null,status:null,diff:null,stagedDiff:null,submodules:null,untracked:[],ignored:{complete:!0,files:[]},physical:{complete:!0,files:[]},reuseNonce:null},n=!1;try{i.head=I(e.projectRoot,["rev-parse","HEAD"]),n=!0,i.branch=I(e.projectRoot,["branch","--show-current"]),i.status=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...r]);let a=I(e.projectRoot,["diff","--name-only","-z","HEAD","--",...r]).split("\0").filter(Boolean).sort();i.diff=await Zh(a,4,async c=>{let l=O.resolve(e.projectRoot,...c.split("/"));try{let{digest:u}=await _s(l);return{path:c,digest:u}}catch{return{path:c,digest:null}}}),i.diff.some(({digest:c})=>c===null)&&(i.complete=!1);let o=I(e.projectRoot,["ls-files","--stage","-z","--",...r]);i.stagedDiff=NS(o),i.submodules=rD(o)?I(e.projectRoot,["submodule","status","--recursive"]):"";let s=I(e.projectRoot,["ls-files","--others","--exclude-standard","-z","--",...r]).split("\0").filter(Boolean).sort();i.untracked=await Zh(s,4,async c=>{let l=O.resolve(e.projectRoot,...c.split("/"));try{let{digest:u,size:p}=await _s(l);return{path:c,digest:u,size:p}}catch{return{path:c,digest:null,size:null}}}),i.untracked.some(({digest:c})=>c===null)&&(i.complete=!1),i.ignored=await PS(e.projectRoot,e.plans,e.managedArtifactRoot,t),i.ignored.complete||(i.complete=!1)}catch{n?i.complete=!1:(i.capture="physical-tree",i.physical=await sD(e.projectRoot,e.plans,e.managedArtifactRoot,t),i.complete=i.physical.complete)}return $("comet.native.check-input.v1",{candidateId:e.state.builder_handoff?.candidate_id??null,shapeConfirmationHash:e.state.shape_confirmation_hash??null,acceptance:e.state.acceptance.map(({id:a,source:o,text:s})=>({id:a,source:o,text:s})),git:i,projectRoot:O.resolve(e.projectRoot),machineId:Tr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,path:process.env.PATH??null,pathext:process.env.PATHEXT??null,boundEnvironment:Object.entries(process.env).filter(([a])=>AS.has(a.toUpperCase())).map(([a,o])=>[a,o??null]).sort(([a],[o])=>a.localeCompare(o))})}var AS=new Set(["PATH","PATHEXT","NODE_OPTIONS","NODE_ENV","NODE_PATH","LANG","LC_ALL","HOME","USERPROFILE","SYSTEMROOT","COMSPEC","SHELL","TMPDIR","TEMP","TMP","HTTP_PROXY","HTTPS_PROXY","NO_PROXY"]);function cD(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function lD(){return Object.entries(process.env).filter(([e])=>AS.has(e.toUpperCase())).map(([e,t])=>[e,t??null]).sort(([e],[t])=>e.localeCompare(t))}async function IS(e){try{let t=await zh(e.projectRoot),r=[...RS(e.projectRoot,e.managedArtifactRoot),...[...t].map(c=>`:(exclude,literal)${c}`)],i=I(e.projectRoot,["rev-parse","HEAD"]),n=I(e.projectRoot,["branch","--show-current"]),a=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...r]),o=I(e.projectRoot,["ls-files","--stage","-z","--",...r]);if(i===null||a===null)return null;let s=[];for(let c of Za(e.projectRoot).filter(l=>!t.has(l)&&!Am(l,e.projectRoot,e.managedArtifactRoot))){let l=O.resolve(e.projectRoot,...c.split("/")),u=null;try{u=(await _s(l)).digest}catch{return null}s.push({path:c,digest:u})}return s.sort((c,l)=>c.path.localeCompare(l.path,"en")),{runnerInputs:t,binding:{candidateId:e.candidateId,head:i,branch:n,status:a,staged:o,workingTree:s,projectRoot:O.resolve(e.projectRoot),machineId:Tr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,boundEnvironment:lD()}}}catch{return null}}async function Pm(e,t){if(t===null)return null;try{let r=await PS(e.projectRoot,e.plans??[],e.managedArtifactRoot,t.runnerInputs);return r.complete?$("comet.native.check-input-gate.v1",{...t.binding,ignored:r}):null}catch{return null}}async function vS(e){return Pm(e,await IS(e))}async function TS(e){let t=await IS(e);return{branch:t===null?ge(e.projectRoot):t.binding.branch||null,gate:await Pm(e,t),candidateGate:await Pm({...e,plans:[]},t)}}function vi(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);if(r.status==="passed"&&(r.evidence!=="runtime"||!r.evidenceDigest))throw new Error(`Native Runtime check ${r.id} has no Runtime execution evidence`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:J(i),argv_display:$o(r.argv.slice(1)).map(n=>J(n)),argv_truncated:!1,cwd_ref:Mu(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:cD(r)}})}function uD(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function gi(e){if(e.local===null||e.local.change!==e.state.name)return ae({portableState:e.state,projectRoot:e.projectRoot,branch:ge(e.projectRoot)});let t=e.local.execution?.operationId??wS();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function $r(e){try{let t=await Ce(L(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}async function Tm(e){let t=await $r({paths:e.paths,state:e.state}),r=Ik({state:e.state,summary:e.summary}),i=await fe({paths:e.paths,previous:e.state,next:r});return await M(L(e.paths,e.state.name),gi({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}async function $S(e,t){for(let r of e.checks)if(r.status==="passed"){if(r.evidence!=="runtime")return!1;try{let i=await G(t,O.resolve(t,...r.log.split(/[\\/]/u)));if(!(await ur.stat(i)).isFile())return!1;let n=await ur.readFile(i,"utf8");if(!r.evidenceDigest||r.evidenceDigest!==Im(r,n))return!1}catch{return!1}}return!0}async function jS(e){let{local:t,previous:r,next:i,plans:n,paths:a}=e;if(!t||!t.checks.length||t.checks.some(({status:s})=>s!=="passed")||t.basedOnStateVersion!==r.state_version||t.candidateId!==r.builder_handoff?.candidate_id||t.workspace.machineId!==Tr.hostname()||t.inputFingerprint==null||t.inputFingerprintGate==null||t.execution?.stage==="checking"&&t.execution.status==="running"||r.shape_confirmation_hash!==i.shape_confirmation_hash||JSON.stringify(r.acceptance.map(({id:s,source:c,text:l})=>({id:s,source:c,text:l})))!==JSON.stringify(i.acceptance.map(({id:s,source:c,text:l})=>({id:s,source:c,text:l}))))return null;let o=t.workspace.worktreeRoot;if(O.resolve(t.workspace.projectRoot)!==O.resolve(e.projectRoot??a.projectRoot)||O.resolve(o)!==O.resolve(e.projectRoot??a.projectRoot))return null;try{if(t.workspace.branch!==ge(o)||!Cm(t,n,o)||!await $S(t,me(a,i.name)))return null;let s={projectRoot:o,candidateId:t.candidateId??null,plans:n,managedArtifactRoot:a.artifactRoot},c=await vS(s);if(c===null||c!==t.inputFingerprintGate)return null;let l=await _S({state:i,projectRoot:o,plans:n,managedArtifactRoot:a.artifactRoot}),u=await TS({...s,candidateId:i.builder_handoff.candidate_id});return u.gate===null||u.candidateGate===null||await vS(s)!==c?null:{...gi({local:t,state:i,projectRoot:a.projectRoot}),candidateId:i.builder_handoff.candidate_id,inputFingerprint:l,inputFingerprintGate:u.gate,candidateInputFingerprintGate:u.candidateGate}}catch{return null}}async function dD(e){return A(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let{gate:r,candidateGate:i,branch:n}=await TS({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),a=n,o=L(e.paths,t.name),s=(await Eu({file:o,portableState:t,projectRoot:e.projectRoot,branch:a,containedRoot:e.paths.runtimeDir})).state;a!==null&&s.workspace.branch===`heads/${a}`&&(a=ge(e.projectRoot));let c=r===null,u=r!==null&&s.inputFingerprint!==null&&s.inputFingerprintGate===r&&s.candidateInputFingerprintGate===i&&s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.machineId===Tr.hostname()?s.inputFingerprint:await _S({state:t,projectRoot:e.projectRoot,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),p=me(e.paths,t.name),d=await $S(s,p),f=s.checks.every(S=>S.status==="passed"),h=e.retryCheckIds===void 0?null:new Set(e.retryCheckIds),m=s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.branch===a&&s.workspace.machineId===Tr.hostname()&&s.inputFingerprint===u,v=i!==null&&s.candidateInputFingerprintGate===i&&s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.branch===a&&s.workspace.machineId===Tr.hostname(),g=v&&s.inputFingerprint!==null&&s.inputFingerprint!==u,w=bS(s,e.plans,e.projectRoot,t,u,a)||v&&Cm(s,e.plans,e.projectRoot),N=s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.branch===a&&s.workspace.machineId===Tr.hostname(),y=m&&f&&!d;if(h&&h.size===0)throw new Error("Native check retry list must contain at least one ID");if(!m&&s.execution?.stage==="checking"&&s.execution.actor==="runtime"&&s.execution.status==="running"){let S=await Fu(s);if(S!=="orphaned")throw new Error(S==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before changing its binding":"Native check plan is already in progress on another workspace binding");s=mS(s),await M(o,s,{containedRoot:e.paths.runtimeDir})}if(!m&&N&&s.inputFingerprint!==null&&(s.execution!==null||s.checks.length>0)){let S=s.inputFingerprint!==u;if(!(c&&!S||g)){let C=pi({state:t,reason:"Native check input changed after the candidate was built; a new Builder candidate is required before checks can run again."}),P=await fe({paths:e.paths,previous:t,next:C});throw await M(o,ae({portableState:P,projectRoot:e.paths.projectRoot,branch:a}),{containedRoot:e.paths.runtimeDir}),new Error("Native check input changed after the candidate was built; the change returned to Build for a new candidate")}}if(!m&&!v){let S=ae({portableState:t,projectRoot:e.projectRoot,branch:a});await M(o,S,{containedRoot:e.paths.runtimeDir}),s=S}let E=Cm(s,e.plans,e.projectRoot);if(s.execution?.stage==="checking"&&s.execution.actor==="runtime"&&E&&w){let S=s.execution;if(S.status==="running"){let P=await Fu(s);if(P!=="orphaned")throw new Error(P==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before retrying":"Native check plan is already in progress");s=mS(s),await M(o,s,{containedRoot:e.paths.runtimeDir}),S=s.execution}let C=s.checks.filter(P=>P.status==="interrupted");if(C.length===0&&S.status==="completed"&&f&&!y&&!g){let P=new Map(e.plans.map(({id:_,name:j})=>[_,j]));return{kind:"reuse",state:t,checks:vi({local:s,projectRoot:e.projectRoot,supplied:[],requestedNames:P})}}if(C.length===0&&S.status==="completed"&&!f&&!y&&!g)throw new Error(`Native check plan contains a failed check (${s.checks.filter(({status:P})=>P==="failed").map(({id:P})=>P).join(", ")}); submit a new Builder candidate`);if(C.length>0&&C.some(P=>!P.repeatable)&&!y){let P=pi({state:t,reason:`A non-repeatable Runtime check was interrupted (${C.filter(j=>!j.repeatable).map(({id:j})=>j).join(", ")}); a new Builder candidate is required before it can run again.`}),_=await fe({paths:e.paths,previous:t,next:P});throw await M(L(e.paths,t.name),ae({portableState:_,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${C.find(j=>!j.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}if(C.length>0&&h===null&&!y&&!g){let P=new Map(e.plans.map(({id:_,name:j})=>[_,j]));return{kind:"reuse",state:t,checks:vi({local:s,projectRoot:e.projectRoot,supplied:[],requestedNames:P})}}if(h){let P=[...h].filter(j=>!C.some(ue=>ue.id===j));if(P.length>0)throw new Error(`Native check retry IDs must refer to interrupted checks: ${P.join(", ")}`);let _=C.filter(j=>h.has(j.id)&&j.executionCount>=3);if(_.length>0)throw new Error(`Native check retry limit (3) reached: ${_.map(({id:j})=>j).join(", ")}`)}}if(s.execution!==null&&s.checks.length>0){if(!(s.execution.stage==="checking"&&s.execution.actor==="runtime"&&s.checks.some(C=>C.status==="interrupted")&&E)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan")}else if((s.execution!==null||s.checks.length>0)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan");let b=wS(),x=await ct(process.pid),k={...s,candidateId:t.builder_handoff?.candidate_id??null,inputFingerprint:u,inputFingerprintGate:r,candidateInputFingerprintGate:i,workspace:{...s.workspace,projectRoot:O.resolve(e.projectRoot),worktreeRoot:O.resolve(e.projectRoot),branch:ge(e.projectRoot),machineId:Tr.hostname()},execution:{operationId:b,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0,ownerPid:process.pid,...x?{ownerIdentity:x}:{}},checks:e.plans.map(S=>{let C=s.checks.find(P=>P.id===S.id);return g&&C?qu(S,b,e.projectRoot):y&&C?_m(C,S,b,e.projectRoot):C?.status==="interrupted"&&(h===null||h.has(C.id))?iD(C,S,b,e.projectRoot):C?{...C,operationId:b,activeProcess:null}:qu(S,b,e.projectRoot)})};return await M(o,k,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:k,plans:e.plans.filter(S=>{let C=s.checks.find(P=>P.id===S.id);return y||g||C===void 0||C.status==="interrupted"&&(h===null||h.has(C.id))})}})}async function Cs(e){return A(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await H(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=L(e.paths,t.name),i=await Ce(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await M(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function As(e){let t=e.projectRoot??e.paths.projectRoot;lt(t,e.plans);let r=[],i=new Set;for(let c of e.plans){jo(t,c);let l=qn(c);i.has(l)||(i.add(l),r.push(c))}let n=await dD({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return{...n,disposition:"reused"};let a=n.local.execution.operationId,o=me(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await Cs({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(f=>f.id===c.id?{...f,status:"running",executionCount:f.executionCount+1,startedAt:l,activeProcess:{status:"starting"}}:f)})});let u=await Bi({projectRoot:t,runtimeDir:o,operationId:a,plan:c,onSpawn:async({pid:d})=>{let f=await ct(d);await Cs({paths:e.paths,state:n.state,operationId:a,update:h=>({...h,checks:h.checks.map(m=>m.id===c.id?{...m,activeProcess:{status:"running",pid:d,...f?{identity:f}:{}}}:m)})})}}),p=await ur.readFile(O.resolve(o,...u.logRef.split("/")),"utf8");await Cs({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(f=>{if(f.id!==c.id)return f;let h={...f,status:u.status,exitCode:u.exitCode,startedAt:u.startedAt,completedAt:u.completedAt,log:u.logRef,activeProcess:null,evidence:"runtime"};return{...h,evidenceDigest:Im(h,p)}})})})}await Cs({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await Cs({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted",activeProcess:null}:u)})})}catch{}throw c}let s=await Ce(L(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:vi({local:s,projectRoot:t,supplied:[]}),disposition:"executed"}}async function $m(e){if(e.checkIds.length===0)throw new Error("Native check retry list must contain at least one ID");let t=e.projectRoot??e.paths.projectRoot,r=await H(e.paths,e.name);if(r.phase!=="verify"||r.status!=="active"||r.loop.stage!=="verify-ready"||r.builder_handoff===null)throw new Error("Native check retry requires an active Verify-ready candidate");let i=await Ce(L(e.paths,e.name));if(i===null||i.change!==r.name||i.basedOnStateVersion!==r.state_version||i.execution===null||i.execution.stage!=="checking"||i.execution.actor!=="runtime")throw new Error("Native check retry has no current Runtime check execution");let n=new Set(e.checkIds);if(n.size!==e.checkIds.length)throw new Error("Native check retry list contains duplicate IDs");let a=i.checks.filter(c=>n.has(c.id)),o=e.checkIds.filter(c=>!a.some(l=>l.id===c));if(o.length>0)throw new Error(`Native check retry IDs are unknown: ${o.join(", ")}`);for(let c of a){if(c.status!=="interrupted")throw new Error(`Native check ${c.id} is not interrupted and cannot be retried`);if(!c.repeatable)throw new Error(`Native check ${c.id} is not repeatable and cannot be retried`);if(c.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${c.id}`)}let s=i.checks.map(c=>{let[l,...u]=c.argv;if(!l)throw new Error(`Native local check ${c.id} has no executable`);return{id:c.id,name:c.name,executable:l,argv:u,cwdRef:Mu(t,c.cwd),timeoutMs:c.timeoutMs,repeatable:c.repeatable}});return As({paths:e.paths,name:e.name,plans:s,projectRoot:t,retryCheckIds:e.checkIds})}async function OS(e){let t=L(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=Jh)throw new Error(`Native Verifier request-checks exceeded ${Jh} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let f of r.checks){let h=Lu(f,e.projectRoot);n.set(h,f),f.status==="passed"&&i.set(h,f),a.set(f.id,h)}let o=new Map,s=new Map;for(let f of e.response.checks){let h=uD(f);jo(e.projectRoot,h);let m=qn(h),v=s.get(h.id);if(v!==void 0&&v!==m)throw new Error(`Native Verifier check ID ${h.id} refers to conflicting commands`);let g=a.get(h.id);if(g!==void 0&&g!==m)throw new Error(`Native Verifier check ID ${h.id} conflicts with a Runtime check`);s.set(h.id,m);let w=n.get(m);if(w&&w.status!=="passed"&&!w.repeatable)throw new Error(`Native check ${w.id} did not pass and is not repeatable; user resolution is required`);if(w&&w.status!=="passed"&&w.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${w.id}`);o.has(m)||o.set(m,h)}lt(e.projectRoot,[...o.values()]);let c=[...o.entries()],l=c.filter(([f])=>!i.has(f));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let u=r.execution.requestCheckRounds+1,p=new Map(c.map(([,f])=>[f.id,f.name])),d={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...r.checks.map(f=>{let h=Lu(f,e.projectRoot),m=o.get(h);return m&&f.status!=="passed"?_m(f,m,r.execution.operationId,e.projectRoot):f}),...l.filter(([f])=>!n.has(f)).map(([,f])=>qu(f,r.execution.operationId,e.projectRoot))]};return await M(t,d,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:d,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,f])=>f),requestedNames:p,reusedCheckIds:c.filter(([f])=>i.has(f)).map(([,f])=>f.id),suppliedChecks:e.suppliedChecks}}async function Ps(e){return A(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await H(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=L(e.paths,t.name),i=await Ce(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await M(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function HS(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await Ps({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>c.id===r.id?{...c,status:"running",executionCount:c.executionCount+1,startedAt:i,activeProcess:{status:"starting"}}:c)})});let n=me(e.paths,e.reservation.state.name),a=await Bi({projectRoot:e.projectRoot,runtimeDir:n,operationId:e.reservation.local.execution.operationId,plan:r,onSpawn:async({pid:s})=>{let c=await ct(s);await Ps({paths:e.paths,reservation:e.reservation,update:l=>({...l,checks:l.checks.map(u=>u.id===r.id?{...u,activeProcess:{status:"running",pid:s,...c?{identity:c}:{}}}:u)})})}}),o=await ur.readFile(await G(n,O.resolve(n,...a.logRef.split(/[\\/]/u))),"utf8");t=await Ps({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>{if(c.id!==r.id)return c;let l={...c,status:a.status,exitCode:a.exitCode,startedAt:a.startedAt,completedAt:a.completedAt,log:a.logRef,activeProcess:null,evidence:"runtime"};return{...l,evidenceDigest:Im(l,o)}})})})}t=await Ps({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await Ps({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted",activeProcess:null}:n)})})}catch{}throw r}return{checks:vi({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}import{accessSync as C6,constants as P6,promises as FS}from"node:fs";import fa from"node:path";ne();var pD=hr(Gt(),1);We();pe();rt();at();bn();We();gt();ve();gt();ve();Hi();kr();at();ni();async function jm(e){return A(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"confirm-shape"}),t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native Shape can only be confirmed from the persisted user confirmation boundary");if(e.coordinationMode!==void 0&&t.coordination_mode!==void 0&&e.coordinationMode!==t.coordination_mode)throw new Error("--coordination-mode is already bound to this Shape confirmation; revise Shape before changing it");await Ze({paths:e.paths,state:t});let r=await Du({paths:e.paths,state:t}),i=await Bu({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Je({changeDir:le(e.paths,t.name),acceptanceIds:n.map(({id:g})=>g),validation:bt({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await Nl(e.paths,t.name);let g=Ru(t.workspace,e.paths.projectRoot);if(g===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");o=ke({...t,workspace:g},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${g.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await ls(le(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,c=e.coordinationMode??t.coordination_mode;if(!s&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");if(s&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(s&&c===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let l=Ss({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:t.coordination_mode});if(t.shape_confirmation_hash===void 0||l!==t.shape_confirmation_hash){let g=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await Rs({paths:e.paths,state:t,reason:g,keepFailureBudget:!0}),new Error(`${g}; Native change returned to Shape and requires confirmation`)}let u=kk({state:{...o,spec_changes:r,shape_confirmation_hash:Ss({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c})},acceptance:n.map(g=>({...g}))});if(delete u.children_contract_hash,delete u.coordination_mode,a){u.children_contract_hash=ta({acceptance:u.acceptance,children:a.contract}),s&&(u.coordination_mode=c);let g=[...t.history].reverse().find(({outcome:w})=>w==="pass"||w==="fail");if(g?.outcome==="fail"&&g.unresolved_ids.length>0){let w=await Le({paths:e.paths,state:u}),N=new Map((w?.children??[]).map(({name:b,status:x})=>[b,x])),y=new Set(a.contract.children.filter(({name:b})=>{let x=N.get(b);return x!=="done"&&x!=="integrated"&&x!=="archived"}).flatMap(({covers:b})=>b)),E=g.unresolved_ids.filter(b=>!y.has(b));if(E.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${E.join(", ")}`)}}let p=null,d=a?.contract.schema==="comet.native.children.v2"?await D(e.paths,t.name):null,f=null,h=null;if(a?.contract.schema==="comet.native.children.v2"){if(f=o.workspace.change_branch??o.workspace.target_branch,!f)throw new Error("Native Supervisor v2 requires a target branch");if(h=wr(e.paths.projectRoot,f),!h)throw new Error(`Native Supervisor target branch has no commit: ${f}`);d||(d=await cs({paths:e.paths,parent:t.name,targetBranch:f,contract:a.contract})),d||(p=await Fh({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:f,sourceConfig:await Oe(e.paths.projectRoot)}))}let m=a?.contract.schema==="comet.native.children.v2"&&f&&h?d?Ef({state:d,contract:a.contract}):p?Ro({parent:u.name,targetBranch:f,targetCommit:h,integrationBranch:p.binding.changeBranch,integrationWorktree:p.projectRoot,contract:a.contract}):null:null;if(a?.contract.schema==="comet.native.children.v2"&&!m)throw new Error("Native Supervisor integration state is unavailable");let v=await fe({paths:e.paths,previous:t,next:u});return await M(L(e.paths,t.name),ae({portableState:v,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),m&&await q(e.paths,m),v})}import{randomUUID as fD}from"node:crypto";import Vu from"node:path";ve();So();ji();function DS(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function hD(e){let{state:t,local:r,envelope:i}=e;if(!ml(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function mD(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Om(e){return A(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),await Je({changeDir:le(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:o})=>o),validation:bt(t)})||t.children_contract_hash){let o=await Le({paths:e.paths,state:t});if(!o?.confirmed||!o.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=Ek({state:t,input:e.input}),n=e.verificationChecks===void 0?null:await jS({paths:e.paths,previous:t,next:i,plans:e.verificationChecks,projectRoot:e.projectRoot,local:await $r({paths:e.paths,state:t})}),a=await fe({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),n??ae({portableState:a,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a})}async function Hm(e){return A(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Ze({paths:e.paths,state:t});let i=(await Eu({file:L(e.paths,t.name),portableState:t,projectRoot:r,branch:ge(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");vi({local:i,projectRoot:r,supplied:e.checks});let n=xk(t),a=await fe({paths:e.paths,previous:t,next:n}),o=L(e.paths,t.name),s=fD();return await M(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function Dm(e){return A(e.paths,`confirm portable verifier start ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier start confirmation requires an active Verifier attempt");let r=L(e.paths,e.name),i=await Ce(r),n=i?.execution;if(i===null||i.change!==t.name||i.basedOnStateVersion!==t.state_version||!n||n.stage!=="verifying"||n.actor!=="verifier"||n.status!=="running"||n.executionId===null||n.executionId!==e.verifierExecutionRef)throw new Error("Native Verifier start confirmation is stale for the current attempt");if(t.builder_handoff?.candidate_id!==e.candidateId)throw new Error("Native Verifier start confirmation is stale for the current candidate");return n.verifierStartedAt===void 0&&await M(r,{...i,execution:{...n,verifierStartedAt:new Date().toISOString()}},{containedRoot:e.paths.runtimeDir}),t})}async function Bm(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await A(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await H(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Ze({paths:e.paths,state:r});let n=await $r({paths:e.paths,state:r}),a=hD({state:r,local:n,envelope:e.envelope}),o;try{o=ko(a.payload)}catch(p){throw new Error(`Native Verifier response was rejected: ${p.message}; correct the response and continue the same active Verifier`,{cause:p})}let s=mD(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=vi({local:n,projectRoot:i,supplied:e.checks}));let p=Rk({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(p.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await OS({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:p.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:p.response,reservation:d}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=p}catch(p){throw new Error(`Native Verifier response was rejected: ${p.message}; correct the response or request missing checks using the same active Verifier`,{cause:p})}let u=await fe({paths:e.paths,previous:r,next:l.state});return await M(L(e.paths,r.name),gi({local:n,state:u,projectRoot:i}),{containedRoot:e.paths.runtimeDir}),u.verification!==null&&await hi({file:Vu.join(le(e.paths,r.name),"verification.md"),state:u}),{kind:"final-result",result:{state:u,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await HS({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier-requested check execution failed: ${r.message}`,n=await A(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await H(e.paths,e.name);return a.state_version!==t.state.state_version?null:Tm({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Gh} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Lm(e){return A(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await H(e.paths,e.name),r=await $r({paths:e.paths,state:t});if(DS({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return Tm({paths:e.paths,state:t,summary:e.summary})})}async function Fm(e){return A(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let r=await $r({paths:e.paths,state:t}),i=DS({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=vi({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=Pk({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await fe({paths:e.paths,previous:t,next:a});return await M(L(e.paths,t.name),gi({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await hi({file:Vu.join(le(e.paths,t.name),"verification.md"),state:o}),o})}async function qm(e){return A(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);Mt({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Ze({paths:e.paths,state:t});let r=_k({state:t,summary:e.summary}),i=await fe({paths:e.paths,previous:t,next:r});return await M(L(e.paths,t.name),ae({portableState:i,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await hi({file:Vu.join(le(e.paths,t.name),"verification.md"),state:i}),i})}async function Mm(e){return A(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await H(e.paths,e.name);Mt({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Ze({paths:e.paths,state:t});let r=await $r({paths:e.paths,state:t}),i=Ak(t,{reason:e.reason}),n=await fe({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),gi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Vm(e){return A(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);Mt({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await $r({paths:e.paths,state:t}),i=Tk(t),n=await fe({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),gi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function an(e){return A(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=e.preserveLocalChecks!==!1,i=r?await $r({paths:e.paths,state:t}):null,n=pi({state:t,reason:e.reason,...e.failureBudget?{failureBudget:e.failureBudget}:{}}),a=await fe({paths:e.paths,previous:t,next:n});return await M(L(e.paths,t.name),r?gi({local:i,state:a,projectRoot:e.paths.projectRoot}):ae({portableState:a,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a})}async function Is(e){if(e.state.verification===null)return"not-applicable";let t=Vu.join(le(e.paths,e.state.name),"verification.md");return await lS({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await hi({file:t,state:e.state}),"rebuilt")}import vD from"node:path";kr();ve();async function Wm(e){return A(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Ze({paths:e.paths,state:t}),e.finish!==void 0&&!["keep","merge","push","pull-request"].includes(e.finish))throw new Error("Native workspace finish must be keep, merge, push, or pull-request");if(e.finish!==void 0&&t.workspace.isolation==="current")throw new Error("A workspace finish choice requires an isolated Native workspace");let r=await D(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(Yi(r).stateVersion!==r.stateVersion)return ua({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await q(e.paths,Xi(r,t))}let i=Ck(t);e.finish!==void 0&&(i.workspace={...i.workspace,finish:e.finish});let n=await fe({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await hi({file:vD.join(le(e.paths,t.name),"verification.md"),state:n}),n})}import{promises as BS}from"node:fs";kr();ve();zl();async function Ts(e){let t=await H(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await Le({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选可以提交并进入验证":"All Children are complete; the Supervisor parent candidate can be submitted for verification.";return{state:t,parentAdvance:{...r,message:n}}}async function LS(e){let t=await H(e.paths,e.name),r=await Wl(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await D(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await BS.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=Yi(n);if(i||a.stateVersion!==n.stateVersion){let o=await ua({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await BS.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await q(e.paths,Xi(n,t)),{state:t,action:"recorded-final-verification"}}async function Wu(e){return A(e.paths,`recover Supervisor final verification ${e.name}`,()=>LS(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}var g6=16*1024;Jn();bn();var qS="comet.native.workspace-finish.v1",wD="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",WS=new RegExp(`^${wD}$`,"u"),yD=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,$s=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function MS(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function bD(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==qS||typeof t.name!="string"||!WS.test(t.name)||typeof t.transactionId!="string"||!yD.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!fa.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"&&fa.isAbsolute(i))||![r.changeBranch,r.targetBranch].every(i=>typeof i=="string"&&i.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!fa.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");MS(r.commitMessage,"commit-message"),r.mergeMessage!==null&&MS(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||!$s.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(i=>typeof i=="string"&&i.length>0&&!fa.posix.isAbsolute(i)&&!fa.win32.isAbsolute(i)&&!i.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(i=>typeof i=="string")||r.sha!==null&&!$s.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!$s.test(r.target)||!$s.test(r.source)||r.sha!==null&&!$s.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:qS,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 ND(e,t){if(!WS.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return fa.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function zS(e,t,r={}){let i=ND(e,t);try{let n=await FS.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=bD(JSON.parse(await FS.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}}import{randomUUID as kD}from"node:crypto";import{promises as js}from"node:fs";import SD from"node:path";ne();rt();ve();nh();zl();Fl();at();ie();var GS=["evidence.md","repair.md","archive.md","checkpoint.md"],ED="verification.md";async function xD(e,t){let r=await Wl(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function JS(e,t){await js.mkdir(e.transactionsDir,{recursive:!0}),await he(Vl(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function US(e,t,r={}){let i=r.removeVerificationReport===!1?GS:[...GS,ED];await Promise.all([js.rm(me(e,t),{recursive:!0,force:!0}),js.rm(df(e,t),{recursive:!0,force:!0}),...i.map(n=>js.rm(SD.join(Ft(e,t),n),{force:!0}))])}async function KS(e,t){await M(L(e,t.name),ae({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function YS(e,t){try{let r=await ws(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function XS(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=oe(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function RD(e){let t=Ft(e.paths,e.state.name),r=await Z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Ll({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function QS(e,t){let r=await oS(e,t);if(r.status==="runtime-incompatible")throw new Qt(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function ZS(e){return A(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await xD(e.paths,e.name),r=await aa(e.paths,e.name)?await yt(dt(e.paths,e.name)):null;if(!t&&r)return await US(e.paths,e.name,{removeVerificationReport:!1}),await KS(e.paths,r),r;let i=null,n=null;for(t||(i=await QS(e.paths,e.name),n=await YS(e.paths,e.name),XS(e.paths,n),t={schema:ql,id:kD(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await JS(e.paths,t));;){let a=Gb(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await QS(e.paths,e.name),n??=await YS(e.paths,e.name),XS(e.paths,n),r=zb({state:i,acceptance:await RD({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await bo(dt(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await US(e.paths,e.name):a.action==="commit-transaction"&&(r??=await yt(dt(e.paths,e.name)),await KS(e.paths,r)),t={...t,status:a.nextStatus},await JS(e.paths,t)}return await js.rm(Vl(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??yt(dt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as tE}from"node:fs";import rE from"node:path";ve();import{promises as zm}from"node:fs";import CD from"node:path";pe();var PD=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),_D=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),AD=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),ID=new Set(["status","summary"]);function zu(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Gu(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 TD(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function on(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function $D(e,t,r,i){let n=zu(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Gu(n,PD,"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=zu(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Gu(o,_D,"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=zu(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Gu(c,ID,"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,p]of n.children.entries()){let d=zu(p,`Native Supervisor child ${u}`);if(!d)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:f,contractHash:h,...m}=d,v=Gu(m,AD,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],w=g.covers.length>0?g.covers.map(y=>({id:y,source:r.acceptance_index?.[y]?.source??"brief.md",text:r.acceptance_index?.[y]?.text??y})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(w)||h!==void 0&&h!==$("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(d.name!==g.name||d.summary!==g.summary||!TD(d.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let N=g.depends_on.length===0?"ready":"pending";if(d.status!==N)return`Native Supervisor child ${g.name} has progressed beyond its initial ${N} status`;if(d.baseCommit!==null||d.candidateCommit!==null||d.verifiedCommit!==null||d.integrationCommit!==null||d.verification!==null||d.blocker!==null||d.projectRoot!==null||d.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if((d.builderFailureCount??0)!==0)return`Native Supervisor child ${g.name} contains Builder failure progress`;if(!Array.isArray(d.checks)||d.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function ha(e){let t=Di(e.paths,e.state.name),r;try{let c=await zm.lstat(t);if(!c.isFile()||c.isSymbolicLink())return on(t,"","Native Supervisor overlay is not a regular file");r=await zm.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:on(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return on(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=CD.join(e.paths.changesDir,e.state.name),a;try{a=await Je({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return on(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 D(e.paths,e.state.name)}catch(c){return on(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return on(t,r,"Native Supervisor overlay disappeared during inspection");let s=$D(i,e.state,a.contract,o);return s?on(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function eE(e){let t=await ha({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await zm.rm(t.file,{force:!1})}at();ni();function Gm(e,t){let r=oe(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function jD(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function OD(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:ke(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(t),completed_at:i});return B({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?jD(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function HD(e){try{let t=await Ce(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Jm(e){return A(e.paths,`recover portable change ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.status==="done")return await Is({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=Gm(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await ha({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await eE({paths:e.paths,state:t,expected:i}),n=!0);let a=L(e.paths,e.name),o=await HD(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason,c=s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed";if(c&&o.local?.execution?.status==="running"){let m=o.local.execution,v=await Fu(o.local),g=m.stage==="verifying"&&m.actor==="verifier"&&m.executionId!==null,w=v==="unknown"&&e.recoverUnknownRuntimeCheck===!0&&m.stage==="checking"&&m.actor==="runtime";if(g||v!=="orphaned"&&!w)return{state:t,local:o.local,action:"await-user",reason:"execution-active",message:g?m.verifierStartedAt===void 0&&m.requestCheckRounds===0?`Native Verifier execution ${m.executionId} is registered but never confirmed startup; if the task did not start, record an explicit Verifier failure before retrying it.`:`Native Verifier execution ${m.executionId} remains owned by its host task; record an explicit Verifier failure before retrying it.`:v==="unknown"?"The Native Runtime check owner could not be proven to have exited; inspect the overlay or run Doctor with --repair to take over explicitly.":"The Native Runtime check operation is still owned by a live process; wait for it to finish before recovering it."}}if(c&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(m=>m.status==="planned"||m.status==="running"?{...m,status:"interrupted"}:m)},await M(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Is({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(m=>m.status==="interrupted"&&!m.repeatable):void 0;if(l){let m=pi({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Bn({file:dt(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot}),await tE.rm(rE.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let v=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await M(a,v,{containedRoot:e.paths.runtimeDir}),{state:t,local:v,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let u=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",p=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=u||p;if(d){let m=OD(t,p?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",p);t=await Bn({file:dt(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot})}let f=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:oe(e.paths.projectRoot).currentBranch});await tE.mkdir(rE.dirname(L(e.paths,t.name)),{recursive:!0}),await M(a,f,{containedRoot:e.paths.runtimeDir}),await Is({paths:e.paths,state:t});let h=s==="stale"&&o.local?`Local execution overlay was recorded for state version ${String(o.local.basedOnStateVersion)} of ${o.local.change} but the current state version is ${String(t.state_version)} of ${t.name}; a state transition moved on, so the overlay was rebuilt from the stable boundary.`:null;return{state:t,local:f,action:d?"reverify":"resume-stable-boundary",reason:s,message:h??(d?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`)}})}import iE from"node:path";function nE(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Pe(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:nE(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:nE(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=>iE.relative(t.projectRoot,iE.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}vo();go();function Ju(e){return e.charCodeAt(0)===65279?e.slice(1):e}Wo();Jn();pe();import{randomUUID as lE}from"node:crypto";import{promises as aE}from"node:fs";import Os from"node:path";We();Mn();Lh();So();ve();ji();function ga(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function W(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function ma(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>W(r,`${t}[${i}]`))}function DD(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=ga(t,`Native Builder check ${r}`);if(ee(i,["name","result","note"],`Native Builder check ${r}`,`/checks/${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:W(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function Uu(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=ga(t,`Native Runtime check ${r}`);if(ee(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`,`/checks/${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:W(i.id,`Native Runtime check ${r} id`),name:W(i.name,`Native Runtime check ${r} name`),executable:W(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:W(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function oE(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:W(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function BD(e){let t=ga(e,"Native Supervisor evidence");return ee(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence","/evidence"),{summary:W(t.summary,"Native Supervisor evidence summary"),checks:ma(t.checks,"Native Supervisor evidence checks"),acceptance:gl(t.acceptance,"/evidence/acceptance"),...t.receiptRef===null?{}:{receiptRef:W(t.receiptRef,"Native Supervisor receipt ref")}}}function uE(e){let t=ga(e,"Native Runner input");if(t.kind==="builder-handoff"){let r=["kind","summary","addressed_acceptance_ids","checks","known_limits"];Object.hasOwn(t,"acceptance_review")&&r.push("acceptance_review"),Object.hasOwn(t,"verification_checks")&&r.push("verification_checks"),ee(t,Object.hasOwn(t,"review")?[...r,"review"]:r,"Native Runner Builder input");let i=null;if(t.review!==void 0&&t.review!==null){let n=ga(t.review,"Native Builder review");if(ee(n,["status","summary","reviewer_execution_ref"],"Native Builder review","/review"),n.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");i={status:"passed",summary:W(n.summary,"Native Builder review summary"),reviewer_execution_ref:W(n.reviewer_execution_ref,"Native Builder reviewer execution ref")}}return{kind:"builder-handoff",summary:W(t.summary,"Native Builder summary"),...Object.hasOwn(t,"acceptance_review")?{acceptance_review:$n(t.acceptance_review)}:{},addressed_acceptance_ids:ma(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:DD(t.checks),...Object.hasOwn(t,"verification_checks")?{verification_checks:Uu(t.verification_checks)}:{},known_limits:ma(t.known_limits,"Native Builder known limits"),review:i}}if(t.kind==="dispatch-verifier")return ee(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:Uu(t.checks)};if(t.kind==="retry-checks")return ee(t,["kind","check_ids"],"Native Runner check retry input"),{kind:"retry-checks",check_ids:ma(t.check_ids,"Native check retry IDs")};if(t.kind==="verifier-response")return ee(t,["kind","candidateId","verifierExecutionRef","response"],"Native Runner Verifier input"),{kind:"verifier-response",candidateId:W(t.candidateId,"Native Runner Verifier candidateId"),verifierExecutionRef:W(t.verifierExecutionRef,"Native Runner Verifier verifierExecutionRef"),response:ko(t.response,"/response")};if(t.kind==="verifier-started")return ee(t,["kind","candidateId","verifierExecutionRef"],"Native Runner started input"),{kind:"verifier-started",candidateId:W(t.candidateId,"Native Runner started candidateId"),verifierExecutionRef:W(t.verifierExecutionRef,"Native Runner started verifierExecutionRef")};if(t.kind==="verifier-execution-error")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:W(t.summary,"Native Verifier execution error summary"),...oE(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:W(t.summary,"Native unavailable Verifier summary"),...oE(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return ee(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),candidateCommit:W(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return ee(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),reason:W(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-retry-builder"){if(ee(t,["kind","child","stateVersion"],"Native Supervisor Builder retry input"),!Number.isSafeInteger(t.stateVersion)||t.stateVersion<1)throw new Error("Native Supervisor Builder retry stateVersion is invalid");return{kind:"supervisor-retry-builder",child:W(t.child,"Native Supervisor child"),stateVersion:t.stateVersion}}if(t.kind==="supervisor-reconnect")return ee(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return ee(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),reason:W(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(ee(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:BD(t.evidence)}}if(t.kind==="supervisor-checks"){let r=["kind","child","runId","checks","materials"];if(ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor checks"),!Array.isArray(t.materials))throw new Error("Native Supervisor materials must be an array");return{kind:"supervisor-checks",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),checks:Uu(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:ma(t.retry_check_ids,"Native Supervisor retry IDs")},materials:t.materials.map((i,n)=>{let a=ga(i,"Native Supervisor material");return ee(a,["name","content"],"Native Supervisor material",`/materials/${n}`),{name:W(a.name,"Native Supervisor material name"),content:W(a.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate"){let r=["kind","child","checks"];return ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor integration input"),{kind:"supervisor-integrate",child:W(t.child,"Native Supervisor child"),checks:Uu(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:ma(t.retry_check_ids,"Native Supervisor retry IDs")}}}throw new Error("Native Runner input kind is invalid")}async function Qm(e,t){let r=Os.resolve(t,e),i=await aE.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(Ju(await aE.readFile(r,"utf8")))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return uE(n)}async function Zm(e){await A(e.paths,"register-runner-input",async()=>{await bk({paths:e.paths,file:e.file,validateContent:t=>{let r=uE(JSON.parse(Ju(t)));if($("comet.native.runner-input.v1",r)!==$("comet.native.runner-input.v1",e.input))throw new Error("Native Runner input changed after parsing")}})})}function LD(e){return e.kind==="builder-handoff"||e.kind==="dispatch-verifier"||e.kind==="retry-checks"||e.kind==="verifier-response"||e.kind==="verifier-started"||e.kind==="verifier-execution-error"||e.kind==="verifier-unavailable"}function FD(e){return e.kind.startsWith("supervisor-")}function qD(e){return e.response.kind!=="request-checks"?[]:e.response.checks.map(({id:t,name:r,executable:i,argv:n,cwdRef:a,timeoutMs:o,repeatable:s})=>({id:t,name:r,executable:i,argv:[...n],cwdRef:a,timeoutMs:o,repeatable:s}))}function sE(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.stage!=="verify-ready")throw new Error("Native Runner check input requires an active Verify-ready candidate")}function Um(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result")throw new Error("Native Runner Verifier input requires an active Verifier attempt")}function MD(e,t){if(new Set(t).size!==t.length)throw new Error("Native Builder addressed acceptance IDs contain duplicates");let r=new Set(e.acceptance.map(({id:n})=>n)),i=t.filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native Builder addressed acceptance IDs contain unknown IDs: ${i.join(", ")}`)}async function Km(e){let t=await Ce(L(e.paths,e.state.name)),r=t?.execution;if(t===null||t.basedOnStateVersion!==e.state.state_version||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null)throw new Error("Native Runner Verifier input requires an active Runtime Verifier execution");return r}async function ev(e){let t=await ha({paths:e.paths,state:e.state});if(t.status==="incompatible")throw new Error(t.message);let r=t.status==="repairable-legacy-overlay"?null:await D(e.paths,e.name),i=r!==null&&e.state.phase==="verify"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),n=r!==null&&e.state.phase==="build"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),a=await Le({paths:e.paths,state:e.state}),o=(i||n)&&r?r.integration.worktree:e.projectRoot;if(FD(e.input)&&r===null)throw new Error("Native Supervisor Runner input requires a current Supervisor state");if(r&&LD(e.input)&&!i&&!(e.input.kind==="builder-handoff"&&n))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(e.input.kind==="builder-handoff"){if(e.state.phase!=="build"||e.state.status!=="active")throw new Error("Native Builder input requires an active Build boundary");if(MD(e.state,e.input.addressed_acceptance_ids),jn(e.state.acceptance,e.input.acceptance_review),a&&(!a.confirmed||!a.allDone))throw new Error("Native parent Build advances child changes and does not accept a Builder handoff");if(n&&e.state.loop.stage==="repairing"&&e.state.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first");e.input.verification_checks!==void 0&<(o,e.input.verification_checks);return}if(e.input.kind==="dispatch-verifier"){if(sE(e.state),i&&e.input.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");lt(o,e.input.checks);return}if(e.input.kind==="retry-checks"){if(sE(e.state),e.input.check_ids.length===0||new Set(e.input.check_ids).size!==e.input.check_ids.length)throw new Error("Native check retry list must contain unique IDs");let c=await Ce(L(e.paths,e.name));for(let l of e.input.check_ids){let u=c?.checks.find(p=>p.id===l);if(!u||u.status!=="interrupted")throw new Error(`Native check retry ID is not an interrupted current check: ${l}`);if(!u.repeatable)throw new Error(`Native check ${l} is not repeatable and cannot be retried`);if(u.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${l}`)}return}if(e.input.kind==="verifier-response"){Um(e.state);let c=await Km({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");lt(o,qD(e.input));return}if(e.input.kind==="verifier-started"){Um(e.state);let c=await Km({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner started input is stale for the current candidate or execution");return}if(e.input.kind==="verifier-execution-error"||e.input.kind==="verifier-unavailable"){Um(e.state);let c=await Km({paths:e.paths,state:e.state});if(e.input.stateVersion!==e.state.state_version||e.input.iteration!==e.state.loop.iteration||e.input.attempt!==e.state.loop.attempt||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current attempt");return}let s=e.input;if(s.kind==="supervisor-retry-builder"){if(!r)throw new Error("Native Supervisor Builder retry requires a current Supervisor state");let c=r.children.find(({name:l})=>l===s.child);if(!c)throw new Error(`Native Supervisor child ${s.child} does not exist`);if(s.stateVersion!==r.stateVersion||c.status!=="blocked"||c.task!==null||(c.builderFailureCount??0)<Nr)throw new Error("Native Supervisor Builder retry input is stale or not currently required");return}if(e.input.kind==="supervisor-checks"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:u})=>u)).size!==c.checks.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(c.checks.some(({repeatable:u})=>!u))throw new Error("Native Supervisor checks must be repeatable for safe recovery");let l=r?.children.find(({name:u})=>u===c.child)?.task;if(!l||l.role!=="verifier"||l.runId!==c.runId)throw new Error("Native Supervisor check runId is not current");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");lt(l.projectRoot,c.checks);return}if(e.input.kind==="supervisor-integrate"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:l})=>l)).size!==c.checks.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(c.checks.some(({repeatable:l})=>!l))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");lt(r.integration.worktree,c.checks)}}function dE(e){return`${Se}:${e}:${lE()}`}function cE(e,t,r,i){if(Os.resolve(I(e.projectRoot,["rev-parse","--show-toplevel"]))!==Os.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(I(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!tr(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(I(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function VD(e,t){let r=oe(e.projectRoot),i=Os.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Os.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=I(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!tr(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function va(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Se)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");return e.builder_handoff}function WD(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function pE(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=va(r),s=WD(r),c=r.acceptance.filter(({result:p})=>p==="pending").map(({id:p})=>p),l=r.acceptance.filter(({id:p})=>c.includes(p)).map(({id:p,source:d,text:f})=>({id:p,source:d,text:f})),u=l.length<=eh.maxItems&&Buffer.byteLength(JSON.stringify(l),"utf8")<=eh.maxSerializedBytes;return{coordination:Se,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:le(t,r.name),supervisorStateRef:a?Di(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:p,operation:d,source:f})=>({capability:p,operation:d,ref:f})),acceptanceCount:r.acceptance.length,scopeCount:c.length,scopeIds:c,...u?{acceptance:l}:{},startupInput:{kind:"verifier-started",candidateId:o.candidate_id,verifierExecutionRef:n},detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:o.review?{status:o.review.status,summary:o.review.summary}:null,builderSummary:o.summary.text,runtimeChecks:i.map(p=>({...p})),builderReportedChecks:o.checks.map(p=>({...p})),builderKnownLimits:o.known_limits.map(p=>({...p})),startupInstruction:"As this Verifier, submit the startup receipt first: copy startupInput into a temporary JSON file and run comet native next <change> --runner-input <file> --project-root <projectRoot above>. It records that this Verifier actually started; a repeat submission is accepted without side effects. Read acceptance when included; otherwise follow detailsPageArgs until every scopeId has been read. Then inspect the linked brief and Spec and proceed.",evidenceInstruction:"Independently inspect the current candidate against every scenario in scopeIds exactly once. Runtime checks are bound evidence; Builder-reported checks and review are claims to corroborate, not Runtime receipts. Reuse applicable completed evidence, request only missing or invalidated checks, and do not repeat full suites by default. Use one Verifier for this dispatch; keep it running across wait-tool timeouts. Return the actual scoped findings, risks, and incomplete checks without omitting limitations. Keep using the same CLI executable that produced this dispatch; do not switch to a different PATH installation.",responseInstruction:"Return one acceptance entry for each ID in scopeIds and no other acceptance IDs. Runtime safely filters a known already-passed superset only when every extra entry still reports passed; nonexistent IDs and conflicting out-of-scope results remain invalid."}}async function Ym(e){let t=dE("verifier"),r=await Hm({paths:e.paths,name:e.name,checks:e.checks,verifierExecutionId:t,...e.supervisor?{projectRoot:e.supervisor.integration.worktree}:{}});return{state:r,checks:e.checks,runtimeCheckExecution:{disposition:e.disposition},requestChecks:null,verifierDispatch:pE({paths:e.paths,state:r,checks:e.checks,verifierExecutionRef:t,supervisor:e.supervisor}),continuation:Y(r,void 0,{verifierExecutionRef:t,verifierStartup:"unconfirmed"})}}async function Xm(e){va(e.state);let t=await Ce(L(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function fE(e){let t=e.input;e.inputFile&&await Zm({paths:e.paths,file:e.inputFile,input:t});let r=await H(e.paths,e.name),i=await ha({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await D(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:h})=>h==="integrated"||h==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:h})=>h==="integrated"||h==="archived");if(n&&t.kind==="supervisor-checks"){let h=await Bh({paths:e.paths,parent:e.name,child:t.child,runId:t.runId,plans:t.checks,materials:t.materials,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),m=await D(e.paths,e.name),v=m?.children.find(({name:g})=>g===t.child)?.task;return{state:r,supervisorState:m,supervisorTask:v&&v.runId===t.runId?ri(v,e.name,e.paths.projectRoot):null,checks:[],checkExecution:h,requestChecks:null,verifierDispatch:null,continuation:Y(r)}}if(n&&t.kind==="supervisor-builder-result")return A(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let h=await D(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:y})=>y===t.child);if(!m?.task||m.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{cE(m.task,t.candidateCommit,"builder",`comet/supervisor/${h.parent}/${t.child}`)}catch(y){throw await q(e.paths,Po(h,{child:t.child,runId:t.runId,reason:y.message})),y}let v=m.task.projectRoot,g=Rf(h,t),w=Co(g,{role:"verifier",child:t.child,projectRoot:v,runId:lE()});await q(e.paths,w.state);let N=await H(e.paths,e.name);return{state:N,supervisorTask:ri(w.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(N)}});if(n&&t.kind==="supervisor-builder-failure")return A(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let h=await D(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:w})=>w===t.child);if(!m?.task||m.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let v=wl(h,{child:t.child,runId:t.runId,reason:t.reason});await q(e.paths,v);let g=await H(e.paths,e.name);return{state:g,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(g)}});if(n&&t.kind==="supervisor-retry-builder")return A(e.paths,`retry Native Supervisor Builder task ${t.child}`,async()=>{let h=await D(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=Pf(h,{child:t.child,expectedStateVersion:t.stateVersion});await q(e.paths,m);let v=await H(e.paths,e.name);return{state:v,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(v)}});if(n&&t.kind==="supervisor-reconnect")return A(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let h=await D(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:w})=>w===t.child)?.task;if(!m||m.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{VD(m,`comet/supervisor/${h.parent}/${t.child}`)}catch(w){throw await q(e.paths,Po(h,{child:t.child,runId:t.runId,reason:w.message})),w}let v=xf(h,{child:t.child,runId:t.runId});await q(e.paths,v.state);let g=await H(e.paths,e.name);return{state:g,supervisorState:v.state,supervisorTask:ri(v.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(g)}});if(n&&t.kind==="supervisor-cancel")return A(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let h=await D(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=wl(h,{child:t.child,runId:t.runId,reason:t.reason});await q(e.paths,m);let v=await H(e.paths,e.name);return{state:v,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(v)}});if(n&&t.kind==="supervisor-verifier-result")return A(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let h=await D(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:N})=>N===t.child);if(!m?.task||m.task.role!=="verifier"||!m.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{cE(m.task,m.candidateCommit,"verifier",`comet/supervisor/${h.parent}/${t.child}`)}catch(N){throw await q(e.paths,Po(h,{child:t.child,runId:t.runId,reason:N.message})),N}let v=t.evidence.receiptRef||t.verdict==="pass"?await ea({paths:e.paths,parent:e.name,task:m.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!v||v.checks.some(({status:N,exitCode:y})=>N!=="passed"||y!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let g=Cf(h,{...t,evidence:{...t.evidence,checks:v?.checks.map(({name:N,status:y})=>`${N}: ${y}`)??[],execution:structuredClone(m.task)}});await q(e.paths,g);let w=await H(e.paths,e.name);return{state:w,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(w)}});if(n&&t.kind==="supervisor-integrate"){let h=await Mh({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),m=await Ts({paths:e.paths,name:e.name,trigger:"v2-integrate"}),v=m.state;return{state:v,supervisorState:h,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:m.parentAdvance,continuation:Y(v)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="retry-checks"||t.kind==="verifier-response"||t.kind==="verifier-started"||t.kind==="verifier-execution-error"||t.kind==="verifier-unavailable"||t.kind==="supervisor-builder-result"||t.kind==="supervisor-builder-failure"||t.kind==="supervisor-reconnect"||t.kind==="supervisor-cancel"||t.kind==="supervisor-verifier-result")&&!a&&!(t.kind==="builder-handoff"&&o))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(t.kind==="builder-handoff"){if(o&&t.verification_checks?.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let m=Nf().captureExecutionIdentity({identityProvider:Se,executionRef:dE("builder")}),v=await Om({paths:e.paths,name:e.name,verificationChecks:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{},input:{identity:m,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,acceptanceReview:t.acceptance_review,checks:t.checks,knownLimits:t.known_limits,review:t.review?{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}:null}});if(t.verification_checks!==void 0){let g=await As({paths:e.paths,name:e.name,plans:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{}}),w=g.checks.filter(({status:E})=>E==="failed").map(({id:E})=>E),N=g.checks.filter(({status:E})=>E==="interrupted").map(({id:E})=>E),y=t.verification_checks.filter(({id:E,repeatable:b})=>N.includes(E)&&!b).map(({id:E})=>E);if(w.length>0||y.length>0){let E=w.length>0?`Builder handoff Runtime checks failed: ${w.join(", ")}`:`Builder handoff Runtime checks were interrupted and cannot be repeated: ${y.join(", ")}`,b=await an({paths:e.paths,name:e.name,reason:E,failureBudget:{maxVerifyFailures:e.maxVerifyFailures}});return{state:b,checks:g.checks,runtimeCheckExecution:{disposition:g.disposition},requestChecks:null,verifierDispatch:null,continuation:Y(b)}}return N.length===0?Ym({paths:e.paths,name:e.name,checks:g.checks,disposition:g.disposition,supervisor:o?n:null}):{state:g.state,checks:g.checks,runtimeCheckExecution:{disposition:g.disposition},continuationCheckPlans:t.verification_checks,...N.length>0?{continuationRetryCheckIds:N}:{},requestChecks:null,verifierDispatch:null,continuation:Y(g.state,void 0,{...N.length>0?{retryCheckIds:N}:{verificationCheckPlans:t.verification_checks}})}}return{state:v,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(v)}}if(t.kind==="retry-checks"){if(n&&!a)throw new Error("Native Supervisor check retry is only valid after every Child is integrated");let h=await H(e.paths,e.name);va(h);let m=await $m({paths:e.paths,name:e.name,checkIds:t.check_ids,...a&&n?{projectRoot:n.integration.worktree}:{}}),v=m.checks.filter(({status:g})=>g==="interrupted").map(({id:g})=>g);if(v.length>0){let w=((await Ce(L(e.paths,e.name)))?.checks??[]).filter(({id:N,status:y,executionCount:E})=>v.includes(N)&&y==="interrupted"&&E>=3).map(({id:N})=>N);if(w.length>0){let N=await an({paths:e.paths,name:e.name,reason:`Native Runtime checks reached the retry limit after repeated interruptions: ${w.join(", ")}`,failureBudget:{maxVerifyFailures:e.maxVerifyFailures},preserveLocalChecks:!0});return{state:N,checks:m.checks,requestChecks:null,verifierDispatch:null,continuation:Y(N)}}}return v.length===0&&m.checks.every(({status:g})=>g==="passed")?Ym({paths:e.paths,name:e.name,checks:m.checks,disposition:"executed",supervisor:a?n:null}):{state:m.state,checks:m.checks,...v.length>0?{continuationRetryCheckIds:v}:{},requestChecks:null,verifierDispatch:null,continuation:Y(m.state,void 0,{retryCheckIds:v.length>0?v:void 0})}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let h=await H(e.paths,e.name);if(h.builder_handoff!==null&&h.builder_handoff.identity_provider!==Se){let w=await an({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:w,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(w)}}va(h);let m=await As({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}}),v=m.checks,g=v.filter(({status:w})=>w==="interrupted").map(({id:w})=>w);if(g.length>0){let w=t.checks.filter(({id:y,repeatable:E})=>g.includes(y)&&!E).map(({id:y})=>y);if(w.length>0)throw new Error(`Native non-repeatable checks were interrupted and require a new Builder candidate: ${w.join(", ")}`);let N=await H(e.paths,e.name);return{state:N,checks:v,runtimeCheckExecution:{disposition:m.disposition},continuationRetryCheckIds:g,requestChecks:null,verifierDispatch:null,continuation:Y(N,void 0,{retryCheckIds:g})}}return Ym({paths:e.paths,name:e.name,checks:v,disposition:m.disposition,supervisor:a?n:null})}if(t.kind==="verifier-started"){let h=await Dm({paths:e.paths,name:e.name,candidateId:t.candidateId,verifierExecutionRef:t.verifierExecutionRef});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(h,void 0,{verifierExecutionRef:t.verifierExecutionRef,verifierStartup:"confirmed"})}}if(t.kind==="verifier-execution-error"){let h=await H(e.paths,e.name);va(h),await Xm({paths:e.paths,state:h});let m=await Lm({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(m)}}if(t.kind==="verifier-unavailable"){let h=await Fm({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:h,checks:h.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:Y(h)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await H(e.paths,e.name),c=va(s),l=await Xm({paths:e.paths,state:s});if(t.candidateId!==c.candidate_id||t.verifierExecutionRef!==l)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");let u=Nf(),p=u.captureExecutionIdentity({identityProvider:Se,executionRef:l}),d=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let h=await D(e.paths,e.name);if(!h)throw new Error("Native Supervisor state disappeared before final verification");d=Yi(h)}let f=await Bm({paths:e.paths,name:e.name,envelope:u.envelopeVerifierResponse({candidateId:c.candidate_id,identity:p,payload:t.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...a&&n?{projectRoot:n.integration.worktree}:{}});if(a&&f.response.kind==="final-result"){if(f.state.verification_result==="pass"&&(f.checks.length===0||f.checks.some(({status:v})=>v!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let h=d??await D(e.paths,e.name);if(!h)throw new Error("Native Supervisor state disappeared during verification");let m=Xi(h,f.state);return await q(e.paths,m),{...f,supervisorState:m,verifierDispatch:null,continuation:Y(f.state)}}return{...f,verifierDispatch:f.requestChecks===null?null:pE({paths:e.paths,state:f.state,checks:f.checks,verifierExecutionRef:await Xm({paths:e.paths,state:f.state}),supervisor:a?n:null}),continuation:Y(f.state,void 0,{verifierExecutionRef:l,verifierStartup:"confirmed"})}}ji();On();lo();import Ds from"path";import{realpathSync as _B}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 jr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function mE(e){return e?e.command?`${jr.next} ${e.command}`:e.ask_user?`${jr.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("",jr.relay,e.user_message),t!==void 0&&r.push("",jr.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
368
375
|
`)}
|
|
369
|
-
`}function
|
|
370
|
-
`)}pe();rt();pe();var
|
|
371
|
-
`)}}let r=t.continuation;if(
|
|
376
|
+
`}function gE(e,t,r){let i=[e.summary],n=mE(e.next);return n&&i.push(n),e.user_message&&i.push("",jr.relay,e.user_message),i.push("",`${jr.detail} ${t}`),r!==void 0&&i.push("",jr.details,JSON.stringify(r,null,2)),i.join(`
|
|
377
|
+
`)}pe();rt();pe();var zD=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});ui();Zt();gt();ie();ne();rr();Ho();ve();ie();Zt();ii();pe();pe();fu();Xn();rr();var wE={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:[]},GD=ut("comet-native-runtime:v3:scope-reopen"),O9=[{skillVersion:"3",skillHash:ut("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ut("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ut("comet-native-runtime:v1")}];rr();rr();Bo();var bE=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],m4=new Set(bE),ZD=new Set([...bE,"minimum_runtime_version","revision"]),v4=new Set([...ZD,"operation"]),eB=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),g4=new Set([...eB,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);Wo();rt();rt();Wo();pe();var k4={maxAcceptanceCriteria:Bl.maxCriteria};ui();Jo();Xn();fu();import{execFile as lB}from"node:child_process";yn();Xa();Of();import{promisify as uB}from"node:util";ne();rr();ie();Zt();eo();ii();ve();ne();Rh();ie();Jt();ui();ve();ii();var Hs=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Jo();mu();Xn();var S3=64*1024;var E3=3600*1e3;var x3=uB(lB);mu();var Ku=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}};rr();Zt();ne();Jt();ie();Zt();Ql();ne();Wi();ui();var b8=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});rr();Ho();ve();ie();Zt();Ql();var Yu=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"},Xu=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"};ie();gt();function F(e,t,r){return e==="zh-CN"?r:t}var tv={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function kE(e,t){return typeof e=="string"&&tv[e]?F(t,tv[e].en,tv[e].zh):typeof e=="string"?e:""}function rv(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 hB(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 SE(e,t){let r=[];e.failed>0&&r.push(F(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(F(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(F(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=F(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function EE(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 iv(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function mB(e,t,r){return e==="done"?F(r,"complete","已完成"):e==="await-user"?F(r,"waiting for a user decision","等待用户决定"):e==="blocked"?F(r,"paused: needs attention","已暂停,需要处理"):t?F(r,"waiting for a user decision","等待用户决定"):F(r,"ready to continue","可继续推进")}function vB(e,t,r){let i=iv(e),n=[];r&&n.push(r);let a=F(i,`Change ${e.change}`,`需求 ${e.change}`),o=kE(e.phase,i),s=mB(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(SE(t,i));let c=e.userCommunication,l=xE(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function xE(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:F(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:F(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:F(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function gB(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function wB(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=kE(e.phase,t),n=e.status==="await-user"?F(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?F(t,"paused","已暂停"):e.status==="done"?F(t,"complete","已完成"):F(t,"in progress","进行中"),a=rv(e.acceptance)?`${F(t,", ",",")}${SE(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function yB(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 bB(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 NB(e){if(e.healthy){let i=e.repaired?F("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):F("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=kB(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:F("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:F("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function kB(e){return EE(e)?xE(e,iv(e)):void 0}function RE(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(bB(t))return NB(t);if(gB(t)){let i=yB(t.items);return{summary:[t.total===t.items.length?F(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):F(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>wB(a,i))].join(`
|
|
378
|
+
`)}}let r=t.continuation;if(EE(r)){let i=iv(r),n=vB(r,SB(t),xB(t,i));return EB(t)==="unconfirmed"?{...n,summary:`${n.summary}${F(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:F(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 SB(e){if(rv(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(rv(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return hB(r.acceptance)}return null}function EB(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 xB(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return F(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?F(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function CE(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:F("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:F("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:F("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:F("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:F("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:F("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:F("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:F("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:F("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}vo();go();var PE=["--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."],nv=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:PE,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
|
|
372
379
|
comet native spec remove <change-name> <capability>
|
|
373
380
|
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>]
|
|
374
381
|
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>]
|
|
375
382
|
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>]
|
|
376
|
-
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
|
|
383
|
+
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 Qu(e,t){return`${e}:
|
|
377
384
|
${t.map(r=>` ${r}`).join(`
|
|
378
|
-
`)}`}function
|
|
379
|
-
${r.output}`),r.examples&&i.push("",
|
|
385
|
+
`)}`}function RB(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return nv[r]||t.length>1&&nv[t[0]]?.subcommands?r:t[0]}function CB(e=[]){let t=RB(e),r=nv[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",Qu("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",Qu("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...PE];return n&&n.length>0&&i.push("",Qu("Options",n)),i.push("",`Output:
|
|
386
|
+
${r.output}`),r.examples&&i.push("",Qu("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
380
387
|
`)}
|
|
381
|
-
`}}var
|
|
382
|
-
`}function et(e,t,r){return{command:e,exitCode:0,data:t,text:r??
|
|
383
|
-
`}:e.error?{exitCode:e.exitCode,stderr:i?
|
|
388
|
+
`}}var PB=CB().usage;var _5=10*1024*1024,X=class extends Error{};function Vt(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new X(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function dr(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new X(`${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 X(`${t} requires a value`);return e.splice(i,2),n}function AE(e){if(e.length>0)throw new X(`Unexpected argument: ${e[0]}`)}function IE(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new X(`${t} is required`);return r}function av(e,t){let r=Ds.normalize(_E(e)),i=Ds.normalize(_E(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function _E(e){let t=Ds.resolve(e);try{return _B.native(t)}catch{return t}}function AB(e,t){let r=Ds.resolve(t,e),i=oe(t);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=oe(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!av(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||av(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:av(t,i.currentWorktreeRoot)?Ds.resolve(t):i.currentWorktreeRoot}async function TE(e,t=process.cwd()){return e?AB(e,t):tl(t)}function $E(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}async function jE(e){let t=await Sy({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function OE(e){return JSON.stringify(e,null,2)+`
|
|
389
|
+
`}function et(e,t,r){return{command:e,exitCode:0,data:t,text:r??OE(t)}}function IB(e,t){if(t instanceof la)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof Tn)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 mo)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof X)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Yu)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 Xu)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Tu)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 bs)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 ai)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof $u)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 Ku)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Hs)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 sn(e,t){let r=IB(e,t),i=r.error;if(!i)return r;let n=CE({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function TB(e,t,r=!1){let i=e.envelope??RE(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:hE(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}})+`
|
|
390
|
+
`}:e.error?{exitCode:e.exitCode,stderr:i?gE(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:vE(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==OE(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
384
391
|
${jr.details}
|
|
385
392
|
${JSON.stringify(e.data,null,2)}
|
|
386
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}function bB(e,t,r=!1){let i=yB(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 RE(e,t,r=!1){return bB(e,t,r).output}var NB=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function kB(e){let t=dr(e,"--expected-state-version"),r=dr(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new X("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new X("--expected-state-version must be a positive integer");if(!NB.has(r))throw new X("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function pr(e,t,r,i,n){let a=await Qf({paths:e,name:t.name});a.local&&(r??=Kf(t,a.local),i===void 0&&(i=lS(a.local,a.local.workspace.projectRoot)));let o=await Le({paths:e,state:t}),s=o?.confirmed?await D(e,t.name,{diagnostics:!0}):null,c=s?.children.flatMap(({task:d})=>d?[d.child]:[])??[],l=s?.integration.checkExecution,u=l?.status==="interrupted"?(l.checkStates??[]).filter(({status:d})=>d==="interrupted").map(({id:d})=>d):void 0;return{...o?{childSummary:o.children.reduce((d,p)=>({...d,[p.status]:(d[p.status]??0)+1}),{total:o.children.length}),readyChildren:c.length>0?c:o.readyChildren}:{},continuation:Y(t,o,{verifierExecutionRef:r,verifierStartup:Sk(t,a.localStatus==="available"?a.local:null),verificationCheckPlans:i,retryCheckIds:n,supervisorIntegrationRetryIds:u})}}function SB(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"&&t!=="continuationCheckPlans"&&t!=="continuationRetryCheckIds"))}function CE(e){return{action:e.action,reason:e.reason,message:e.message}}async function _E(e,t){let r=NE(e,"change name"),i=dr(e,"--summary"),n=dr(e,"--runner-input"),a=Vt(e,"--validate-only"),o=Vt(e,"--confirmed"),s=Vt(e,"--accept-result"),c=dr(e,"--finish");if(c!==void 0&&(!s||!["keep","merge","push","pull-request"].includes(c)))throw new X("--finish requires --accept-result and must be keep, merge, push, or pull-request");let l=Vt(e,"--revise-implementation"),u=Vt(e,"--revise-requirements"),d=Vt(e,"--retry-verifier"),p=Vt(e,"--resolve-verifier-blocker"),h=dr(e,"--coordination-mode"),f=h;if(h!==void 0&&!il.includes(h))throw new X("--coordination-mode must be multi-session or single-session");if(a&&n===void 0)throw new X("--validate-only requires --runner-input");let m=dr(e,"--max-parallel"),v=m===void 0?2:Number(m);if(!Number.isSafeInteger(v)||v<1)throw new X("--max-parallel must be a positive integer");let g=kB(e);if([o,s,l,u,d,p].filter(Boolean).length>1)throw new X("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(f!==void 0&&(s||l||u||d||p||n!==void 0))throw new X("--coordination-mode is only valid when preparing or confirming a Supervisor Shape");bE(e);let w=await EE(t),N=await OS(w.paths,r);if(!await na(w.paths,r)){if(N){let _={schema:"comet.native.continuation.v2",skill:"comet-native",change:r,phase:"archive",status:"blocked",disposition:"blocked",requiresUserDecision:!1,action:"archive",commandArgs:N.result?.recoveryArgs??["comet","native","archive",r,"--confirmed"],requiredInputs:[],inputOptions:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0},userCommunication:{required:!0,message:N.result?.message??"Native Archive completed, but workspace finish is still pending.",suggestedReply:null,agentInstruction:"Report the blocker and resolve it within the recorded delivery authorization, then retry the recorded command. Ask only if new information or authorization is needed; a retry of the same finish does not need another confirmation."}};return{command:"next",exitCode:73,data:{change:r,archived:!0,workspaceFinishResult:N.result,continuation:_},error:{code:"conflict",message:N.result?.message??"Native Archive completed, but workspace finish is still pending"}}}if(n)throw new X("--runner-input is only valid for portable Native changes");if(!i)throw new X("--summary is required");let P=await VS({paths:w.paths,name:r});return et("next",{state:Pe(P,w.paths),migration:{completed:!0,summary:i},continuation:Y(P)})}let y=await H(w.paths,r);if(a){if(i||o||s||l||u||d||p||g||f!==void 0)throw new X("--validate-only cannot be combined with --summary, continuation expectations, or coordination mode");let P;try{P=await Jm(n,t)}catch(_){let j=on("next",_);return{...j,data:{...j.data&&typeof j.data=="object"?j.data:{},state:Pe(y,w.paths),continuation:Y(y)}}}try{await Km({paths:w.paths,name:r,state:y,input:P,projectRoot:t})}catch(_){let j=on("next",_);return{...j,data:{...j.data&&typeof j.data=="object"?j.data:{},state:Pe(y,w.paths),continuation:Y(y)}}}return et("next",{validation:{valid:!0,kind:P.kind},state:Pe(y,w.paths),continuation:Y(y)})}if(n!==void 0||!i||y.phase==="verify"||y.phase==="archive"||y.verification_result==="pass"){let P=Fm(w.paths,y);if(P)return PE(w.paths,y,r,P)}if(n){if(i||o||s||l||u||d||p||f!==void 0||g)throw new X("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let P;try{P=await Jm(n,t),await Um({paths:w.paths,file:n,input:P}),await Km({paths:w.paths,name:r,state:y,input:P,projectRoot:t}),y.document_constraints_version===1&&await ju({paths:w.paths,state:y})}catch(hr){let _e=on("next",hr);return{..._e,data:{..._e.data&&typeof _e.data=="object"?_e.data:{},state:Pe(y,w.paths),continuation:Y(y)}}}let _=await Mu({paths:w.paths,name:r});if(_.action==="rerun-final-verification")return et("next",{state:Pe(_.state,w.paths),...await pr(w.paths,_.state)});let j=await Mm({paths:w.paths,name:r,preserveRunningExecution:!0}),ue=j.state;if(j.action==="await-user"||j.action==="done"||j.reason!=="available")return et("next",{state:Pe(ue,w.paths),recovery:CE(j),...await pr(w.paths,ue)});if(ue.phase==="build"){let hr=await Ns({paths:w.paths,state:ue});if(hr.drifted){let ga=await ks({paths:w.paths,name:r,reason:hr.reason??"Native confirmed requirements changed",keepFailureBudget:!0});return et("next",{state:Pe(ga,w.paths),...await pr(w.paths,ga)})}let _e=await D(w.paths,r),Ae=await Le({paths:w.paths,state:ue});if(Ae&&!Ae.allDone&&!_e)throw new X("Native parent Build advances child changes and does not accept a Builder handoff")}let de;try{de=await iE({paths:w.paths,name:r,input:P,inputFile:n,maxVerifyFailures:w.config.native.max_verify_failures})}catch(hr){let _e=await H(w.paths,r),Ae=on("next",hr);return{...Ae,data:{...Ae.data&&typeof Ae.data=="object"?Ae.data:{},state:Pe(_e,w.paths),...await pr(w.paths,_e)}}}let Or="continuationCheckPlans"in de?de.continuationCheckPlans:void 0,tt="continuationRetryCheckIds"in de?de.continuationRetryCheckIds:void 0;return et("next",{...SB(de),state:Pe(de.state,w.paths),...await pr(w.paths,de.state,de.verifierDispatch?.verifierExecutionRef,Or,tt),coordination:Se})}if(!i)throw new X("--summary is required");let b=await Mu({paths:w.paths,name:r});if(b.action==="rerun-final-verification")return et("next",{state:Pe(b.state,w.paths),...await pr(w.paths,b.state)});let x=await Mm({paths:w.paths,name:r}),k=x.state;if(x.reason==="workspace-mismatch")return PE(w.paths,k,r,x.message);if(f!==void 0&&k.phase!=="shape")throw new X("--coordination-mode is only valid when confirming Shape");let S,C=null;if(o)if(k.phase==="shape"&&k.status==="await-user"&&k.loop.next_action==="confirm-shape"){if(!g)throw new X("--expected-state-version and --expected-action are required for Shape confirmation");S=await _m({paths:w.paths,name:r,expectedContinuation:g,...f===void 0?{}:{coordinationMode:f}})}else{if(k.phase==="shape")throw new X("--confirmed is only valid from the persisted Shape user confirmation boundary");if(k.phase==="verify"&&k.status==="await-user"&&k.loop.next_action==="confirm-verifier-unavailable")S=await Hm({paths:w.paths,name:r,summary:i,expectedContinuation:g});else throw new X("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(s){if(!g&&(k.phase!=="verify"||k.status!=="await-user"||k.loop.next_action!=="confirm-skill-coordinated-pass"))throw new X("--accept-result is only valid for a pending Verify pass decision");S=await Lm({paths:w.paths,name:r,expectedContinuation:g,finish:c})}else if(l){if(k.phase!=="verify")throw new X("--revise-implementation is only valid from Verify");S=await nn({paths:w.paths,name:r,reason:i,expectedContinuation:g})}else if(u){if(!g&&k.phase!=="verify"&&k.phase!=="archive")throw new X("--revise-requirements is only valid from Verify or Archive");S=await ks({paths:w.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:g})}else if(d)S=await Bm({paths:w.paths,name:r,expectedContinuation:g});else if(p)S=await Dm({paths:w.paths,name:r,reason:i,expectedContinuation:g});else{if(x.reason!=="available"){let ue=((await Le({paths:w.paths,state:k}))?.confirmed?await D(w.paths,k.name,{diagnostics:!0}):null)?.children.flatMap(({task:de})=>de?[ri(de,k.name,w.paths.projectRoot)]:[])??[];return et("next",{state:Pe(k,w.paths),recovery:CE(x),...await pr(w.paths,k),...ue.length>0?{supervisorTasks:ue}:{}})}if(k.phase==="build"){let _=await Ns({paths:w.paths,state:k});if(_.drifted)S=await ks({paths:w.paths,name:r,reason:_.reason??"Native confirmed requirements changed",keepFailureBudget:!0});else{let j=await Le({paths:w.paths,state:k});if(j){let ue=j,de=[],Or=[],tt=null,hr=await D(w.paths,r);if(hr&&!j.allDone){let _e=await qf({paths:w.paths,parent:r,maxParallel:k.coordination_mode==="single-session"?1:v});de=_e.state.children.flatMap(({task:Ae})=>Ae?[ri(Ae,r,w.paths.projectRoot)]:[]),tt=_e.tasks.map(({child:Ae})=>Ae),Or=_e.state.children.flatMap(({name:Ae,blocker:ga})=>ga?[{child:Ae,message:ga}]:[]),(de.length>0||_e.state.stateVersion!==hr.stateVersion)&&(ue=await Le({paths:w.paths,state:k})??ue)}if(ue.allDone&&!(k.loop.stage==="repairing"&&k.verification_result==="fail"))C=await _s({paths:w.paths,name:r,trigger:"recovery"}),S=C.state;else return et("next",{state:Pe(k,w.paths),childSummary:ue.children.reduce((_e,Ae)=>({..._e,[Ae.status]:(_e[Ae.status]??0)+1}),{total:ue.children.length}),readyChildren:tt??ue.readyChildren,...de.length>0?{supervisorTasks:de}:{},...Or.length>0?{supervisorBlockers:Or}:{},continuation:Y(k,ue)})}}}if(k.phase==="shape"&&(S=await bm({paths:w.paths,name:r,enforceDocumentConstraints:!0,...f===void 0?{}:{coordinationMode:f},expectedContinuation:g})),S)return et("next",{state:Pe(S,w.paths),...C?{parentAdvance:C.parentAdvance}:{},...await pr(w.paths,S)});let P=k.phase==="shape"?await Le({paths:w.paths,state:k}):null;return et("next",{state:Pe(k,w.paths),continuation:Y(k,P)})}return et("next",{state:Pe(S,w.paths),...f===void 0?{}:{coordinationMode:f},...await pr(w.paths,S)})}async function PE(e,t,r,i){let n=Y(t),a=t.language==="zh-CN"?`先恢复此需求绑定的工作区和分支,再运行 comet native status ${r} --json 获取下一步;当前操作未推进状态,不要重复请求验收确认。`:`Restore the workspace and branch bound to this change, then run comet native status ${r} --json for the next action. No transition occurred; do not request acceptance again.`;return et("next",{state:Pe(t,e),...await pr(e,t),recovery:{action:"await-user",reason:"workspace-mismatch",message:i},continuation:{...n,disposition:"blocked",requiresUserDecision:!1,action:"repair",commandArgs:null,commandAlternatives:[],requiredInputs:[],inputOptions:[],runnerAction:{...n.runnerAction,kind:"none"},userCommunication:{required:!0,message:`${i}. ${a}`,suggestedReply:null,agentInstruction:a}}})}async function AE(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{Vt(n,"--json"),Vt(n,"--verbose"),c=dr(n,"--project-root");let d=[...n,...a],p=async()=>{let h=await kE(c);return{executionCwd:h,...await t(d,h)}};l=SE(e,d)?await Uw(p):await p()}catch(d){l=on(e,d)}let u=RE(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
393
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}function $B(e,t,r=!1){let i=TB(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 HE(e,t,r=!1){return $B(e,t,r).output}var jB=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function OB(e){let t=dr(e,"--expected-state-version"),r=dr(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new X("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new X("--expected-state-version must be a positive integer");if(!jB.has(r))throw new X("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function pr(e,t,r,i,n){let a=await tm({paths:e,name:t.name});a.local&&(r??=Qh(t,a.local),i===void 0&&(i=yS(a.local,a.local.workspace.projectRoot)));let o=await Le({paths:e,state:t}),s=o?.confirmed?await D(e,t.name,{diagnostics:!0}):null,c=s?.children.flatMap(({task:p})=>p?[p.child]:[])??[],l=s?.integration.checkExecution,u=l?.status==="interrupted"?(l.checkStates??[]).filter(({status:p})=>p==="interrupted").map(({id:p})=>p):void 0;return{...o?{childSummary:o.children.reduce((p,d)=>({...p,[d.status]:(p[d.status]??0)+1}),{total:o.children.length}),readyChildren:c.length>0?c:o.readyChildren}:{},continuation:Y(t,o,{verifierExecutionRef:r,verifierStartup:jk(t,a.localStatus==="available"?a.local:null),verificationCheckPlans:i,retryCheckIds:n,supervisorIntegrationRetryIds:u})}}function HB(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"&&t!=="continuationCheckPlans"&&t!=="continuationRetryCheckIds"))}function DE(e){return{action:e.action,reason:e.reason,message:e.message}}async function LE(e,t){let r=IE(e,"change name"),i=dr(e,"--summary"),n=dr(e,"--runner-input"),a=Vt(e,"--validate-only"),o=Vt(e,"--confirmed"),s=Vt(e,"--accept-result"),c=dr(e,"--finish");if(c!==void 0&&(!s||!["keep","merge","push","pull-request"].includes(c)))throw new X("--finish requires --accept-result and must be keep, merge, push, or pull-request");let l=Vt(e,"--revise-implementation"),u=Vt(e,"--revise-requirements"),p=Vt(e,"--retry-verifier"),d=Vt(e,"--resolve-verifier-blocker"),f=dr(e,"--coordination-mode"),h=f;if(f!==void 0&&!ol.includes(f))throw new X("--coordination-mode must be multi-session or single-session");if(a&&n===void 0)throw new X("--validate-only requires --runner-input");let m=dr(e,"--max-parallel"),v=m===void 0?2:Number(m);if(!Number.isSafeInteger(v)||v<1)throw new X("--max-parallel must be a positive integer");let g=OB(e);if([o,s,l,u,p,d].filter(Boolean).length>1)throw new X("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(h!==void 0&&(s||l||u||p||d||n!==void 0))throw new X("--coordination-mode is only valid when preparing or confirming a Supervisor Shape");AE(e);let w=await jE(t),N=await zS(w.paths,r);if(!await aa(w.paths,r)){if(N){let _={schema:"comet.native.continuation.v2",skill:"comet-native",change:r,phase:"archive",status:"blocked",disposition:"blocked",requiresUserDecision:!1,action:"archive",commandArgs:N.result?.recoveryArgs??["comet","native","archive",r,"--confirmed"],requiredInputs:[],inputOptions:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0},userCommunication:{required:!0,message:N.result?.message??"Native Archive completed, but workspace finish is still pending.",suggestedReply:null,agentInstruction:"Report the blocker and resolve it within the recorded delivery authorization, then retry the recorded command. Ask only if new information or authorization is needed; a retry of the same finish does not need another confirmation."}};return{command:"next",exitCode:73,data:{change:r,archived:!0,workspaceFinishResult:N.result,continuation:_},error:{code:"conflict",message:N.result?.message??"Native Archive completed, but workspace finish is still pending"}}}if(n)throw new X("--runner-input is only valid for portable Native changes");if(!i)throw new X("--summary is required");let P=await ZS({paths:w.paths,name:r});return et("next",{state:Pe(P,w.paths),migration:{completed:!0,summary:i},continuation:Y(P)})}let y=await H(w.paths,r);if(a){if(i||o||s||l||u||p||d||g||h!==void 0)throw new X("--validate-only cannot be combined with --summary, continuation expectations, or coordination mode");let P;try{P=await Qm(n,t)}catch(_){let j=sn("next",_);return{...j,data:{...j.data&&typeof j.data=="object"?j.data:{},state:Pe(y,w.paths),continuation:Y(y)}}}try{await ev({paths:w.paths,name:r,state:y,input:P,projectRoot:t})}catch(_){let j=sn("next",_);return{...j,data:{...j.data&&typeof j.data=="object"?j.data:{},state:Pe(y,w.paths),continuation:Y(y)}}}return et("next",{validation:{valid:!0,kind:P.kind},state:Pe(y,w.paths),continuation:Y(y)})}if(n!==void 0||!i||y.phase==="verify"||y.phase==="archive"||y.verification_result==="pass"){let P=Gm(w.paths,y);if(P)return BE(w.paths,y,r,P)}if(n){if(i||o||s||l||u||p||d||h!==void 0||g)throw new X("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let P;try{P=await Qm(n,t),await Zm({paths:w.paths,file:n,input:P}),await ev({paths:w.paths,name:r,state:y,input:P,projectRoot:t}),y.document_constraints_version===1&&await Hu({paths:w.paths,state:y})}catch(fr){let _e=sn("next",fr);return{..._e,data:{..._e.data&&typeof _e.data=="object"?_e.data:{},state:Pe(y,w.paths),continuation:Y(y)}}}let _=await Wu({paths:w.paths,name:r});if(_.action==="rerun-final-verification")return et("next",{state:Pe(_.state,w.paths),...await pr(w.paths,_.state)});let j=await Jm({paths:w.paths,name:r,preserveRunningExecution:!0}),ue=j.state;if(j.action==="await-user"||j.action==="done"||j.reason!=="available")return et("next",{state:Pe(ue,w.paths),recovery:DE(j),...await pr(w.paths,ue)});if(ue.phase==="build"){let fr=await Es({paths:w.paths,state:ue});if(fr.drifted){let wa=await xs({paths:w.paths,name:r,reason:fr.reason??"Native confirmed requirements changed",keepFailureBudget:!0});return et("next",{state:Pe(wa,w.paths),...await pr(w.paths,wa)})}let _e=await D(w.paths,r),Ae=await Le({paths:w.paths,state:ue});if(Ae&&!Ae.allDone&&!_e)throw new X("Native parent Build advances child changes and does not accept a Builder handoff")}let de;try{de=await fE({paths:w.paths,name:r,input:P,inputFile:n,maxVerifyFailures:w.config.native.max_verify_failures})}catch(fr){let _e=await H(w.paths,r),Ae=sn("next",fr);return{...Ae,data:{...Ae.data&&typeof Ae.data=="object"?Ae.data:{},state:Pe(_e,w.paths),...await pr(w.paths,_e)}}}let Or="continuationCheckPlans"in de?de.continuationCheckPlans:void 0,tt="continuationRetryCheckIds"in de?de.continuationRetryCheckIds:void 0;return et("next",{...HB(de),state:Pe(de.state,w.paths),...await pr(w.paths,de.state,de.verifierDispatch?.verifierExecutionRef,Or,tt),coordination:Se})}if(!i)throw new X("--summary is required");let b=await Wu({paths:w.paths,name:r});if(b.action==="rerun-final-verification")return et("next",{state:Pe(b.state,w.paths),...await pr(w.paths,b.state)});let x=await Jm({paths:w.paths,name:r}),k=x.state;if(x.reason==="workspace-mismatch")return BE(w.paths,k,r,x.message);if(h!==void 0&&k.phase!=="shape")throw new X("--coordination-mode is only valid when confirming Shape");let S,C=null;if(o)if(k.phase==="shape"&&k.status==="await-user"&&k.loop.next_action==="confirm-shape"){if(!g)throw new X("--expected-state-version and --expected-action are required for Shape confirmation");S=await jm({paths:w.paths,name:r,expectedContinuation:g,...h===void 0?{}:{coordinationMode:h}})}else{if(k.phase==="shape")throw new X("--confirmed is only valid from the persisted Shape user confirmation boundary");if(k.phase==="verify"&&k.status==="await-user"&&k.loop.next_action==="confirm-verifier-unavailable")S=await qm({paths:w.paths,name:r,summary:i,expectedContinuation:g});else throw new X("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(s){if(!g&&(k.phase!=="verify"||k.status!=="await-user"||k.loop.next_action!=="confirm-skill-coordinated-pass"))throw new X("--accept-result is only valid for a pending Verify pass decision");S=await Wm({paths:w.paths,name:r,expectedContinuation:g,finish:c})}else if(l){if(k.phase!=="verify")throw new X("--revise-implementation is only valid from Verify");S=await an({paths:w.paths,name:r,reason:i,expectedContinuation:g})}else if(u){if(!g&&k.phase!=="verify"&&k.phase!=="archive")throw new X("--revise-requirements is only valid from Verify or Archive");S=await xs({paths:w.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:g})}else if(p)S=await Vm({paths:w.paths,name:r,expectedContinuation:g});else if(d)S=await Mm({paths:w.paths,name:r,reason:i,expectedContinuation:g});else{if(x.reason!=="available"){let ue=((await Le({paths:w.paths,state:k}))?.confirmed?await D(w.paths,k.name,{diagnostics:!0}):null)?.children.flatMap(({task:de})=>de?[ri(de,k.name,w.paths.projectRoot)]:[])??[];return et("next",{state:Pe(k,w.paths),recovery:DE(x),...await pr(w.paths,k),...ue.length>0?{supervisorTasks:ue}:{}})}if(k.phase==="build"){let _=await Es({paths:w.paths,state:k});if(_.drifted)S=await xs({paths:w.paths,name:r,reason:_.reason??"Native confirmed requirements changed",keepFailureBudget:!0});else{let j=await Le({paths:w.paths,state:k});if(j){let ue=j,de=[],Or=[],tt=null,fr=await D(w.paths,r);if(fr&&!j.allDone){let _e=await Vh({paths:w.paths,parent:r,maxParallel:k.coordination_mode==="single-session"?1:v});de=_e.state.children.flatMap(({task:Ae})=>Ae?[ri(Ae,r,w.paths.projectRoot)]:[]),tt=_e.tasks.map(({child:Ae})=>Ae),Or=_e.state.children.flatMap(({name:Ae,blocker:wa})=>wa?[{child:Ae,message:wa}]:[]),(de.length>0||_e.state.stateVersion!==fr.stateVersion)&&(ue=await Le({paths:w.paths,state:k})??ue)}if(ue.allDone&&!(k.loop.stage==="repairing"&&k.verification_result==="fail"))C=await Ts({paths:w.paths,name:r,trigger:"recovery"}),S=C.state;else return et("next",{state:Pe(k,w.paths),childSummary:ue.children.reduce((_e,Ae)=>({..._e,[Ae.status]:(_e[Ae.status]??0)+1}),{total:ue.children.length}),readyChildren:tt??ue.readyChildren,...de.length>0?{supervisorTasks:de}:{},...Or.length>0?{supervisorBlockers:Or}:{},continuation:Y(k,ue)})}}}if(k.phase==="shape"&&(S=await xm({paths:w.paths,name:r,enforceDocumentConstraints:!0,...h===void 0?{}:{coordinationMode:h},expectedContinuation:g})),S)return et("next",{state:Pe(S,w.paths),...C?{parentAdvance:C.parentAdvance}:{},...await pr(w.paths,S)});let P=k.phase==="shape"?await Le({paths:w.paths,state:k}):null;return et("next",{state:Pe(k,w.paths),continuation:Y(k,P)})}return et("next",{state:Pe(S,w.paths),...h===void 0?{}:{coordinationMode:h},...await pr(w.paths,S)})}async function BE(e,t,r,i){let n=Y(t),a=t.language==="zh-CN"?`先恢复此需求绑定的工作区和分支,再运行 comet native status ${r} --json 获取下一步;当前操作未推进状态,不要重复请求验收确认。`:`Restore the workspace and branch bound to this change, then run comet native status ${r} --json for the next action. No transition occurred; do not request acceptance again.`;return et("next",{state:Pe(t,e),...await pr(e,t),recovery:{action:"await-user",reason:"workspace-mismatch",message:i},continuation:{...n,disposition:"blocked",requiresUserDecision:!1,action:"repair",commandArgs:null,commandAlternatives:[],requiredInputs:[],inputOptions:[],runnerAction:{...n.runnerAction,kind:"none"},userCommunication:{required:!0,message:`${i}. ${a}`,suggestedReply:null,agentInstruction:a}}})}async function FE(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{Vt(n,"--json"),Vt(n,"--verbose"),c=dr(n,"--project-root");let p=[...n,...a],d=async()=>{let f=await TE(c);return{executionCwd:f,...await t(p,f)}};l=$E(e,p)?await Zw(d):await d()}catch(p){l=sn(e,p)}let u=HE(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
387
394
|
`)?"":`
|
|
388
|
-
`)),u.exitCode}process.exitCode=await
|
|
395
|
+
`)),u.exitCode}process.exitCode=await FE("next",LE);
|