@rpamis/comet 0.4.0-rc.3 → 0.4.0-rc.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/LICENSE +21 -21
- package/README.md +1 -0
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +2 -2
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +56 -56
- package/assets/skills/comet/scripts/comet-guard.mjs +51 -51
- package/assets/skills/comet/scripts/comet-handoff.mjs +29 -29
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +35 -35
- package/assets/skills/comet/scripts/comet-hook-router.mjs +162 -156
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +34 -34
- package/assets/skills/comet/scripts/comet-runtime.mjs +69 -69
- package/assets/skills/comet/scripts/comet-state.mjs +38 -38
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +20 -20
- package/assets/skills/comet-native/SKILL.md +6 -7
- package/assets/skills/comet-native/reference/artifacts.md +1 -2
- package/assets/skills/comet-native/reference/clarification.md +6 -6
- package/assets/skills/comet-native/reference/commands.md +2 -0
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +127 -126
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +136 -135
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +61 -60
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +30 -29
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +125 -124
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +123 -122
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +16 -15
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +165 -164
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +111 -110
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +81 -80
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +118 -117
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +108 -107
- package/assets/skills-zh/comet-native/SKILL.md +6 -7
- package/assets/skills-zh/comet-native/reference/artifacts.md +1 -2
- package/assets/skills-zh/comet-native/reference/clarification.md +6 -6
- package/assets/skills-zh/comet-native/reference/commands.md +2 -0
- package/dist/app/cli/index.js +16 -0
- package/dist/app/cli/index.js.map +1 -1
- package/dist/app/commands/comet-task.d.ts +3 -0
- package/dist/app/commands/comet-task.d.ts.map +1 -1
- package/dist/app/commands/comet-task.js +21 -0
- package/dist/app/commands/comet-task.js.map +1 -1
- package/dist/app/commands/native.js +2 -0
- package/dist/app/commands/native.js.map +1 -1
- package/dist/app/commands/personal-memory.d.ts.map +1 -1
- package/dist/app/commands/personal-memory.js +1 -0
- package/dist/app/commands/personal-memory.js.map +1 -1
- package/dist/app/commands/project-knowledge.d.ts +3 -0
- package/dist/app/commands/project-knowledge.d.ts.map +1 -1
- package/dist/app/commands/project-knowledge.js +39 -1
- package/dist/app/commands/project-knowledge.js.map +1 -1
- package/dist/domains/agent-learning/context-director.d.ts +14 -5
- package/dist/domains/agent-learning/context-director.d.ts.map +1 -1
- package/dist/domains/agent-learning/context-director.js +106 -26
- package/dist/domains/agent-learning/context-director.js.map +1 -1
- package/dist/domains/comet-entry/plugin-context.d.ts +2 -1
- package/dist/domains/comet-entry/plugin-context.d.ts.map +1 -1
- package/dist/domains/comet-entry/plugin-context.js +10 -1
- package/dist/domains/comet-entry/plugin-context.js.map +1 -1
- package/dist/domains/comet-memory/personal-memory.d.ts.map +1 -1
- package/dist/domains/comet-memory/personal-memory.js +126 -33
- package/dist/domains/comet-memory/personal-memory.js.map +1 -1
- package/dist/domains/comet-memory/plugin.js +3 -1
- package/dist/domains/comet-memory/plugin.js.map +1 -1
- package/dist/domains/comet-memory/types.d.ts +7 -0
- package/dist/domains/comet-memory/types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-archive-command.js +119 -19
- package/dist/domains/comet-native/native-archive-command.js.map +1 -1
- package/dist/domains/comet-native/native-artifacts.d.ts +1 -0
- package/dist/domains/comet-native/native-artifacts.d.ts.map +1 -1
- package/dist/domains/comet-native/native-artifacts.js +53 -2
- package/dist/domains/comet-native/native-artifacts.js.map +1 -1
- package/dist/domains/comet-native/native-children.d.ts +1 -0
- package/dist/domains/comet-native/native-children.d.ts.map +1 -1
- package/dist/domains/comet-native/native-children.js +1 -0
- package/dist/domains/comet-native/native-children.js.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +6 -6
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-doctor-command.js +41 -1
- package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
- package/dist/domains/comet-native/native-experience.d.ts.map +1 -1
- package/dist/domains/comet-native/native-experience.js +23 -10
- package/dist/domains/comet-native/native-experience.js.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.d.ts +4 -0
- package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.js +29 -2
- package/dist/domains/comet-native/native-loop-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-next-command.js +42 -18
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts +11 -4
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +173 -15
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-portable-recovery.d.ts +1 -1
- package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-recovery.js +26 -1
- package/dist/domains/comet-native/native-portable-recovery.js.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.d.ts +7 -1
- package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.js +163 -11
- package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-state.js +6 -0
- package/dist/domains/comet-native/native-portable-state.js.map +1 -1
- package/dist/domains/comet-native/native-portable-status.d.ts +5 -0
- package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-status.js +21 -1
- package/dist/domains/comet-native/native-portable-status.js.map +1 -1
- package/dist/domains/comet-native/native-portable-summary.d.ts +7 -1
- package/dist/domains/comet-native/native-portable-summary.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-summary.js +20 -1
- package/dist/domains/comet-native/native-portable-summary.js.map +1 -1
- package/dist/domains/comet-native/native-portable-types.d.ts +1 -0
- package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-types.js.map +1 -1
- package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
- package/dist/domains/comet-native/native-runner-input.js +12 -4
- package/dist/domains/comet-native/native-runner-input.js.map +1 -1
- package/dist/domains/comet-native/native-supervisor-overlay.d.ts +30 -0
- package/dist/domains/comet-native/native-supervisor-overlay.d.ts.map +1 -0
- package/dist/domains/comet-native/native-supervisor-overlay.js +202 -0
- package/dist/domains/comet-native/native-supervisor-overlay.js.map +1 -0
- package/dist/domains/comet-native/native-supervisor.d.ts.map +1 -1
- package/dist/domains/comet-native/native-supervisor.js +7 -3
- package/dist/domains/comet-native/native-supervisor.js.map +1 -1
- package/dist/domains/comet-native/native-types.d.ts +1 -0
- package/dist/domains/comet-native/native-types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-workspace-finish.d.ts +12 -1
- package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -1
- package/dist/domains/comet-native/native-workspace-finish.js +77 -22
- package/dist/domains/comet-native/native-workspace-finish.js.map +1 -1
- package/dist/domains/comet-plugin/integration.d.ts +2 -2
- package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
- package/dist/domains/comet-plugin/integration.js +22 -4
- package/dist/domains/comet-plugin/integration.js.map +1 -1
- package/dist/domains/dashboard/web/assets/{abnfDiagram-VCTEODGH-UcCx24DV.js → abnfDiagram-VCTEODGH-DktP_xx6.js} +1 -1
- package/dist/domains/dashboard/web/assets/{arc-n8qsRq7W.js → arc-Bn1VKVxB.js} +1 -1
- package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-Doz1cLoT.js +1 -0
- package/dist/domains/dashboard/web/assets/{architectureDiagram-5GKGNRK7-D4pJ8CU0.js → architectureDiagram-5GKGNRK7-B968UcrU.js} +1 -1
- package/dist/domains/dashboard/web/assets/{blockDiagram-I7D4REHJ-C7n-qrSQ.js → blockDiagram-I7D4REHJ-Ben_8wAV.js} +1 -1
- package/dist/domains/dashboard/web/assets/{c4Diagram-7LVT6UL2-cMVrWYOm.js → c4Diagram-7LVT6UL2-Dob7HfzV.js} +1 -1
- package/dist/domains/dashboard/web/assets/channel-CVf4X4BV.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-4HAMMTFA-CE5QrCQd.js → chunk-4HAMMTFA-WLtkq7Gw.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-75Z2AOVW-BtZqN-pM.js → chunk-75Z2AOVW-DPRWDP1s.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-DU6HZSFF-CChv0huc.js → chunk-DU6HZSFF-B4Z8Mce9.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-F27PBJKO-CDT1ttJ8.js → chunk-F27PBJKO-D5FH4UPb.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-GMAD6QVW-y5m6LMR7.js → chunk-GMAD6QVW-D0gALUpa.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-GVQU2GXP-DkhKkaHd.js → chunk-GVQU2GXP-Cz71fWUR.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-IMKFNOWR-BaDSh7Jp.js → chunk-IMKFNOWR-Bqryqw0r.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-L3NEJ4N5-B4ztH2fV.js → chunk-L3NEJ4N5-CJKqYHaP.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-OSK3NFVY-BhX6NVzA.js → chunk-OSK3NFVY-C-anVJYL.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-P2QGCYS3-BCNdGJkX.js → chunk-P2QGCYS3-D-IhFZGl.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-POPQ4Y6H-DwYVuiXw.js → chunk-POPQ4Y6H-DHZ2x8cS.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-PWAF6VOD-Cyg0IO0R.js → chunk-PWAF6VOD-DfS3bSOb.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-SHT3W25Y-BZ6skx8I.js → chunk-SHT3W25Y-D3iDzF3T.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-SVP7TREG-CLIGmSO0.js → chunk-SVP7TREG-BQunJ2lh.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-TICWLB2K-BAQBbsn9.js → chunk-TICWLB2K-BaqCQLlB.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-D07UbEpV.js → chunk-XXDRQBXY-mmlWRTLt.js} +1 -1
- package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-DXerFgpQ.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-DXerFgpQ.js +1 -0
- package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-wIi0mUih.js → cose-bilkent-JH36ORCC-D3cS4IXf.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefin-OW5HDTMX-DBdxyuTN.js → cynefin-OW5HDTMX-DE1IHUyY.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefinDiagram-5FMLGOSQ-DzO3jXxV.js → cynefinDiagram-5FMLGOSQ-DzqK0Tbz.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dagre-GXQ25YYZ-CE7H_hZS.js → dagre-GXQ25YYZ-AI4ZWaO2.js} +1 -1
- package/dist/domains/dashboard/web/assets/{demo-DrJ2uuUL.js → demo-COS52Sbp.js} +8 -8
- package/dist/domains/dashboard/web/assets/{diagram-S7CK7UJ4-jUGQk5n-.js → diagram-S7CK7UJ4-g0XXZtEw.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-UQ7AKVKN-DaH_zW8T.js → diagram-UQ7AKVKN-Cms0TctP.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-VSXAHHWV-DmG80db0.js → diagram-VSXAHHWV-1FH11lSW.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-VX7I27RA-ltQ6niKn.js → diagram-VX7I27RA-6k2xns6T.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-Z3DM3KII-x92ex4lK.js → diagram-Z3DM3KII-7VmVYxMS.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dist-Cf0h0n6i.js → dist-C3Eu0v0t.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ebnfDiagram-PWID7BFC-CI2u976k.js → ebnfDiagram-PWID7BFC-CIbiadEp.js} +1 -1
- package/dist/domains/dashboard/web/assets/{erDiagram-RLTQ6QDP-DKs90SRd.js → erDiagram-RLTQ6QDP-Cge5wrQ7.js} +1 -1
- package/dist/domains/dashboard/web/assets/{es-D7xGlyQk.js → es-BBSVi8Cm.js} +1 -1
- package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-BNDjhcIe.js +1 -0
- package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-BfAyylTq.js +1 -0
- package/dist/domains/dashboard/web/assets/{ganttDiagram-EL5Y4UJY-D3z6G60S.js → ganttDiagram-EL5Y4UJY-Dr4gcis6.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraph-4MIJSDKK-vT1UnORT.js → gitGraph-4MIJSDKK-DzFO7GXq.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraphDiagram-WWUBYQGX-BJmJ96jv.js → gitGraphDiagram-WWUBYQGX-jCmQLI23.js} +1 -1
- package/dist/domains/dashboard/web/assets/index-Cu7ImK90.js +261 -0
- package/dist/domains/dashboard/web/assets/index-st3h1lQU.css +1 -0
- package/dist/domains/dashboard/web/assets/{info-A6RAGUB7-DFeLqqen.js → info-A6RAGUB7-CFW1R5j4.js} +1 -1
- package/dist/domains/dashboard/web/assets/{infoDiagram-27XIBGKW-DxuY43XD.js → infoDiagram-27XIBGKW-DXRLxyIw.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ishikawaDiagram-5VMMS53U-DxillfWQ.js → ishikawaDiagram-5VMMS53U-27Bkcq65.js} +1 -1
- package/dist/domains/dashboard/web/assets/{journeyDiagram-3NMN7TZE-BPngQ3ag.js → journeyDiagram-3NMN7TZE-CNTUOJev.js} +1 -1
- package/dist/domains/dashboard/web/assets/{kanban-definition-UXKFOSKX-DHMLEGD4.js → kanban-definition-UXKFOSKX-wxkpxo_z.js} +1 -1
- package/dist/domains/dashboard/web/assets/{line-D31peBjo.js → line-COcnxdlo.js} +1 -1
- package/dist/domains/dashboard/web/assets/{linear-B7X50T2m.js → linear-BYi1bTXs.js} +1 -1
- package/dist/domains/dashboard/web/assets/{mermaid-parser.core-CX3Pzygh.js → mermaid-parser.core-j8j63RgF.js} +3 -3
- package/dist/domains/dashboard/web/assets/{mermaid.core-DlMjBFb6.js → mermaid.core-BU_qb_8K.js} +4 -4
- package/dist/domains/dashboard/web/assets/{mindmap-definition-YA3MSWOX-BKuSGF75.js → mindmap-definition-YA3MSWOX-G0BDXvKi.js} +1 -1
- package/dist/domains/dashboard/web/assets/{packet-AYTQ26CC-B1T8Bds9.js → packet-AYTQ26CC-JORyJlKy.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pegDiagram-XKGWAZYB-BYgTNxLw.js → pegDiagram-XKGWAZYB-hA0fUEjQ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pie-WAS4IAKB-fqAjmoQw.js → pie-WAS4IAKB-gWVXoOeL.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pieDiagram-E7YTZNPT-BAO0Ufky.js → pieDiagram-E7YTZNPT-_NamTf64.js} +1 -1
- package/dist/domains/dashboard/web/assets/{quadrantDiagram-AXDQQJYC-SA_1-7DT.js → quadrantDiagram-AXDQQJYC-BUU5A24c.js} +1 -1
- package/dist/domains/dashboard/web/assets/{radar-RG4KPBEZ-Bl_UfUle.js → radar-RG4KPBEZ-BHdo5LzP.js} +1 -1
- package/dist/domains/dashboard/web/assets/{railroad-74A4TZTK-yj6dkiSy.js → railroad-74A4TZTK-DT_vTugC.js} +1 -1
- package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CADAqTZD.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-6x_wNdA6.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-D2Az23Om.js +1 -0
- package/dist/domains/dashboard/web/assets/{railroadDiagram-O6MQD6OU-DqV18Y46.js → railroadDiagram-O6MQD6OU-BdOuWAHc.js} +1 -1
- package/dist/domains/dashboard/web/assets/{requirementDiagram-BXWQKSXE-Ca2K5LuT.js → requirementDiagram-BXWQKSXE-oNwG2AbA.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sankeyDiagram-P5KCCOFB-D9MKl-Nr.js → sankeyDiagram-P5KCCOFB-DfAhDJhA.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sequenceDiagram-WJ2MYXX4-CXfvIzRx.js → sequenceDiagram-WJ2MYXX4-IlotrNmf.js} +1 -1
- package/dist/domains/dashboard/web/assets/{src-CquUPIQx.js → src-Dcq60QMV.js} +1 -1
- package/dist/domains/dashboard/web/assets/{stateDiagram-D77RDMKH-B7iaZHW7.js → stateDiagram-D77RDMKH-7_W4JVdo.js} +1 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-Co817OY3.js +1 -0
- package/dist/domains/dashboard/web/assets/{swimlanes-42K2YHIH-OK-62yZl.js → swimlanes-42K2YHIH-d31leTl1.js} +1 -1
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-DYbLacQM.js +8 -0
- package/dist/domains/dashboard/web/assets/{timeline-definition-24CTP7MA-D0l01B1h.js → timeline-definition-24CTP7MA-nWxcdycl.js} +1 -1
- package/dist/domains/dashboard/web/assets/{treeView-Q6P3EWNA-Bg5u_o3A.js → treeView-Q6P3EWNA-5Mutr1Nu.js} +1 -1
- package/dist/domains/dashboard/web/assets/{treemap-WGGIJYW6-x89ccozk.js → treemap-WGGIJYW6-C36e-gzl.js} +1 -1
- package/dist/domains/dashboard/web/assets/{vennDiagram-4TSXK5OY-DV19Cqhv.js → vennDiagram-4TSXK5OY-DozZoQRR.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardley-WFR3VGLG-BWoeoVk5.js → wardley-WFR3VGLG-Bz4TuX9w.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardleyDiagram-VM6X3IG4-D4fCpoIP.js → wardleyDiagram-VM6X3IG4-DwSpGS7T.js} +1 -1
- package/dist/domains/dashboard/web/assets/{xychartDiagram-S5SC5T6Z-DALnOMLb.js → xychartDiagram-S5SC5T6Z-DZ3ysAHJ.js} +1 -1
- package/dist/domains/dashboard/web/index.html +16 -16
- package/dist/domains/eval/agent-learning-eval.js +1 -1
- package/dist/domains/eval/agent-learning-eval.js.map +1 -1
- package/dist/domains/project-knowledge/corpus.d.ts.map +1 -1
- package/dist/domains/project-knowledge/corpus.js +13 -13
- package/dist/domains/project-knowledge/corpus.js.map +1 -1
- package/dist/domains/project-knowledge/deterministic-extractors.d.ts +5 -0
- package/dist/domains/project-knowledge/deterministic-extractors.d.ts.map +1 -1
- package/dist/domains/project-knowledge/deterministic-extractors.js +381 -184
- package/dist/domains/project-knowledge/deterministic-extractors.js.map +1 -1
- package/dist/domains/project-knowledge/host-review.d.ts +19 -0
- package/dist/domains/project-knowledge/host-review.d.ts.map +1 -0
- package/dist/domains/project-knowledge/host-review.js +87 -0
- package/dist/domains/project-knowledge/host-review.js.map +1 -0
- package/dist/domains/project-knowledge/index-store.d.ts +1 -1
- package/dist/domains/project-knowledge/index-store.d.ts.map +1 -1
- package/dist/domains/project-knowledge/index-store.js +21 -12
- package/dist/domains/project-knowledge/index-store.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 +1 -0
- package/dist/domains/project-knowledge/learning.d.ts.map +1 -1
- package/dist/domains/project-knowledge/learning.js +42 -17
- package/dist/domains/project-knowledge/learning.js.map +1 -1
- package/dist/domains/project-knowledge/local-provider.d.ts +1 -0
- package/dist/domains/project-knowledge/local-provider.d.ts.map +1 -1
- package/dist/domains/project-knowledge/local-provider.js +60 -11
- package/dist/domains/project-knowledge/local-provider.js.map +1 -1
- package/dist/domains/project-knowledge/local-store.d.ts +5 -1
- package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
- package/dist/domains/project-knowledge/local-store.js +366 -116
- package/dist/domains/project-knowledge/local-store.js.map +1 -1
- package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
- package/dist/domains/project-knowledge/plugin.js +68 -23
- package/dist/domains/project-knowledge/plugin.js.map +1 -1
- package/dist/domains/project-knowledge/query.d.ts.map +1 -1
- package/dist/domains/project-knowledge/query.js +32 -3
- package/dist/domains/project-knowledge/query.js.map +1 -1
- package/dist/domains/project-knowledge/readiness.d.ts +10 -0
- package/dist/domains/project-knowledge/readiness.d.ts.map +1 -0
- package/dist/domains/project-knowledge/readiness.js +65 -0
- package/dist/domains/project-knowledge/readiness.js.map +1 -0
- package/dist/domains/project-knowledge/records.d.ts +2 -0
- package/dist/domains/project-knowledge/records.d.ts.map +1 -1
- package/dist/domains/project-knowledge/records.js +8 -0
- package/dist/domains/project-knowledge/records.js.map +1 -1
- package/dist/domains/project-knowledge/types.d.ts +16 -0
- package/dist/domains/project-knowledge/types.d.ts.map +1 -1
- package/dist/domains/workflow-contract/protected-project-path.d.ts +4 -1
- package/dist/domains/workflow-contract/protected-project-path.d.ts.map +1 -1
- package/dist/domains/workflow-contract/protected-project-path.js +25 -1
- package/dist/domains/workflow-contract/protected-project-path.js.map +1 -1
- package/dist/platform/fs/race-safe-read.d.ts +14 -0
- package/dist/platform/fs/race-safe-read.d.ts.map +1 -1
- package/dist/platform/fs/race-safe-read.js +81 -0
- package/dist/platform/fs/race-safe-read.js.map +1 -1
- package/dist/platform/install/project-registry.d.ts.map +1 -1
- package/dist/platform/install/project-registry.js +76 -5
- package/dist/platform/install/project-registry.js.map +1 -1
- package/dist/platform/paths/project-path-selector.d.ts +3 -0
- package/dist/platform/paths/project-path-selector.d.ts.map +1 -0
- package/dist/platform/paths/project-path-selector.js +32 -0
- package/dist/platform/paths/project-path-selector.js.map +1 -0
- package/package.json +2 -1
- package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-B5p4GzJf.js +0 -1
- package/dist/domains/dashboard/web/assets/channel-BZeSeXVb.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-2fcinal6.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-2fcinal6.js +0 -1
- package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-uARcGZPD.js +0 -1
- package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-DXL1E4Bl.js +0 -1
- package/dist/domains/dashboard/web/assets/index-BG3MF8re.js +0 -261
- package/dist/domains/dashboard/web/assets/index-C2Hlo7VZ.css +0 -1
- package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CvouMciM.js +0 -1
- package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-CkYQEX72.js +0 -1
- package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-B0uYr48F.js +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-B6KoHQVe.js +0 -1
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-CjdOls9K.js +0 -8
|
@@ -1,77 +1,77 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`)}};
|
|
6
|
-
`)
|
|
4
|
+
var xP=Object.create;var Qm=Object.defineProperty;var AP=Object.getOwnPropertyDescriptor;var _P=Object.getOwnPropertyNames;var IP=Object.getPrototypeOf,TP=Object.prototype.hasOwnProperty;var Zs=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var jP=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of _P(t))!TP.call(e,n)&&n!==i&&Qm(e,n,{get:()=>t[n],enumerable:!(r=AP(t,n))||r.enumerable});return e};var $n=(e,t,i)=>(i=e!=null?xP(IP(e)):{},jP(t||!e||!e.__esModule?Qm(i,"default",{value:e,enumerable:!0}):i,e));var G=C($e=>{"use strict";var Ed=Symbol.for("yaml.alias"),cv=Symbol.for("yaml.document"),ic=Symbol.for("yaml.map"),lv=Symbol.for("yaml.pair"),Pd=Symbol.for("yaml.scalar"),rc=Symbol.for("yaml.seq"),Ci=Symbol.for("yaml.node.type"),LP=e=>!!e&&typeof e=="object"&&e[Ci]===Ed,MP=e=>!!e&&typeof e=="object"&&e[Ci]===cv,FP=e=>!!e&&typeof e=="object"&&e[Ci]===ic,BP=e=>!!e&&typeof e=="object"&&e[Ci]===lv,uv=e=>!!e&&typeof e=="object"&&e[Ci]===Pd,VP=e=>!!e&&typeof e=="object"&&e[Ci]===rc;function dv(e){if(e&&typeof e=="object")switch(e[Ci]){case ic:case rc:return!0}return!1}function qP(e){if(e&&typeof e=="object")switch(e[Ci]){case Ed:case ic:case Pd:case rc:return!0}return!1}var WP=e=>(uv(e)||dv(e))&&!!e.anchor;$e.ALIAS=Ed;$e.DOC=cv;$e.MAP=ic;$e.NODE_TYPE=Ci;$e.PAIR=lv;$e.SCALAR=Pd;$e.SEQ=rc;$e.hasAnchor=WP;$e.isAlias=LP;$e.isCollection=dv;$e.isDocument=MP;$e.isMap=FP;$e.isNode=qP;$e.isPair=BP;$e.isScalar=uv;$e.isSeq=VP});var Qa=C(Rd=>{"use strict";var xe=G(),ot=Symbol("break visit"),fv=Symbol("skip children"),ci=Symbol("remove node");function nc(e,t){let i=hv(t);xe.isDocument(e)?On(null,e.contents,i,Object.freeze([e]))===ci&&(e.contents=null):On(null,e,i,Object.freeze([]))}nc.BREAK=ot;nc.SKIP=fv;nc.REMOVE=ci;function On(e,t,i,r){let n=pv(e,t,i,r);if(xe.isNode(n)||xe.isPair(n))return mv(e,r,n),On(e,n,i,r);if(typeof n!="symbol"){if(xe.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=On(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ot)return ot;o===ci&&(t.items.splice(a,1),a-=1)}}}else if(xe.isPair(t)){r=Object.freeze(r.concat(t));let a=On("key",t.key,i,r);if(a===ot)return ot;a===ci&&(t.key=null);let o=On("value",t.value,i,r);if(o===ot)return ot;o===ci&&(t.value=null)}}return n}async function ac(e,t){let i=hv(t);xe.isDocument(e)?await Hn(null,e.contents,i,Object.freeze([e]))===ci&&(e.contents=null):await Hn(null,e,i,Object.freeze([]))}ac.BREAK=ot;ac.SKIP=fv;ac.REMOVE=ci;async function Hn(e,t,i,r){let n=await pv(e,t,i,r);if(xe.isNode(n)||xe.isPair(n))return mv(e,r,n),Hn(e,n,i,r);if(typeof n!="symbol"){if(xe.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await Hn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ot)return ot;o===ci&&(t.items.splice(a,1),a-=1)}}}else if(xe.isPair(t)){r=Object.freeze(r.concat(t));let a=await Hn("key",t.key,i,r);if(a===ot)return ot;a===ci&&(t.key=null);let o=await Hn("value",t.value,i,r);if(o===ot)return ot;o===ci&&(t.value=null)}}return n}function hv(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,i,r){if(typeof i=="function")return i(e,t,r);if(xe.isMap(t))return i.Map?.(e,t,r);if(xe.isSeq(t))return i.Seq?.(e,t,r);if(xe.isPair(t))return i.Pair?.(e,t,r);if(xe.isScalar(t))return i.Scalar?.(e,t,r);if(xe.isAlias(t))return i.Alias?.(e,t,r)}function mv(e,t,i){let r=t[t.length-1];if(xe.isCollection(r))r.items[e]=i;else if(xe.isPair(r))e==="key"?r.key=i:r.value=i;else if(xe.isDocument(r))r.contents=i;else{let n=xe.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Rd.visit=nc;Rd.visitAsync=ac});var Cd=C(gv=>{"use strict";var vv=G(),zP=Qa(),JP={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},GP=e=>e.replace(/[!,[\]{}]/g,t=>JP[t]),Za=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+GP(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&vv.isNode(t.contents)){let a={};zP.visit(t.contents,(o,s)=>{vv.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
|
|
5
|
+
`)}};Za.defaultYaml={explicit:!1,version:"1.2"};Za.defaultTags={"!!":"tag:yaml.org,2002:"};gv.Directives=Za});var oc=C(eo=>{"use strict";var wv=G(),UP=Qa();function KP(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function yv(e){let t=new Set;return UP.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Nv(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function YP(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=yv(e));let o=Nv(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(wv.isScalar(o.node)||wv.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:r}}eo.anchorIsValid=KP;eo.anchorNames=yv;eo.createNodeAnchors=YP;eo.findNewAnchor=Nv});var xd=C(bv=>{"use strict";function to(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=to(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=to(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=to(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=to(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}bv.applyReviver=to});var Qi=C(Sv=>{"use strict";var XP=G();function kv(e,t,i){if(Array.isArray(e))return e.map((r,n)=>kv(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!XP.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}Sv.toJS=kv});var sc=C(Pv=>{"use strict";var QP=xd(),Ev=G(),ZP=Qi(),Ad=class{constructor(t){Object.defineProperty(this,Ev.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!Ev.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=ZP.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?QP.applyReviver(a,{"":s},"",s):s}};Pv.NodeBase=Ad});var io=C(Rv=>{"use strict";var eR=oc(),tR=Qa(),Dn=G(),iR=sc(),rR=Qi(),_d=class extends iR.NodeBase{constructor(t){super(Dn.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],tR.visit(t,{Node:(a,o)=>{(Dn.isAlias(o)||Dn.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(rR.toJS(o,null,i),s=r.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=cc(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if(eR.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 cc(e,t,i){if(Dn.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Dn.isCollection(t)){let r=0;for(let n of t.items){let a=cc(e,n,i);a>r&&(r=a)}return r}else if(Dn.isPair(t)){let r=cc(e,t.key,i),n=cc(e,t.value,i);return Math.max(r,n)}return 1}Rv.Alias=_d});var ke=C(Id=>{"use strict";var nR=G(),aR=sc(),oR=Qi(),sR=e=>!e||typeof e!="function"&&typeof e!="object",Zi=class extends aR.NodeBase{constructor(t){super(nR.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:oR.toJS(this.value,t,i)}toString(){return String(this.value)}};Zi.BLOCK_FOLDED="BLOCK_FOLDED";Zi.BLOCK_LITERAL="BLOCK_LITERAL";Zi.PLAIN="PLAIN";Zi.QUOTE_DOUBLE="QUOTE_DOUBLE";Zi.QUOTE_SINGLE="QUOTE_SINGLE";Id.Scalar=Zi;Id.isScalarValue=sR});var ro=C(xv=>{"use strict";var cR=io(),Xr=G(),Cv=ke(),lR="tag:yaml.org,2002:";function uR(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function dR(e,t,i){if(Xr.isDocument(e)&&(e=e.contents),Xr.isNode(e))return e;if(Xr.isPair(e)){let d=i.schema[Xr.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new cR.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=lR+t.slice(2));let l=uR(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Cv.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Xr.MAP]:Symbol.iterator in Object(e)?o[Xr.SEQ]:o[Xr.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new Cv.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}xv.createNode=dR});var uc=C(lc=>{"use strict";var fR=ro(),li=G(),hR=sc();function Td(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return fR.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Av=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,jd=class extends hR.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>li.isNode(r)||li.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Av(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(li.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Td(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(li.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&li.isScalar(a)?a.value:a:li.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!li.isPair(i))return!1;let r=i.value;return r==null||t&&li.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return li.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(li.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Td(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};lc.Collection=jd;lc.collectionFromPath=Td;lc.isEmptyPath=Av});var no=C(dc=>{"use strict";var pR=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function $d(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var mR=(e,t,i)=>e.endsWith(`
|
|
6
|
+
`)?$d(i,t):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
|
|
9
|
-
`)i===
|
|
10
|
-
`&&h!==" "){let
|
|
11
|
-
`&&
|
|
12
|
-
${t}${e.slice(0,k)}`:(i===
|
|
13
|
-
${t}${e.slice(
|
|
14
|
-
`);r=t,n=t+1,a=e[n]}return r}
|
|
15
|
-
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function
|
|
8
|
+
`+$d(i,t):(e.endsWith(" ")?"":" ")+i;dc.indentComment=$d;dc.lineComment=mR;dc.stringifyComment=pR});var Iv=C(ao=>{"use strict";var vR="flow",Od="block",fc="quoted";function gR(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,h,v=!1,m=-1,p=-1,b=-1;i===Od&&(m=_v(e,m,t.length),m!==-1&&(d=m+c));for(let S;S=e[m+=1];){if(i===fc&&S==="\\"){switch(p=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if(S===`
|
|
9
|
+
`)i===Od&&(m=_v(e,m,t.length)),d=m+t.length+c,f=void 0;else{if(S===" "&&h&&h!==" "&&h!==`
|
|
10
|
+
`&&h!==" "){let N=e[m+1];N&&N!==" "&&N!==`
|
|
11
|
+
`&&N!==" "&&(f=m)}if(m>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===fc){for(;h===" "||h===" ";)h=S,S=e[m+=1],v=!0;let N=m>b+1?m-2:p-1;if(u[N])return e;l.push(N),u[N]=!0,d=N+c,f=void 0}else v=!0}h=S}if(v&&s&&s(),l.length===0)return e;o&&o();let g=e.slice(0,l[0]);for(let S=0;S<l.length;++S){let N=l[S],k=l[S+1]||e.length;N===0?g=`
|
|
12
|
+
${t}${e.slice(0,k)}`:(i===fc&&u[N]&&(g+=`${e[N]}\\`),g+=`
|
|
13
|
+
${t}${e.slice(N+1,k)}`)}return g}function _v(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
+
`);r=t,n=t+1,a=e[n]}return r}ao.FOLD_BLOCK=Od;ao.FOLD_FLOW=vR;ao.FOLD_QUOTED=fc;ao.foldFlowLines=gR});var so=C(Tv=>{"use strict";var zt=ke(),er=Iv(),pc=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),mc=e=>/^(%|---|\.\.\.)/m.test(e);function wR(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function oo(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(mc(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
20
|
-
${i}`)+"'";return t.implicitKey?r:
|
|
18
|
+
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:er.foldFlowLines(o,a,er.FOLD_QUOTED,pc(t,!1))}function Hd(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return oo(e,t);let i=t.indent||(mc(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return t.implicitKey?r:er.foldFlowLines(r,i,er.FOLD_FLOW,pc(t,!1))}function Ln(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=oo;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=Hd:a&&!n?r=oo:r=i?Hd:oo}return r(e,t)}var Dd;try{Dd=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{Dd=/\n+(?!\n|$)/g}function hc({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return Ln(i,r);let l=r.indent||(r.forceBlockIndent||mc(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===zt.Scalar.BLOCK_FOLDED?!1:t===zt.Scalar.BLOCK_LITERAL?!0:!wR(i,c,l.length);if(!i)return u?`|
|
|
24
24
|
`:`>
|
|
25
25
|
`;let d,f;for(f=i.length;f>0;--f){let k=i[f-1];if(k!==`
|
|
26
26
|
`&&k!==" "&&k!==" ")break}let h=i.substring(f),v=h.indexOf(`
|
|
27
27
|
`);v===-1?d="-":i===h||v!==h.length-1?(d="+",a&&a()):d="",h&&(i=i.slice(0,-h.length),h[h.length-1]===`
|
|
28
|
-
`&&(h=h.slice(0,-1)),h=h.replace(
|
|
29
|
-
`)b=p;else break}let g=i.substring(0,b<p?b+1:p);g&&(i=i.substring(g.length),g=g.replace(/\n+/g,`$&${l}`));let
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),
|
|
31
|
-
${l}${
|
|
32
|
-
${l}${g}${i}${h}`}function
|
|
33
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(f)||h?.some(f))return
|
|
37
|
-
${t.indent}${s}`:s}
|
|
38
|
-
${s}:`):(p=`${p}:`,f&&(p+=
|
|
39
|
-
`:"",g){let R=l(g);
|
|
40
|
-
${
|
|
41
|
-
`&&
|
|
28
|
+
`&&(h=h.slice(0,-1)),h=h.replace(Dd,`$&${l}`));let m=!1,p,b=-1;for(p=0;p<i.length;++p){let k=i[p];if(k===" ")m=!0;else if(k===`
|
|
29
|
+
`)b=p;else break}let g=i.substring(0,b<p?b+1:p);g&&(i=i.substring(g.length),g=g.replace(/\n+/g,`$&${l}`));let N=(m?l?"2":"1":"")+d;if(e&&(N+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let k=i.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,R=pc(r,!0);o!=="folded"&&t!==zt.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{E=!0});let y=er.foldFlowLines(`${g}${k}${h}`,l,er.FOLD_BLOCK,R);if(!E)return`>${N}
|
|
31
|
+
${l}${y}`}return i=i.replace(/\n+/g,`$&${l}`),`|${N}
|
|
32
|
+
${l}${g}${i}${h}`}function yR(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
33
|
+
`)||u&&/[[\]{},]/.test(a))return Ln(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
+
`)?Ln(a,t):hc(e,t,i,r);if(!s&&!u&&n!==zt.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return hc(e,t,i,r);if(mc(a)){if(c==="")return t.forceBlockIndent=!0,hc(e,t,i,r);if(s&&c===l)return Ln(a,t)}let d=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(f)||h?.some(f))return Ln(a,t)}return s?d:er.foldFlowLines(d,c,er.FOLD_FLOW,pc(t,!1))}function NR(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==zt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=zt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case zt.Scalar.BLOCK_FOLDED:case zt.Scalar.BLOCK_LITERAL:return n||a?Ln(o.value,t):hc(o,t,i,r);case zt.Scalar.QUOTE_DOUBLE:return oo(o.value,t);case zt.Scalar.QUOTE_SINGLE:return Hd(o.value,t);case zt.Scalar.PLAIN:return yR(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Tv.stringifyString=NR});var co=C(Ld=>{"use strict";var bR=oc(),tr=G(),kR=no(),SR=so();function ER(e,t){let i=Object.assign({blockQuote:!0,commentString:kR.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function PR(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(tr.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function RR(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(tr.isScalar(e)||tr.isCollection(e))&&e.anchor;a&&bR.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function CR(e,t,i,r){if(tr.isPair(e))return e.toString(t,i,r);if(tr.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=tr.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=PR(t.doc.schema.tags,a));let o=RR(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):tr.isScalar(a)?SR.stringifyString(a,t,i,r):a.toString(t,i,r);return o?tr.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}Ld.createStringifyContext=ER;Ld.stringify=CR});var Hv=C(Ov=>{"use strict";var xi=G(),jv=ke(),$v=co(),lo=no();function xR({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=xi.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(xi.isCollection(e)||!xi.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let h=!d&&(!e||f&&t==null&&!i.inFlow||xi.isCollection(e)||(xi.isScalar(e)?e.type===jv.Scalar.BLOCK_FOLDED||e.type===jv.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let v=!1,m=!1,p=$v.stringify(e,i,()=>v=!0,()=>m=!0);if(!h&&!i.inFlow&&p.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),p===""?"?":h?`? ${p}`:p}else if(a&&!d||t==null&&h)return p=`? ${p}`,f&&!v?p+=lo.lineComment(p,i.indent,l(f)):m&&n&&n(),p;v&&(f=null),h?(f&&(p+=lo.lineComment(p,i.indent,l(f))),p=`? ${p}
|
|
38
|
+
${s}:`):(p=`${p}:`,f&&(p+=lo.lineComment(p,i.indent,l(f))));let b,g,S;xi.isNode(t)?(b=!!t.spaceBefore,g=t.commentBefore,S=t.comment):(b=!1,g=null,S=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&xi.isScalar(t)&&(i.indentAtStart=p.length+1),m=!1,!u&&c.length>=2&&!i.inFlow&&!h&&xi.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let N=!1,k=$v.stringify(t,i,()=>N=!0,()=>m=!0),E=" ";if(f||b||g){if(E=b?`
|
|
39
|
+
`:"",g){let R=l(g);E+=`
|
|
40
|
+
${lo.indentComment(R,i.indent)}`}k===""&&!i.inFlow?E===`
|
|
41
|
+
`&&S&&(E=`
|
|
42
42
|
|
|
43
|
-
`):
|
|
44
|
-
${i.indent}`}else if(!h&&xi.isCollection(t)){let R=k[0],
|
|
45
|
-
`),w=
|
|
43
|
+
`):E+=`
|
|
44
|
+
${i.indent}`}else if(!h&&xi.isCollection(t)){let R=k[0],y=k.indexOf(`
|
|
45
|
+
`),w=y!==-1,P=i.inFlow??t.flow??t.items.length===0;if(w||!P){let F=!1;if(w&&(R==="&"||R==="!")){let $=k.indexOf(" ");R==="&"&&$!==-1&&$<y&&k[$+1]==="!"&&($=k.indexOf(" ",$+1)),($===-1||y<$)&&(F=!0)}F||(E=`
|
|
46
46
|
${i.indent}`)}}else(k===""||k[0]===`
|
|
47
|
-
`)&&(
|
|
47
|
+
`)&&(E="");return p+=E+k,i.inFlow?N&&r&&r():S&&!N?p+=lo.lineComment(p,i.indent,l(S)):m&&n&&n(),p}Ov.stringifyPair=xR});var Fd=C(Md=>{"use strict";var Dv=Zs("process");function AR(e,...t){e==="debug"&&console.log(...t)}function _R(e,t){(e==="debug"||e==="warn")&&(typeof Dv.emitWarning=="function"?Dv.emitWarning(t):console.warn(t))}Md.debug=AR;Md.warn=_R});var Nc=C(yc=>{"use strict";var wc=G(),Lv=ke(),vc="<<",gc={identify:e=>e===vc||typeof e=="symbol"&&e.description===vc,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Lv.Scalar(Symbol(vc)),{addToJSMap:Mv}),stringify:()=>vc},IR=(e,t)=>(gc.identify(t)||wc.isScalar(t)&&(!t.type||t.type===Lv.Scalar.PLAIN)&&gc.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===gc.tag&&i.default);function Mv(e,t,i){let r=Fv(e,i);if(wc.isSeq(r))for(let n of r.items)Bd(e,t,n);else if(Array.isArray(r))for(let n of r)Bd(e,t,n);else Bd(e,t,r)}function Bd(e,t,i){let r=Fv(e,i);if(!wc.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Fv(e,t){return e&&wc.isAlias(t)?t.resolve(e.doc,e):t}yc.addMergeToJSMap=Mv;yc.isMergeKey=IR;yc.merge=gc});var qd=C(qv=>{"use strict";var TR=Fd(),Bv=Nc(),jR=co(),Vv=G(),Vd=Qi();function $R(e,t,{key:i,value:r}){if(Vv.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Bv.isMergeKey(e,i))Bv.addMergeToJSMap(e,t,r);else{let n=Vd.toJS(i,"",e);if(t instanceof Map)t.set(n,Vd.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=OR(i,n,e),o=Vd.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function OR(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Vv.isNode(e)&&i?.doc){let r=jR.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),TR.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}qv.addPairToJSMap=$R});var ir=C(Wd=>{"use strict";var Wv=ro(),HR=Hv(),DR=qd(),bc=G();function LR(e,t,i){let r=Wv.createNode(e,void 0,i),n=Wv.createNode(t,void 0,i);return new kc(r,n)}var kc=class e{constructor(t,i=null){Object.defineProperty(this,bc.NODE_TYPE,{value:bc.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return bc.isNode(i)&&(i=i.clone(t)),bc.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return DR.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?HR.stringifyPair(this,t,i,r):JSON.stringify(this)}};Wd.Pair=kc;Wd.createPair=LR});var zd=C(Jv=>{"use strict";var Qr=G(),zv=co(),Sc=no();function MR(e,t,i){return(t.inFlow??e.flow?BR:FR)(e,t,i)}function FR({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let m=t[v],p=null;if(Qr.isNode(m))!d&&m.spaceBefore&&f.push(""),Ec(i,f,m.commentBefore,d),m.comment&&(p=m.comment);else if(Qr.isPair(m)){let g=Qr.isNode(m.key)?m.key:null;g&&(!d&&g.spaceBefore&&f.push(""),Ec(i,f,g.commentBefore,d))}d=!1;let b=zv.stringify(m,u,()=>p=null,()=>d=!0);p&&(b+=Sc.lineComment(b,a,l(p))),d&&p&&(d=!1),f.push(r+b)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let v=1;v<f.length;++v){let m=f[v];h+=m?`
|
|
48
48
|
${c}${m}`:`
|
|
49
49
|
`}}return e?(h+=`
|
|
50
|
-
`+
|
|
51
|
-
`)),v<e.length-1?b+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((g,
|
|
50
|
+
`+Sc.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function BR({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let m=e[v],p=null;if(Qr.isNode(m))m.spaceBefore&&d.push(""),Ec(t,d,m.commentBefore,!1),m.comment&&(p=m.comment);else if(Qr.isPair(m)){let g=Qr.isNode(m.key)?m.key:null;g&&(g.spaceBefore&&d.push(""),Ec(t,d,g.commentBefore,!1),g.comment&&(l=!0));let S=Qr.isNode(m.value)?m.value:null;S?(S.comment&&(p=S.comment),S.commentBefore&&(l=!0)):m.value==null&&g?.comment&&(p=g.comment)}p&&(l=!0);let b=zv.stringify(m,c,()=>p=null);l||(l=d.length>u||b.includes(`
|
|
51
|
+
`)),v<e.length-1?b+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((g,S)=>g+S.length+2,2)+(b.length+2)>t.options.lineWidth)),l&&(b+=",")),p&&(b+=Sc.lineComment(b,r,s(p))),d.push(b),u=d.length}let{start:f,end:h}=i;if(d.length===0)return f+h;if(!l){let v=d.reduce((m,p)=>m+p.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let m of d)v+=m?`
|
|
52
52
|
${a}${n}${m}`:`
|
|
53
53
|
`;return`${v}
|
|
54
|
-
${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function
|
|
55
|
-
`:" ")}return
|
|
54
|
+
${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function Ec({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Sc.indentComment(t(r),e);i.push(a.trimStart())}}Jv.stringifyCollection=MR});var nr=C(Gd=>{"use strict";var VR=zd(),qR=qd(),WR=uc(),rr=G(),Pc=ir(),zR=ke();function uo(e,t){let i=rr.isScalar(t)?t.value:t;for(let r of e)if(rr.isPair(r)&&(r.key===t||r.key===i||rr.isScalar(r.key)&&r.key.value===i))return r}var Jd=class extends WR.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(rr.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Pc.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;rr.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Pc.Pair(t,t?.value):r=new Pc.Pair(t.key,t.value);let n=uo(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);rr.isScalar(n.value)&&zR.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=uo(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=uo(this.items,t)?.value;return(!i&&rr.isScalar(n)?n.value:n)??void 0}has(t){return!!uo(this.items,t)}set(t,i){this.add(new Pc.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)qR.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!rr.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})),VR.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Gd.YAMLMap=Jd;Gd.findPair=uo});var Mn=C(Uv=>{"use strict";var JR=G(),Gv=nr(),GR={collection:"map",default:!0,nodeClass:Gv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return JR.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Gv.YAMLMap.from(e,t,i)};Uv.map=GR});var ar=C(Kv=>{"use strict";var UR=ro(),KR=zd(),YR=uc(),Cc=G(),XR=ke(),QR=Qi(),Ud=class extends YR.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Cc.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Rc(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Rc(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Cc.isScalar(n)?n.value:n}has(t){let i=Rc(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Rc(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Cc.isScalar(n)&&XR.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(QR.toJS(a,String(n++),i));return r}toString(t,i,r){return t?KR.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(UR.createNode(s,void 0,r))}}return a}};function Rc(e){let t=Cc.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Kv.YAMLSeq=Ud});var Fn=C(Xv=>{"use strict";var ZR=G(),Yv=ar(),eC={collection:"seq",default:!0,nodeClass:Yv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return ZR.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Yv.YAMLSeq.from(e,t,i)};Xv.seq=eC});var fo=C(Qv=>{"use strict";var tC=so(),iC={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),tC.stringifyString(e,t,i,r)}};Qv.string=iC});var xc=C(tg=>{"use strict";var Zv=ke(),eg={identify:e=>e==null,createNode:()=>new Zv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Zv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&eg.test.test(e)?e:t.options.nullStr};tg.nullTag=eg});var Kd=C(rg=>{"use strict";var rC=ke(),ig={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new rC.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&ig.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};rg.boolTag=ig});var Bn=C(ng=>{"use strict";function nC({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}ng.stringifyNumber=nC});var Xd=C(Ac=>{"use strict";var aC=ke(),Yd=Bn(),oC={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:Yd.stringifyNumber},sC={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():Yd.stringifyNumber(e)}},cC={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 aC.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Yd.stringifyNumber};Ac.float=cC;Ac.floatExp=sC;Ac.floatNaN=oC});var Zd=C(Ic=>{"use strict";var ag=Bn(),_c=e=>typeof e=="bigint"||Number.isInteger(e),Qd=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function og(e,t,i){let{value:r}=e;return _c(r)&&r>=0?i+r.toString(t):ag.stringifyNumber(e)}var lC={identify:e=>_c(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Qd(e,2,8,i),stringify:e=>og(e,8,"0o")},uC={identify:_c,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Qd(e,0,10,i),stringify:ag.stringifyNumber},dC={identify:e=>_c(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Qd(e,2,16,i),stringify:e=>og(e,16,"0x")};Ic.int=uC;Ic.intHex=dC;Ic.intOct=lC});var cg=C(sg=>{"use strict";var fC=Mn(),hC=xc(),pC=Fn(),mC=fo(),vC=Kd(),ef=Xd(),tf=Zd(),gC=[fC.map,pC.seq,mC.string,hC.nullTag,vC.boolTag,tf.intOct,tf.int,tf.intHex,ef.floatNaN,ef.floatExp,ef.float];sg.schema=gC});var dg=C(ug=>{"use strict";var wC=ke(),yC=Mn(),NC=Fn();function lg(e){return typeof e=="bigint"||Number.isInteger(e)}var Tc=({value:e})=>JSON.stringify(e),bC=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Tc},{identify:e=>e==null,createNode:()=>new wC.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Tc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Tc},{identify:lg,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>lg(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:Tc}],kC={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},SC=[yC.map,NC.seq].concat(bC,kC);ug.schema=SC});var nf=C(fg=>{"use strict";var ho=Zs("buffer"),rf=ke(),EC=so(),PC={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ho.Buffer=="function")return ho.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof ho.Buffer=="function")s=o instanceof ho.Buffer?o.toString("base64"):ho.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=rf.Scalar.BLOCK_LITERAL),t!==rf.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===rf.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return EC.stringifyString({comment:e,type:t,value:s},r,n,a)}};fg.binary=PC});var Oc=C($c=>{"use strict";var jc=G(),af=ir(),RC=ke(),CC=ar();function hg(e,t){if(jc.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!jc.isPair(r)){if(jc.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new af.Pair(new RC.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
|
|
56
56
|
${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
|
|
57
|
-
${a.comment}`:r.comment}r=n}e.items[i]=Ac.isPair(r)?r:new Qd.Pair(r)}}else t("Expected a sequence for this tag");return e}function sg(e,t,i){let{replacer:r}=i,n=new gC.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Qd.createPair(s,c,i))}return n}var wC={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:og,createNode:sg};_c.createPairs=sg;_c.pairs=wC;_c.resolvePairs=og});var tf=C(ef=>{"use strict";var cg=G(),Zd=Yi(),uo=ir(),yC=rr(),lg=Tc(),Yr=class e extends yC.YAMLSeq{constructor(){super(),this.add=uo.YAMLMap.prototype.add.bind(this),this.delete=uo.YAMLMap.prototype.delete.bind(this),this.get=uo.YAMLMap.prototype.get.bind(this),this.has=uo.YAMLMap.prototype.has.bind(this),this.set=uo.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(cg.isPair(n)?(a=Zd.toJS(n.key,"",i),o=Zd.toJS(n.value,a,i)):a=Zd.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=lg.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Yr.tag="tag:yaml.org,2002:omap";var NC={collection:"seq",identify:e=>e instanceof Map,nodeClass:Yr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=lg.resolvePairs(e,t),r=[];for(let{key:n}of i.items)cg.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Yr,i)},createNode:(e,t,i)=>Yr.from(e,t,i)};ef.YAMLOMap=Yr;ef.omap=NC});var pg=C(rf=>{"use strict";var ug=ke();function dg({value:e,source:t},i){return t&&(e?fg:hg).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var fg={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};rf.falseTag=hg;rf.trueTag=fg});var mg=C(Ic=>{"use strict";var bC=ke(),nf=Ln(),kC={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:nf.stringifyNumber},SC={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():nf.stringifyNumber(e)}},EC={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 bC.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:nf.stringifyNumber};Ic.float=EC;Ic.floatExp=SC;Ic.floatNaN=kC});var gg=C(ho=>{"use strict";var vg=Ln(),fo=e=>typeof e=="bigint"||Number.isInteger(e);function jc(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function af(e,t,i){let{value:r}=e;if(fo(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return vg.stringifyNumber(e)}var PC={identify:fo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>jc(e,2,2,i),stringify:e=>af(e,2,"0b")},RC={identify:fo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>jc(e,1,8,i),stringify:e=>af(e,8,"0")},CC={identify:fo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>jc(e,0,10,i),stringify:vg.stringifyNumber},xC={identify:fo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>jc(e,2,16,i),stringify:e=>af(e,16,"0x")};ho.int=CC;ho.intBin=PC;ho.intHex=xC;ho.intOct=RC});var sf=C(of=>{"use strict";var Hc=G(),$c=er(),Oc=ir(),Xr=class e extends Oc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Hc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new $c.Pair(t.key,null):i=new $c.Pair(t,null),Oc.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Oc.findPair(this.items,t);return!i&&Hc.isPair(r)?Hc.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Oc.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new $c.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push($c.createPair(o,null,r));return a}};Xr.tag="tag:yaml.org,2002:set";var AC={collection:"map",identify:e=>e instanceof Set,nodeClass:Xr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Xr.from(e,t,i),resolve(e,t){if(Hc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Xr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};of.YAMLSet=Xr;of.set=AC});var lf=C(Dc=>{"use strict";var _C=Ln();function cf(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function wg(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return _C.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var TC={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>cf(e,i),stringify:wg},IC={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=>cf(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[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=cf(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$/,"")??""};Dc.floatTime=IC;Dc.intTime=TC;Dc.timestamp=yg});var kg=C(bg=>{"use strict";var jC=Hn(),$C=Ec(),OC=Dn(),HC=co(),DC=Xd(),Ng=pg(),uf=mg(),Lc=gg(),LC=vc(),MC=tf(),FC=Tc(),BC=sf(),df=lf(),VC=[jC.map,OC.seq,HC.string,$C.nullTag,Ng.trueTag,Ng.falseTag,Lc.intBin,Lc.intOct,Lc.int,Lc.intHex,uf.floatNaN,uf.floatExp,uf.float,DC.binary,LC.merge,MC.omap,FC.pairs,BC.set,df.intTime,df.floatTime,df.timestamp];bg.schema=VC});var Ig=C(pf=>{"use strict";var Rg=Hn(),qC=Ec(),Cg=Dn(),WC=co(),zC=qd(),ff=zd(),hf=Gd(),JC=tg(),GC=ng(),xg=Xd(),po=vc(),Ag=tf(),_g=Tc(),Sg=kg(),Tg=sf(),Mc=lf(),Eg=new Map([["core",JC.schema],["failsafe",[Rg.map,Cg.seq,WC.string]],["json",GC.schema],["yaml11",Sg.schema],["yaml-1.1",Sg.schema]]),Pg={binary:xg.binary,bool:zC.boolTag,float:ff.float,floatExp:ff.floatExp,floatNaN:ff.floatNaN,floatTime:Mc.floatTime,int:hf.int,intHex:hf.intHex,intOct:hf.intOct,intTime:Mc.intTime,map:Rg.map,merge:po.merge,null:qC.nullTag,omap:Ag.omap,pairs:_g.pairs,seq:Cg.seq,set:Tg.set,timestamp:Mc.timestamp},UC={"tag:yaml.org,2002:binary":xg.binary,"tag:yaml.org,2002:merge":po.merge,"tag:yaml.org,2002:omap":Ag.omap,"tag:yaml.org,2002:pairs":_g.pairs,"tag:yaml.org,2002:set":Tg.set,"tag:yaml.org,2002:timestamp":Mc.timestamp};function KC(e,t,i){let r=Eg.get(t);if(r&&!e)return i&&!r.includes(po.merge)?r.concat(po.merge):r.slice();let n=r;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 i&&(n=n.concat(po.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Pg[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Pg).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},[])}pf.coreKnownTags=UC;pf.getTags=KC});var gf=C(jg=>{"use strict";var mf=G(),YC=Hn(),XC=Dn(),QC=co(),Fc=Ig(),ZC=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,vf=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Fc.getTags(t,"compat"):t?Fc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Fc.coreKnownTags:{},this.tags=Fc.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,mf.MAP,{value:YC.map}),Object.defineProperty(this,mf.SCALAR,{value:QC.string}),Object.defineProperty(this,mf.SEQ,{value:XC.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?ZC:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};jg.Schema=vf});var Og=C($g=>{"use strict";var ex=G(),wf=ao(),mo=to();function tx(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=wf.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(mo.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(ex.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(mo.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=wf.stringify(e.contents,n,()=>s=null,c);s&&(l+=mo.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(wf.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
-
`)?(i.push("..."),i.push(
|
|
57
|
+
${a.comment}`:r.comment}r=n}e.items[i]=jc.isPair(r)?r:new af.Pair(r)}}else t("Expected a sequence for this tag");return e}function pg(e,t,i){let{replacer:r}=i,n=new CC.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(af.createPair(s,c,i))}return n}var xC={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:hg,createNode:pg};$c.createPairs=pg;$c.pairs=xC;$c.resolvePairs=hg});var cf=C(sf=>{"use strict";var mg=G(),of=Qi(),po=nr(),AC=ar(),vg=Oc(),Zr=class e extends AC.YAMLSeq{constructor(){super(),this.add=po.YAMLMap.prototype.add.bind(this),this.delete=po.YAMLMap.prototype.delete.bind(this),this.get=po.YAMLMap.prototype.get.bind(this),this.has=po.YAMLMap.prototype.has.bind(this),this.set=po.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(mg.isPair(n)?(a=of.toJS(n.key,"",i),o=of.toJS(n.value,a,i)):a=of.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=vg.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Zr.tag="tag:yaml.org,2002:omap";var _C={collection:"seq",identify:e=>e instanceof Map,nodeClass:Zr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=vg.resolvePairs(e,t),r=[];for(let{key:n}of i.items)mg.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Zr,i)},createNode:(e,t,i)=>Zr.from(e,t,i)};sf.YAMLOMap=Zr;sf.omap=_C});var bg=C(lf=>{"use strict";var gg=ke();function wg({value:e,source:t},i){return t&&(e?yg:Ng).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var yg={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 gg.Scalar(!0),stringify:wg},Ng={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 gg.Scalar(!1),stringify:wg};lf.falseTag=Ng;lf.trueTag=yg});var kg=C(Hc=>{"use strict";var IC=ke(),uf=Bn(),TC={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:uf.stringifyNumber},jC={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():uf.stringifyNumber(e)}},$C={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 IC.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:uf.stringifyNumber};Hc.float=$C;Hc.floatExp=jC;Hc.floatNaN=TC});var Eg=C(vo=>{"use strict";var Sg=Bn(),mo=e=>typeof e=="bigint"||Number.isInteger(e);function Dc(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function df(e,t,i){let{value:r}=e;if(mo(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Sg.stringifyNumber(e)}var OC={identify:mo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Dc(e,2,2,i),stringify:e=>df(e,2,"0b")},HC={identify:mo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Dc(e,1,8,i),stringify:e=>df(e,8,"0")},DC={identify:mo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Dc(e,0,10,i),stringify:Sg.stringifyNumber},LC={identify:mo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Dc(e,2,16,i),stringify:e=>df(e,16,"0x")};vo.int=DC;vo.intBin=OC;vo.intHex=LC;vo.intOct=HC});var hf=C(ff=>{"use strict";var Fc=G(),Lc=ir(),Mc=nr(),en=class e extends Mc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Fc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Lc.Pair(t.key,null):i=new Lc.Pair(t,null),Mc.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Mc.findPair(this.items,t);return!i&&Fc.isPair(r)?Fc.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Mc.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Lc.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Lc.createPair(o,null,r));return a}};en.tag="tag:yaml.org,2002:set";var MC={collection:"map",identify:e=>e instanceof Set,nodeClass:en,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>en.from(e,t,i),resolve(e,t){if(Fc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new en,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ff.YAMLSet=en;ff.set=MC});var mf=C(Bc=>{"use strict";var FC=Bn();function pf(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Pg(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return FC.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var BC={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>pf(e,i),stringify:Pg},VC={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=>pf(e,!1),stringify:Pg},Rg={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(Rg.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=pf(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$/,"")??""};Bc.floatTime=VC;Bc.intTime=BC;Bc.timestamp=Rg});var Ag=C(xg=>{"use strict";var qC=Mn(),WC=xc(),zC=Fn(),JC=fo(),GC=nf(),Cg=bg(),vf=kg(),Vc=Eg(),UC=Nc(),KC=cf(),YC=Oc(),XC=hf(),gf=mf(),QC=[qC.map,zC.seq,JC.string,WC.nullTag,Cg.trueTag,Cg.falseTag,Vc.intBin,Vc.intOct,Vc.int,Vc.intHex,vf.floatNaN,vf.floatExp,vf.float,GC.binary,UC.merge,KC.omap,YC.pairs,XC.set,gf.intTime,gf.floatTime,gf.timestamp];xg.schema=QC});var Mg=C(Nf=>{"use strict";var jg=Mn(),ZC=xc(),$g=Fn(),ex=fo(),tx=Kd(),wf=Xd(),yf=Zd(),ix=cg(),rx=dg(),Og=nf(),go=Nc(),Hg=cf(),Dg=Oc(),_g=Ag(),Lg=hf(),qc=mf(),Ig=new Map([["core",ix.schema],["failsafe",[jg.map,$g.seq,ex.string]],["json",rx.schema],["yaml11",_g.schema],["yaml-1.1",_g.schema]]),Tg={binary:Og.binary,bool:tx.boolTag,float:wf.float,floatExp:wf.floatExp,floatNaN:wf.floatNaN,floatTime:qc.floatTime,int:yf.int,intHex:yf.intHex,intOct:yf.intOct,intTime:qc.intTime,map:jg.map,merge:go.merge,null:ZC.nullTag,omap:Hg.omap,pairs:Dg.pairs,seq:$g.seq,set:Lg.set,timestamp:qc.timestamp},nx={"tag:yaml.org,2002:binary":Og.binary,"tag:yaml.org,2002:merge":go.merge,"tag:yaml.org,2002:omap":Hg.omap,"tag:yaml.org,2002:pairs":Dg.pairs,"tag:yaml.org,2002:set":Lg.set,"tag:yaml.org,2002:timestamp":qc.timestamp};function ax(e,t,i){let r=Ig.get(t);if(r&&!e)return i&&!r.includes(go.merge)?r.concat(go.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Ig.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(go.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Tg[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Tg).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},[])}Nf.coreKnownTags=nx;Nf.getTags=ax});var Sf=C(Fg=>{"use strict";var bf=G(),ox=Mn(),sx=Fn(),cx=fo(),Wc=Mg(),lx=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,kf=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Wc.getTags(t,"compat"):t?Wc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Wc.coreKnownTags:{},this.tags=Wc.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,bf.MAP,{value:ox.map}),Object.defineProperty(this,bf.SCALAR,{value:cx.string}),Object.defineProperty(this,bf.SEQ,{value:sx.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?lx:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Fg.Schema=kf});var Vg=C(Bg=>{"use strict";var ux=G(),Ef=co(),wo=no();function dx(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=Ef.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(wo.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(ux.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(wo.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Ef.stringify(e.contents,n,()=>s=null,c);s&&(l+=wo.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Ef.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
+
`)?(i.push("..."),i.push(wo.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(wo.indentComment(a(c),"")))}return i.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}Bg.stringifyDocument=dx});var yo=C(qg=>{"use strict";var fx=io(),Vn=uc(),Rt=G(),hx=ir(),px=Qi(),mx=Sf(),vx=Vg(),Pf=oc(),gx=xd(),wx=ro(),Rf=Cd(),Cf=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Rt.NODE_TYPE,{value:Rt.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Rf.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[Rt.NODE_TYPE]:{value:Rt.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=Rt.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){qn(this.contents)&&this.contents.add(t)}addIn(t,i){qn(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=Pf.anchorNames(this);t.anchor=!i||r.has(i)?Pf.findNewAnchor(i||"a",r):i}return new fx.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let p=g=>typeof g=="number"||g instanceof String||g instanceof Number,b=i.filter(p).map(String);b.length>0&&(i=i.concat(b)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:h}=Pf.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},m=wx.createNode(t,u,v);return s&&Rt.isCollection(m)&&(m.flow=!0),f(),m}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new hx.Pair(n,a)}delete(t){return qn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Vn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):qn(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return Rt.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Vn.isEmptyPath(t)?!i&&Rt.isScalar(this.contents)?this.contents.value:this.contents:Rt.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return Rt.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Vn.isEmptyPath(t)?this.contents!==void 0:Rt.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Vn.collectionFromPath(this.schema,[t],i):qn(this.contents)&&this.contents.set(t,i)}setIn(t,i){Vn.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Vn.collectionFromPath(this.schema,Array.from(t),i):qn(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Rf.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Rf.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new mx.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=px.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?gx.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return vx.stringifyDocument(this,t)}};function qn(e){if(Rt.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}qg.Document=Cf});var ko=C(bo=>{"use strict";var No=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},xf=class extends No{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Af=class extends No{constructor(t,i,r){super("YAMLWarning",t,i,r)}},yx=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};
|
|
66
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(
|
|
67
|
-
`+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||
|
|
68
|
-
`+
|
|
69
|
-
`+
|
|
70
|
-
`+R:
|
|
71
|
-
`+w.comment:
|
|
72
|
-
`+p.comment:l.comment=p.comment),l.range=[r.offset,m,p.offset]}else l.range=[r.offset,m,m];return l}
|
|
65
|
+
`}};bo.YAMLError=No;bo.YAMLParseError=xf;bo.YAMLWarning=Af;bo.prettifyError=yx});var So=C(Wg=>{"use strict";function Nx(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",h=!1,v=!1,m=null,p=null,b=null,g=null,S=null,N=null,k=null;for(let y of e)switch(v&&(y.type!=="space"&&y.type!=="newline"&&y.type!=="comma"&&a(y.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),m&&(l&&y.type!=="comment"&&y.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),y.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&y.source.includes(" ")&&(m=y),u=!0;break;case"comment":{u||a(y,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=y.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=y.source:(!N||i!=="seq-item-ind")&&(c=!0):f+=y.source,l=!0,h=!0,(p||b)&&(g=y),u=!0;break;case"anchor":p&&a(y,"MULTIPLE_ANCHORS","A node can have at most one anchor"),y.source.endsWith(":")&&a(y.offset+y.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=y,k??(k=y.offset),l=!1,u=!1,v=!0;break;case"tag":{b&&a(y,"MULTIPLE_TAGS","A node can have at most one tag"),b=y,k??(k=y.offset),l=!1,u=!1,v=!0;break}case i:(p||b)&&a(y,"BAD_PROP_ORDER",`Anchors and tags must be after the ${y.source} indicator`),N&&a(y,"UNEXPECTED_TOKEN",`Unexpected ${y.source} in ${t??"collection"}`),N=y,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){S&&a(y,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),S=y,l=!1,u=!1;break}default:a(y,"UNEXPECTED_TOKEN",`Unexpected ${y.type} token`),l=!1,u=!1}let E=e[e.length-1],R=E?E.offset+E.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:S,found:N,spaceBefore:c,comment:d,hasNewline:h,anchor:p,tag:b,newlineAfterProp:g,end:R,start:k??R}}Wg.resolveProps=Nx});var zc=C(zg=>{"use strict";function _f(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(_f(t.key)||_f(t.value))return!0}return!1;default:return!0}}zg.containsNewline=_f});var If=C(Jg=>{"use strict";var bx=zc();function kx(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&bx.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Jg.flowIndentCheck=kx});var Tf=C(Ug=>{"use strict";var Gg=G();function Sx(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Gg.isScalar(a)&&Gg.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Ug.mapIncludes=Sx});var ew=C(Zg=>{"use strict";var Kg=ir(),Ex=nr(),Yg=So(),Px=zc(),Xg=If(),Rx=Tf(),Qg="All mapping items must start at the same column";function Cx({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Ex.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:h,value:v}=u,m=Yg.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),p=!m.found;if(p){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",Qg)),!m.anchor&&!m.tag&&!h){l=m.end,m.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||Px.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&n(c,"BAD_INDENT",Qg);i.atKey=!0;let b=m.end,g=f?e(i,f,m,n):t(i,b,d,null,m,n);i.schema.compat&&Xg.flowIndentCheck(r.indent,f,n),i.atKey=!1,Rx.mapIncludes(i,s.items,g)&&n(b,"DUPLICATE_KEY","Map keys must be unique");let S=Yg.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=S.end,S.found){p&&(v?.type==="block-map"&&!S.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&m.start<S.found.offset-1024&&n(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let N=v?e(i,v,S,n):t(i,c,h,null,S,n);i.schema.compat&&Xg.flowIndentCheck(r.indent,v,n),c=N.range[2];let k=new Kg.Pair(g,N);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}else{p&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),S.comment&&(g.comment?g.comment+=`
|
|
68
|
+
`+S.comment:g.comment=S.comment);let N=new Kg.Pair(g);i.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}Zg.resolveBlockMap=Cx});var iw=C(tw=>{"use strict";var xx=ar(),Ax=So(),_x=If();function Ix({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??xx.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=Ax.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let h=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&_x.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}tw.resolveBlockSeq=Ix});var Wn=C(rw=>{"use strict";function Tx(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}rw.resolveEnd=Tx});var sw=C(ow=>{"use strict";var jx=G(),$x=ir(),nw=nr(),Ox=ar(),Hx=Wn(),aw=So(),Dx=zc(),Lx=Tf(),jf="Block collections are not allowed within flow collections",$f=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Mx({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?nw.YAMLMap:Ox.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let p=0;p<r.items.length;++p){let b=r.items[p],{start:g,key:S,sep:N,value:k}=b,E=aw.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:S??N?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!N&&!k){p===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):p<r.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+E.comment:l.comment=E.comment),d=E.end;continue}!o&&i.options.strict&&Dx.containsNewline(S)&&n(S,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(p===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let R="";e:for(let y of g)switch(y.type){case"comma":case"space":break;case"comment":R=y.source.substring(1);break e;default:break e}if(R){let y=l.items[l.items.length-1];jx.isPair(y)&&(y=y.value??y.key),y.comment?y.comment+=`
|
|
70
|
+
`+R:y.comment=R,E.comment=E.comment.substring(R.length+1)}}if(!o&&!N&&!E.found){let R=k?e(i,k,E,n):t(i,E.end,N,null,E,n);l.items.push(R),d=R.range[2],$f(k)&&n(R.range,"BLOCK_IN_FLOW",jf)}else{i.atKey=!0;let R=E.end,y=S?e(i,S,E,n):t(i,R,g,null,E,n);$f(S)&&n(y.range,"BLOCK_IN_FLOW",jf),i.atKey=!1;let w=aw.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:k,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(w.found){if(!o&&!E.found&&i.options.strict){if(N)for(let $ of N){if($===w.found)break;if($.type==="newline"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<w.found.offset-1024&&n(w.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?n(k,"MISSING_CHAR",`Missing space after : in ${s}`):n(w.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let P=k?e(i,k,w,n):w.found?t(i,w.end,N,null,w,n):null;P?$f(k)&&n(P.range,"BLOCK_IN_FLOW",jf):w.comment&&(y.comment?y.comment+=`
|
|
71
|
+
`+w.comment:y.comment=w.comment);let F=new $x.Pair(y,P);if(i.options.keepSourceTokens&&(F.srcToken=b),o){let $=l;Lx.mapIncludes(i,$.items,y)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(F)}else{let $=new nw.YAMLMap(i.schema);$.flow=!0,$.items.push(F);let Be=(P??y).range;$.range=[y.range[0],Be[1],Be[2]],l.items.push($)}d=P?P.range[2]:w.end}}let f=o?"}":"]",[h,...v]=r.end,m=d;if(h?.source===f)m=h.offset+h.source.length;else{let p=s[0].toUpperCase()+s.substring(1),b=u?`${p} must end with a ${f}`:`${p} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",b),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let p=Hx.resolveEnd(v,m,i.options.strict,n);p.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+p.comment:l.comment=p.comment),l.range=[r.offset,m,p.offset]}else l.range=[r.offset,m,m];return l}ow.resolveFlowCollection=Mx});var lw=C(cw=>{"use strict";var Fx=G(),Bx=ke(),Vx=nr(),qx=ar(),Wx=ew(),zx=iw(),Jx=sw();function Of(e,t,i,r,n,a){let o=i.type==="block-map"?Wx.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?zx.resolveBlockSeq(e,t,i,r,a):Jx.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Gx(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!h||h.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===Vx.YAMLMap.tagName&&s==="map"||o===qx.YAMLSeq.tagName&&s==="seq")return Of(e,t,i,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Of(e,t,i,n,o)}let l=Of(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=Fx.isNode(u)?u:new Bx.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}cw.composeCollection=Gx});var Df=C(uw=>{"use strict";var Hf=ke();function Ux(e,t,i){let r=t.offset,n=Kx(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Hf.Scalar.BLOCK_FOLDED:Hf.Scalar.BLOCK_LITERAL,o=t.source?Yx(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let p=o[m][1];if(p===""||p==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
|
|
73
73
|
`.repeat(Math.max(1,o.length-1)):"",p=r+n.length;return t.source&&(p+=t.source.length),{value:m,type:a,comment:n.comment,range:[r,p,p]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let m=0;m<s;++m){let[p,b]=o[m];if(b===""||b==="\r")n.indent===0&&p.length>c&&(c=p.length);else{p.length<c&&i(l+p.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=p.length),u=m,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=p.length+b.length+1}for(let m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let d="",f="",h=!1;for(let m=0;m<u;++m)d+=o[m][0].slice(c)+`
|
|
74
|
-
`;for(let m=u;m<s;++m){let[p,b]=o[m];l+=p.length+b.length+1;let g=b[b.length-1]==="\r";if(g&&(b=b.slice(0,-1)),b&&p.length<c){let
|
|
74
|
+
`;for(let m=u;m<s;++m){let[p,b]=o[m];l+=p.length+b.length+1;let g=b[b.length-1]==="\r";if(g&&(b=b.slice(0,-1)),b&&p.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-b.length-(g?2:1),"BAD_INDENT",N),p=""}a===Hf.Scalar.BLOCK_LITERAL?(d+=f+p.slice(c)+b,f=`
|
|
75
75
|
`):p.length>c||b[0]===" "?(f===" "?f=`
|
|
76
76
|
`:!h&&f===`
|
|
77
77
|
`&&(f=`
|
|
@@ -84,65 +84,65 @@ ${l}
|
|
|
84
84
|
`+o[m][0].slice(c);d[d.length-1]!==`
|
|
85
85
|
`&&(d+=`
|
|
86
86
|
`);break;default:d+=`
|
|
87
|
-
`}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function
|
|
87
|
+
`}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function Kx({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let h=n[f];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let h=t[f];switch(h.type){case"space":l=!0;case"newline":d+=h.source.length;break;case"comment":i&&!l&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,u=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",v);let m=h.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function Yx(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}uw.resolveBlockScalar=Ux});var Mf=C(fw=>{"use strict";var Lf=ke(),Xx=Wn();function Qx(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,h,v)=>i(r+f,h,v);switch(n){case"scalar":s=Lf.Scalar.PLAIN,c=Zx(a,l);break;case"single-quoted-scalar":s=Lf.Scalar.QUOTE_SINGLE,c=eA(a,l);break;case"double-quoted-scalar":s=Lf.Scalar.QUOTE_DOUBLE,c=tA(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=Xx.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Zx(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),dw(e)}function eA(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),dw(e.slice(1,-1)).replace(/''/g,"'")}function dw(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
89
|
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let n=r[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;r=i.exec(e);)r[1]===""?a===`
|
|
90
90
|
`?n+=a:a=`
|
|
91
|
-
`:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function
|
|
91
|
+
`:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function tA(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
|
|
92
92
|
`))if(n===`
|
|
93
|
-
`){let{fold:a,offset:o}=
|
|
93
|
+
`){let{fold:a,offset:o}=iA(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=rA[a];if(o)i+=o;else if(a===`
|
|
94
94
|
`)for(a=e[r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="\r"&&e[r+1]===`
|
|
95
|
-
`)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=
|
|
95
|
+
`)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=nA(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
|
|
96
96
|
`&&!(o==="\r"&&e[r+2]===`
|
|
97
|
-
`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function
|
|
97
|
+
`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function iA(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
|
|
98
98
|
`||r==="\r")&&!(r==="\r"&&e[t+2]!==`
|
|
99
99
|
`);)r===`
|
|
100
100
|
`&&(i+=`
|
|
101
|
-
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var rA={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function nA(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}fw.resolveFlowScalar=Qx});var mw=C(pw=>{"use strict";var tn=G(),hw=ke(),aA=Df(),oA=Mf();function sA(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?aA.resolveBlockScalar(e,t,r):oA.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[tn.SCALAR]:c?l=cA(e.schema,n,c,i,r):t.type==="scalar"?l=lA(e,n,t,r):l=e.schema[tn.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=tn.isScalar(d)?d:new hw.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new hw.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 cA(e,t,i,r,n){if(i==="!")return e[tn.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[tn.SCALAR])}function lA({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[tn.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[tn.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=sA});var gw=C(vw=>{"use strict";function uA(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}vw.emptyScalarPosition=uA});var Nw=C(Bf=>{"use strict";var dA=io(),fA=G(),hA=lw(),ww=mw(),pA=Wn(),mA=gw(),vA={composeNode:yw,composeEmptyNode:Ff};function yw(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=gA(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=ww.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=hA.composeCollection(vA,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Ff(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!fA.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Ff(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:mA.emptyScalarPosition(t,i,r),indent:-1,source:""},d=ww.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function gA({options:e},{offset:t,source:i,end:r},n){let a=new dA.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=pA.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Bf.composeEmptyNode=Ff;Bf.composeNode=yw});var Sw=C(kw=>{"use strict";var wA=yo(),bw=Nw(),yA=Wn(),NA=So();function bA(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new wA.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=NA.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?bw.composeNode(l,n,u,o):bw.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=yA.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}kw.composeDoc=bA});var qf=C(Rw=>{"use strict";var kA=Zs("process"),SA=Cd(),EA=yo(),Eo=ko(),Ew=G(),PA=Sw(),RA=Wn();function Po(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function Pw(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var
|
|
106
|
-
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(
|
|
105
|
+
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var Vf=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=Po(i);a?this.warnings.push(new Eo.YAMLWarning(o,r,n)):this.errors.push(new Eo.YAMLParseError(o,r,n))},this.directives=new SA.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Pw(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(Ew.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Ew.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
|
|
107
107
|
${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
|
|
108
|
-
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
109
|
-
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new
|
|
108
|
+
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Pw(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(kA.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=Po(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=PA.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new Eo.YAMLParseError(Po(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Eo.YAMLParseError(Po(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=RA.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
|
|
109
|
+
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new Eo.YAMLParseError(Po(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new EA.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};Rw.Composer=Vf});var Aw=C(Jc=>{"use strict";var CA=Df(),xA=Mf(),AA=ko(),Cw=so();function _A(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new AA.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return xA.resolveFlowScalar(e,t,r);case"block-scalar":return CA.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function IA(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Cw.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
111
|
`),u=s.substring(0,l),d=s.substring(l+1)+`
|
|
112
|
-
`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function
|
|
112
|
+
`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return xw(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function TA(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Cw.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">":jA(e,c);break;case'"':Wf(e,c,"double-quoted-scalar");break;case"'":Wf(e,c,"single-quoted-scalar");break;default:Wf(e,c,"scalar")}}function jA(e,t){let i=t.indexOf(`
|
|
114
114
|
`),r=t.substring(0,i),n=t.substring(i+1)+`
|
|
115
|
-
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];
|
|
116
|
-
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function
|
|
117
|
-
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}
|
|
115
|
+
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];xw(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 xw(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function Wf(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}Jc.createScalarToken=IA;Jc.resolveAsScalar=_A;Jc.setScalarValue=TA});var Iw=C(_w=>{"use strict";var $A=e=>"type"in e?Uc(e):Gc(e);function Uc(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Uc(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Gc(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Gc(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Gc(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function Gc({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Uc(t)),i)for(let a of i)n+=a.source;return r&&(n+=Uc(r)),n}_w.stringify=$A});var Ow=C($w=>{"use strict";var zf=Symbol("break visit"),OA=Symbol("skip children"),Tw=Symbol("remove item");function rn(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),jw(Object.freeze([]),e,t)}rn.BREAK=zf;rn.SKIP=OA;rn.REMOVE=Tw;rn.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};rn.parentCollection=(e,t)=>{let i=rn.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function jw(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=jw(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===zf)return zf;s===Tw&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}$w.visit=rn});var Kc=C(st=>{"use strict";var Jf=Aw(),HA=Iw(),DA=Ow(),Gf="\uFEFF",Uf="",Kf="",Yf="",LA=e=>!!e&&"items"in e,MA=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function FA(e){switch(e){case Gf:return"<BOM>";case Uf:return"<DOC>";case Kf:return"<FLOW_END>";case Yf:return"<SCALAR>";default:return JSON.stringify(e)}}function BA(e){switch(e){case Gf:return"byte-order-mark";case Uf:return"doc-mode";case Kf:return"flow-error-end";case Yf: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}st.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}st.createScalarToken=Jf.createScalarToken;st.resolveAsScalar=Jf.resolveAsScalar;st.setScalarValue=Jf.setScalarValue;st.stringify=HA.stringify;st.visit=DA.visit;st.BOM=Gf;st.DOCUMENT=Uf;st.FLOW_END=Kf;st.SCALAR=Yf;st.isCollection=LA;st.isScalar=MA;st.prettyToken=FA;st.tokenType=BA});var Zf=C(Dw=>{"use strict";var Ro=Kc();function Jt(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var Hw=new Set("0123456789ABCDEFabcdef"),VA=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Yc=new Set(",[]{}"),qA=new Set(` ,[]{}
|
|
121
|
+
\r `),Xf=e=>!e||qA.has(e),Qf=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
|
|
122
122
|
`?!0:i==="\r"?this.buffer[t+1]===`
|
|
123
123
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
|
|
124
124
|
`||!n&&!this.atEnd)return t+r+1}return i===`
|
|
125
|
-
`||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&
|
|
126
|
-
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===
|
|
125
|
+
`||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&Jt(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]===Ro.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,r=t.indexOf("#");for(;r!==-1;){let a=t[r-1];if(a===" "||a===" "){i=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield Ro.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let i=this.peek(3);if((i==="---"||i==="...")&&Jt(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,i==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Jt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Jt(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Xf),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&Jt(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Ro.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(Xf),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Jt(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
|
|
127
127
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=r.indexOf(`
|
|
128
|
-
`,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>
|
|
128
|
+
`,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>Jt(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,r;e:for(let a=this.pos;r=this.buffer[a];++a)switch(r){case" ":i+=1;break;case`
|
|
129
129
|
`:t=a,i=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
130
|
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
131
131
|
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
132
132
|
`;)r=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
-
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield
|
|
133
|
+
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield Ro.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(Jt(a)||t&&Yc.has(a))break;i=r}else if(Jt(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(r+=1,n=`
|
|
135
|
-
`,a=this.buffer[r+1]):i=r),a==="#"||t&&
|
|
136
|
-
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&
|
|
135
|
+
`,a=this.buffer[r+1]):i=r),a==="#"||t&&Yc.has(a))break;if(n===`
|
|
136
|
+
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&Yc.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Ro.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Xf),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Jt(r)||i&&Yc.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!Jt(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(VA.has(i))i=this.buffer[++t];else if(i==="%"&&Hw.has(this.buffer[t+1])&&Hw.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
137
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Dw.Lexer=Qf});var th=C(Lw=>{"use strict";var eh=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};Lw.LineCounter=eh});var rh=C(qw=>{"use strict";var WA=Zs("process"),Mw=Kc(),zA=Zf();function or(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function Fw(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Vw(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Xc(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 zn(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 Qc(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function Bw(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!or(t.start,"explicit-key-ind")&&!or(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Vw(t.value)?t.value.end?Qc(t.value.end,t.sep):t.value.end=t.sep:Qc(t.start,t.sep),delete t.sep)}var ih=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 zA.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,WA.env.LOG_TOKENS&&console.log("|",Mw.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Mw.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&Bw(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Fw(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Fw(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let i=Xc(this.peek(2)),r=zn(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
140
|
-
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){
|
|
140
|
+
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Qc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(or(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Vw(i.key)&&!or(i.sep,"newline")){let o=zn(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(or(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=zn(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):or(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!or(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Qc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||or(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=Xc(r),a=zn(n);Bw(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
142
|
-
`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=
|
|
142
|
+
`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Xc(t),r=zn(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Xc(t),r=zn(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};qw.Parser=ih});var Uw=C(xo=>{"use strict";var Ww=qf(),JA=yo(),Co=ko(),GA=Fd(),UA=G(),KA=th(),zw=rh();function Jw(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new KA.LineCounter||null,prettyErrors:t}}function YA(e,t={}){let{lineCounter:i,prettyErrors:r}=Jw(t),n=new zw.Parser(i?.addNewLine),a=new Ww.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(Co.prettifyError(e,i)),s.warnings.forEach(Co.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Gw(e,t={}){let{lineCounter:i,prettyErrors:r}=Jw(t),n=new zw.Parser(i?.addNewLine),a=new Ww.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Co.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(Co.prettifyError(e,i)),o.warnings.forEach(Co.prettifyError(e,i))),o}function XA(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Gw(e,i);if(!n)return null;if(n.warnings.forEach(a=>GA.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function QA(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return UA.isDocument(e)&&!r?e.toString(i):new JA.Document(e,r,i).toString(i)}xo.parse=XA;xo.parseAllDocuments=YA;xo.parseDocument=Gw;xo.stringify=QA});var nn=C(X=>{"use strict";var ZA=qf(),e_=yo(),t_=Sf(),nh=ko(),i_=io(),sr=G(),r_=ir(),n_=ke(),a_=nr(),o_=ar(),s_=Kc(),c_=Zf(),l_=th(),u_=rh(),Zc=Uw(),Kw=Qa();X.Composer=ZA.Composer;X.Document=e_.Document;X.Schema=t_.Schema;X.YAMLError=nh.YAMLError;X.YAMLParseError=nh.YAMLParseError;X.YAMLWarning=nh.YAMLWarning;X.Alias=i_.Alias;X.isAlias=sr.isAlias;X.isCollection=sr.isCollection;X.isDocument=sr.isDocument;X.isMap=sr.isMap;X.isNode=sr.isNode;X.isPair=sr.isPair;X.isScalar=sr.isScalar;X.isSeq=sr.isSeq;X.Pair=r_.Pair;X.Scalar=n_.Scalar;X.YAMLMap=a_.YAMLMap;X.YAMLSeq=o_.YAMLSeq;X.CST=s_;X.Lexer=c_.Lexer;X.LineCounter=l_.LineCounter;X.Parser=u_.Parser;X.parse=Zc.parse;X.parseAllDocuments=Zc.parseAllDocuments;X.parseDocument=Zc.parseDocument;X.stringify=Zc.stringify;X.visit=Kw.visit;X.visitAsync=Kw.visitAsync});import{promises as PP}from"node:fs";import gd from"node:path";import{promises as ld}from"fs";import je from"path";import{promises as rE}from"fs";import qa from"path";import{isDeepStrictEqual as mL}from"util";import{createHash as $P}from"crypto";function Zm(e,t,i,r){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!r.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function ev(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))ev(e[t]);return Object.freeze(e)}function Xi(e){return ev(structuredClone(e))}function yd(e,t,i,r){return e.resolveStep({pkg:Xi(t),state:Xi(i),context:Xi(r)})}function tv(e,t,i,r,n,a){return e.resolveNext({pkg:Xi(t),state:Xi(i),step:Xi(r),outcome:Xi(n),context:Xi(a)})}function OP(e,t,i){return $P("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function Nd(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function iv(e,t,i,r,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=yd(r,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Nd(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:OP(s.runId,s.iteration,o.id),stepId:o.id};return HP(e,s,c,i)}function HP(e,t,i,r){let n=Zm(i,t,e.guardrails,r);return n.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:n.reason}}function rv(e,t,i,r,n){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?yd(r,e,t,n):void 0,o=a?Nd(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?tv(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Nd(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as cp}from"fs";import bb from"path";var bd={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:"验证预期"}},nv={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:"结论"}},av={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:"结论"}},ov=new Map,kd=new Map;for(let e of Object.keys(bd)){for(let[t,i]of Object.entries(bd[e]))ov.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(nv[e]))kd.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(av[e]))kd.set(i.toLocaleLowerCase("en-US"),t)}function DP(e,t){return bd[e][t]}function Sd(e,t){return nv[e][t]??av[e][t]}function ec(e){return ov.get(e.trim().toLocaleLowerCase("en-US"))??null}function sv(e){return kd.get(e.trim().toLocaleLowerCase("en-US"))??null}function tc(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(i=>`# ${DP(e,i)}
|
|
143
143
|
`).join(`
|
|
144
|
-
`)}function qt(e,t,i){return e==="zh-CN"?i:t}var Ql=Tn(en(),1);import{promises as rb}from"fs";import mi from"path";import{execFileSync as t_}from"child_process";import Ro from"path";function or(e,t){return t_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function i_(e,t){let i=Ro.normalize(e),r=Ro.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function fe(e){try{let t=Ro.resolve(or(e,["rev-parse","--show-toplevel"])),r=or(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?Ro.resolve(r.slice(9)):t,a=null;try{a=or(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!i_(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function qw(e){try{or(e,["rev-parse","--is-inside-work-tree"]);let t=or(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:Ro.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function Jt(e){return qw(e).map(t=>t.root)}function Co(e,t){try{return or(e,["check-ref-format","--branch",t]),or(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function Ai(e,t){try{let i=or(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as o_}from"node:crypto";import{promises as Gt}from"node:fs";import Ct from"node:path";import{TextDecoder as s_}from"node:util";import Zf from"path";var r_=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),n_=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function a_(e){return e.toLowerCase().startsWith(".env")}function li(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>a_(r))?"environment-file":i.some(r=>n_.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>r_.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function eh(e,t){let i=li(t);if(i)return i;let r=Zf.resolve(e.projectRoot,...t.split("/")),n=Zf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===Zf.resolve(e.configFile)?"native-runtime":null}function sr(e){return e!==0&&e!==0n&&e!=="0"}function vt(e,t){return sr(e.dev)&&sr(t.dev)&&sr(e.ino)&&sr(t.ino)}function z(e,t){let i=sr(e.dev)&&sr(t.dev);if(i&&e.dev!==t.dev)return!1;let r=sr(e.ino)&&sr(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var xo=1024*1024;function th(e,t){let i=Ct.relative(e,t);return i===""||!Ct.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ct.sep}`)}function c_(e){let t=Ct.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})||Ct.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=li(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function l_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function u_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Yc(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Ww(e){let t=await Gt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Gt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function d_(e,t){let i=Ct.resolve(e),r=Ct.resolve(t);if(!th(i,r))throw new Error("Native artifact path is outside its root");let n=[await Ww(i)],a=i;for(let o of Ct.relative(i,r).split(Ct.sep).filter(Boolean)){a=Ct.join(a,o);let s=await Ww(a);if(!th(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 i=await Gt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!u_(t,i)||await Gt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Z(e){let t=c_(e.ref),i=e.maxBytes===null?null:l_(e.maxBytes??xo),r=Ct.resolve(e.root,...t.split("/")),n=await d_(e.root,Ct.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Gt.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Gt.realpath(r);if(!th(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Gt.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Gt.lstat(r),Gt.realpath(r)]);if(await zw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Yc(a,c)||!Yc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let y=i===null?h.length:i+1-f,E=await s.read(h,0,Math.min(h.length,y),null);if(E.bytesRead===0)break;if(f+=E.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,E.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([s.stat(),Gt.lstat(r),Gt.realpath(r)]);if(await zw(n),!m.isFile()||m.isSymbolicLink()||p!==o||!Yc(c,v)||!Yc(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),g;try{g=new s_("utf-8",{fatal:!0}).decode(b)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:f,hash:e.includeHash===!1?null:o_("sha256").update(b).digest("hex"),text:g}}finally{await s.close()}}import{randomUUID as f_}from"crypto";import{promises as _e}from"fs";import Ut from"path";function Xc(e,t){let i=Ut.relative(e,t);return i===""||!Ut.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ut.sep}`)}function h_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Qc(e,t){return z({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function p_(e,t){return Qc(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Jw(e){let t=await _e.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await _e.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function qn(e){for(let t of e){let i=await _e.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!h_(t,i)||await _e.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function m_(e,t,i){let[r,n]=await Promise.all([_e.lstat(e),_e.realpath(e),i?qn(i):Promise.resolve()]);if(!r.isFile()||r.isSymbolicLink()||!Qc(r,t)||i&&!Xc(i[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return r}async function v_(e,t){let i=Ut.resolve(e),r=Ut.resolve(t);if(!Xc(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Jw(i)],a=Ut.relative(i,r).split(Ut.sep).filter(Boolean),o=i;for(let s of a){await qn(n),o=Ut.join(o,s);try{await _e.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Jw(o);if(!Xc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await qn(n),n}async function g_(e){let t;try{t=await _e.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function Gw(e,t,i={}){let r=Ut.dirname(e),n=i.containedRoot?await v_(i.containedRoot,r):null;n||await _e.mkdir(r,{recursive:!0});let a=Ut.join(r,`.${Ut.basename(e)}.${f_()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await _e.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([_e.lstat(a),_e.realpath(a)]);if(await qn(n),!l.isFile()||l.isSymbolicLink()||!Qc(s,l)||!Xc(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(),!Qc(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await m_(a,c,n),await i.beforeCommit?.(),n){await qn(n);let l=await _e.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!p_(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await _e.link(a,e),await _e.unlink(a)):await _e.rename(a,e),await g_(r)}catch(l){if(await o?.close(),!n)await _e.rm(a,{force:!0});else try{await qn(n),await _e.rm(a,{force:!0})}catch{}throw l}}async function he(e,t,i={}){await Gw(e,t,i)}async function Uw(e,t,i={}){await Gw(e,t,i)}async function ee(e,t,i={}){await he(e,JSON.stringify(t,null,2)+`
|
|
145
|
-
`,i)}import
|
|
144
|
+
`)}function Wt(e,t,i){return e==="zh-CN"?i:t}var iu=$n(nn(),1);import{promises as db}from"fs";import vi from"path";import{execFileSync as d_}from"child_process";import Ao from"path";function cr(e,t){return d_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function f_(e,t){let i=Ao.normalize(e),r=Ao.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function fe(e){try{let t=Ao.resolve(cr(e,["rev-parse","--show-toplevel"])),r=cr(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?Ao.resolve(r.slice(9)):t,a=null;try{a=cr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!f_(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Yw(e){try{cr(e,["rev-parse","--is-inside-work-tree"]);let t=cr(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:Ao.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function Gt(e){return Yw(e).map(t=>t.root)}function _o(e,t){try{return cr(e,["check-ref-format","--branch",t]),cr(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function Ai(e,t){try{let i=cr(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as v_}from"node:crypto";import{promises as Ut}from"node:fs";import Ct from"node:path";import{TextDecoder as g_}from"node:util";import ah from"path";var h_=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),p_=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function m_(e){return e.toLowerCase().startsWith(".env")}function ui(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>m_(r))?"environment-file":i.some(r=>p_.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>h_.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function oh(e,t){let i=ui(t);if(i)return i;let r=ah.resolve(e.projectRoot,...t.split("/")),n=ah.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===ah.resolve(e.configFile)?"native-runtime":null}function lr(e){return e!==0&&e!==0n&&e!=="0"}function vt(e,t){return lr(e.dev)&&lr(t.dev)&&lr(e.ino)&&lr(t.ino)}function z(e,t){let i=lr(e.dev)&&lr(t.dev);if(i&&e.dev!==t.dev)return!1;let r=lr(e.ino)&&lr(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var Io=1024*1024;function sh(e,t){let i=Ct.relative(e,t);return i===""||!Ct.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ct.sep}`)}function w_(e){let t=Ct.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})||Ct.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=ui(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function y_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function N_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function el(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Xw(e){let t=await Ut.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ut.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function b_(e,t){let i=Ct.resolve(e),r=Ct.resolve(t);if(!sh(i,r))throw new Error("Native artifact path is outside its root");let n=[await Xw(i)],a=i;for(let o of Ct.relative(i,r).split(Ct.sep).filter(Boolean)){a=Ct.join(a,o);let s=await Xw(a);if(!sh(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Qw(e){for(let t of e){let i=await Ut.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!N_(t,i)||await Ut.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Z(e){let t=w_(e.ref),i=e.maxBytes===null?null:y_(e.maxBytes??Io),r=Ct.resolve(e.root,...t.split("/")),n=await b_(e.root,Ct.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Ut.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Ut.realpath(r);if(!sh(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ut.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ut.lstat(r),Ut.realpath(r)]);if(await Qw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!el(a,c)||!el(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let S=i===null?h.length:i+1-f,N=await s.read(h,0,Math.min(h.length,S),null);if(N.bytesRead===0)break;if(f+=N.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([s.stat(),Ut.lstat(r),Ut.realpath(r)]);if(await Qw(n),!m.isFile()||m.isSymbolicLink()||p!==o||!el(c,v)||!el(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),g;try{g=new g_("utf-8",{fatal:!0}).decode(b)}catch(S){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:S})}return{ref:t,size:f,hash:e.includeHash===!1?null:v_("sha256").update(b).digest("hex"),text:g}}finally{await s.close()}}import{randomUUID as k_}from"crypto";import{promises as _e}from"fs";import Kt from"path";function tl(e,t){let i=Kt.relative(e,t);return i===""||!Kt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Kt.sep}`)}function S_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function il(e,t){return z({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function E_(e,t){return il(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Zw(e){let t=await _e.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await _e.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Jn(e){for(let t of e){let i=await _e.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!S_(t,i)||await _e.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function P_(e,t,i){let[r,n]=await Promise.all([_e.lstat(e),_e.realpath(e),i?Jn(i):Promise.resolve()]);if(!r.isFile()||r.isSymbolicLink()||!il(r,t)||i&&!tl(i[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return r}async function R_(e,t){let i=Kt.resolve(e),r=Kt.resolve(t);if(!tl(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Zw(i)],a=Kt.relative(i,r).split(Kt.sep).filter(Boolean),o=i;for(let s of a){await Jn(n),o=Kt.join(o,s);try{await _e.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Zw(o);if(!tl(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Jn(n),n}async function C_(e){let t;try{t=await _e.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function ey(e,t,i={}){let r=Kt.dirname(e),n=i.containedRoot?await R_(i.containedRoot,r):null;n||await _e.mkdir(r,{recursive:!0});let a=Kt.join(r,`.${Kt.basename(e)}.${k_()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await _e.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([_e.lstat(a),_e.realpath(a)]);if(await Jn(n),!l.isFile()||l.isSymbolicLink()||!il(s,l)||!tl(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(),!il(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await P_(a,c,n),await i.beforeCommit?.(),n){await Jn(n);let l=await _e.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!E_(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await _e.link(a,e),await _e.unlink(a)):await _e.rename(a,e),await C_(r)}catch(l){if(await o?.close(),!n)await _e.rm(a,{force:!0});else try{await Jn(n),await _e.rm(a,{force:!0})}catch{}throw l}}async function he(e,t,i={}){await ey(e,t,i)}async function ty(e,t,i={}){await ey(e,t,i)}async function ee(e,t,i={}){await he(e,JSON.stringify(t,null,2)+`
|
|
145
|
+
`,i)}import nI from"path";var To=$n(nn(),1);import ur from"path";var jo=64*1024,nl=1024,al=64,iy=1024,ry=64,oy=5,rl={learning:!0,retrieval:!0},sy={provider:"local"},x_=12e4,ny=6e5,A_=[".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/**"],__=["**/.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"],I_=[...A_,...__].sort((e,t)=>e.localeCompare(t,"en"));var Yt={include:["**/*"],exclude:[...I_],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Gn={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
146
|
# 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.
|
|
147
147
|
# learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
|
|
148
148
|
# retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
|
|
@@ -166,48 +166,48 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
|
|
|
166
166
|
# 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
|
|
167
167
|
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
168
168
|
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
169
|
-
# 可选值:true | false`}};function
|
|
170
|
-
`)){let s=
|
|
169
|
+
# 可选值:true | false`}};function cy(e,t){return Gn[t][e]}function T_(e,t,i,r){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 Gn.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Gn.en)return s}if(a===4&&t==="knowledge"&&r==="remote"){let s=`knowledge.remote.${o}`;if(s in Gn.en)return s}if(a===4&&t==="knowledge"&&r==="local"){let s=`knowledge.local.${o}`;if(s in Gn.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"&&i==="snapshot"){let s=`native.snapshot.${o}`;if(s in Gn.en)return s}return null}function $o(e,t){let i=[],r=null,n=null,a=null;for(let o of(0,To.stringify)(e).trimEnd().split(`
|
|
170
|
+
`)){let s=T_(o,r,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of cy(s,t).split(`
|
|
171
171
|
`))i.push(`${c}${l}`)}i.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?r="native":o.startsWith("classic:")?r="classic":o.startsWith("hook:")?r="hook":o.startsWith("memory:")?r="memory":o.startsWith("knowledge:")?r="knowledge":r=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(r==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),r==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return i.push(""),i.join(`
|
|
172
|
-
`)}function S_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||cr.posix.isAbsolute(i)||cr.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function zn(e){let t=S_(e,"native.artifact_root");return t.length===0?".":t.join("/")}function iy(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function il(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||cr.posix.isAbsolute(r)||cr.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function _i(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ry(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function rl(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>el)throw new Error(`${t} exceeds ${el} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>tl)throw new Error(`${t} contains more than ${tl} wildcard tokens`);return e}function Qw(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>rl(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function ih(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function E_(e){if(e===void 0)return{...Kt,include:[...Kt.include],exclude:[...Kt.exclude]};let t=_i(e,"native.snapshot");return{include:Qw(t.include,"native.snapshot.include",Kt.include),exclude:Qw(t.exclude,"native.snapshot.exclude",Kt.exclude),max_files:ih(t.max_files,Kt.max_files,"native.snapshot.max_files"),max_total_bytes:ih(t.max_total_bytes,Kt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ih(t.max_duration_ms,Kt.max_duration_ms,"native.snapshot.max_duration_ms")}}function P_(e){if(e===void 0)return;let t=_i(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=_i(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:zn(r),toArtifactRoot:zn(n),stage:a,...o?{cleanup:o}:{}}}function R_(e){if(e===void 0)return;let t=_i(e,"native.finish");if(t.pull_request===void 0)return{};let i=_i(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(cr.posix.isAbsolute(r[0])||cr.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??w_;if(!Number.isSafeInteger(n)||n<1||n>Xw)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Xw}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function C_(e,t={}){let i=_i(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Zw;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=P_(i.pending_root_move),c=R_(i.finish);return{artifact_root:zn(r),language:ry(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:E_(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function x_(e){let t=_i(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:iy(t.artifact_layout),language:ry(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function A_(e){let i=_i(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>il(r,`hook.allow_paths[${n}]`)))]}}function __(e){if(e===void 0)return{...Zc};let t=_i(e,"memory"),i=t.learning??Zc.learning,r=t.retrieval??Zc.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function rh(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function T_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||cr.posix.isAbsolute(i)||cr.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>Kw)throw new Error(`${t} exceeds ${Kw} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>Yw)throw new Error(`${t} contains more than ${Yw} wildcard tokens`);return i}function I_(e){let i=rh(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>T_(r,`knowledge.local.include[${n}]`)))]}}function j_(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function $_(e){let t=rh(e,"knowledge.remote"),i=j_(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function O_(e){if(e===void 0)return{...ey};let t=rh(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:I_(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:$_(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function H_(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function D_(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function Jn(e,t={}){let i=(0,Ao.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=H_(n.ambient_resume),o=n.hook===void 0?void 0:A_(n.hook),s=__(n.memory),c=O_(n.knowledge),l=n.native===void 0?void 0:C_(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:x_(n.classic),d=D_(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 ny(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 ay(e){let t=e.knowledge??{...ey};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Zc},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...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.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:ny(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}}:{}}}function gt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Io(e,t){let i=ay(t),r=Jn((0,Ao.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.hook&&(n.hook={...gt(e.hook),allow_paths:[...r.hook.allow_paths]}),r.memory){let a=gt(e.memory);n.memory={...a,learning:r.memory.learning,retrieval:r.memory.retrieval}}if(r.knowledge){let a=gt(e.knowledge),o={...a,provider:r.knowledge.provider};if(r.knowledge.local&&r.knowledge.local.include.length>0?o.local={...gt(a.local),include:[...r.knowledge.local.include]}:delete o.local,r.knowledge.remote){let c={...gt(a.remote),endpoint:r.knowledge.remote.endpoint,timeout_ms:r.knowledge.remote.timeout_ms,...r.knowledge.remote.token_env===void 0?{}:{token_env:r.knowledge.remote.token_env},...r.knowledge.remote.scope===void 0?{}:{scope:r.knowledge.remote.scope}};r.knowledge.remote.token_env===void 0&&delete c.token_env,r.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(r.native){let a=gt(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(r.native.finish?.pull_request){let s=gt(a.finish);o.finish={...s,pull_request:{...gt(s.pull_request),provider:r.native.finish.pull_request.provider,command:[...r.native.finish.pull_request.command],timeout_ms:r.native.finish.pull_request.timeout_ms}}}else{let s={...gt(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,r.native.pending_root_move){let s=gt(a.pending_root_move),c=ny(r.native.pending_root_move),l=gt(s.cleanup),u=gt(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...gt(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}import{createHash as M_}from"crypto";import{promises as ol}from"fs";import lr from"path";import{constants as nl,promises as tn}from"fs";var Yt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function nh(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function oy(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function jo(e){return{dev:e.dev,ino:e.ino,birthtime:nh(e)}}function al(e,t){let i=jo(e),r=jo(t);return vt(i,r)?z(i,r):z(i,r)&&nh(e)===nh(t)&&oy(e)===oy(t)&&e.size===t.size}async function rn(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await tn.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Yt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Yt("too-large",`${r} exceeds ${t} bytes`);let o=await tn.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:jo(a)});let s=process.platform==="win32"?nl.O_RDONLY:nl.O_RDONLY|nl.O_NOFOLLOW|nl.O_NONBLOCK,c;try{c=await tn.open(e,s)}catch(l){throw l.code==="ELOOP"?new Yt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),tn.lstat(e,{bigint:n}),tn.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!al(a,l)||!al(a,u))throw new Yt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:jo(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-h,{bytesRead:y}=await c.read(v,0,Math.min(v.length,g),null);if(y===0)break;if(h+=y,h>t)throw new Yt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,y)))}await i.hooks?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([c.stat({bigint:n}),tn.lstat(e,{bigint:n}),tn.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||b!==o||!al(a,m)||!al(a,p))throw new Yt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:jo(m)}),{bytes:Buffer.concat(f,h),stat:m,realPath:b}}finally{await c.close()}}function L_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ah(e,t){let i=lr.relative(e,t);return i===""||!lr.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${lr.sep}`)}async function sy(e,t){let i=lr.resolve(e),r=await ol.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ol.realpath(i)}async function cy(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=lr.join(n,i[a]);let o;try{o=await ol.lstat(n)}catch(u){if(L_(u))return{exists:!1,kind:"missing"};throw u}let s=lr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await ol.realpath(n);if(!ah(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Gn(e,t,i){let r=il(t,i.label),n=lr.resolve(e),a=await sy(n,i.label),o=r.split("/"),s=lr.resolve(n,...o);if(!ah(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await cy(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function ur(e,t,i,r){let n=await Gn(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await sy(n.projectRoot,r.label);return rn(n.target,i,{...r,verify:async(o,s)=>{if(!ah(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await cy(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var $o=".comet/config.yaml";function oh(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function F_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function sl(e,t={}){return(await Oo(e,t)).document}async function ly(e){try{return(await ur(e,$o,_o,{label:$o})).bytes}catch(t){if(F_(t))return null;throw t}}function uy(e){return e?{exists:!0,sha256:M_("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function cl(e){return uy(await ly(e))}async function Oo(e,t={}){let i=await ly(e);return{document:i?Jn(i.toString("utf8"),t):null,identity:uy(i)}}async function sh(e){return(await sl(e))?.config??null}var KV=16*1024;async function ch(e,t){if(!t)return;let i=await cl(e);if(!oh(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as dy,promises as dr}from"fs";import K from"path";import W_ from"os";var ll=".comet/config.yaml",z_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function lh(e){try{return await dr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function J_(e){try{let t=await dr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Kn(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}async function Un(e){let t=[],i=e;for(;!await lh(i);){let n=K.dirname(i);if(n===i)break;t.push(K.basename(i)),i=n}let r=await dr.realpath(i);return K.resolve(r,...t.reverse())}async function uh(e){try{return(await dr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function dh(e){let t=K.resolve(e);try{(await dr.stat(t)).isDirectory()||(t=K.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=K.resolve(W_.homedir());for(;;){if(!(t===r&&i!==r)){let o=K.join(t,...ll.split("/")),s=t===i||await J_(o);if(await lh(o)&&s)return t}if(await lh(K.join(t,".git")))return t;let a=K.dirname(t);if(a===t)return i;t=a}}function ul(e){return zn(e)}async function G_(e,t){let i=ul(t),r=K.resolve(e,...i.split("/")),n=await dr.realpath(e),a=await Un(r);if(!Kn(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function qe(e,t){let i=ul(t),r=await G_(e,i),n=K.join(r,"comet");if(await uh(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Un(r),Un(n)]);if(!Kn(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 uh(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([dr.realpath(s),Un(c)]);if(!Kn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:K.join(e,...ll.split("/")),artifactRoot:r,artifactRootRef:i,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 hy(e){if(!z_.test(e))throw new Error(`Invalid Native change name: ${e}`)}function We(e,t){hy(t);let i=K.join(e.changesRuntimeDir,t);if(!O(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function nn(e,t){hy(t);let i=K.join(e.changesDir,t,"runtime");if(!O(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function H(e,t){let i=We(e,t);if(dy(i))return i;let r=nn(e,t);return dy(r)?r:i}async function fy(e){try{let t=await dr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Do(e,t){let i=We(e,t),r=nn(e,t),[n,a]=await Promise.all([fy(i),fy(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function fr(e,t){if(!t.startsWith("runtime/")||K.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=K.resolve(e,...t.slice(8).split("/"));if(!O(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=K.resolve(t);if(O(e.runtimeDir,i))return e.runtimeDir;if(O(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function O(e,t){return Kn(K.resolve(e),K.resolve(t))}async function T(e,t){let i=K.resolve(e),r=K.resolve(t);if(!Kn(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await uh(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Un(i),Un(r)]);if(!Kn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var fh=Kt;var dl=rl;async function ye(e){let t=(await sl(e))?.config??null;return t?.native?t:null}async function Yn(e){let t=await ye(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 hr(e,t,i={}){let r=await Oo(e,{allowPartialProject:!0}),n=Io(r.document?.value??{},t),a=U_.join(e,...ll.split("/"));await he(a,To(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await ch(e,r.identity)}})}import{promises as zI}from"fs";import JI from"path";import{AsyncLocalStorage as K_}from"async_hooks";import{randomUUID as gy}from"crypto";import{promises as xt}from"fs";import wy from"os";import pe from"path";var my=16*1024,hh=".coordinator",Y_=5e3,vy=new K_,fl=new Map;function X_(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function Q_(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function yy(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 hl(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return vt(i,r)?z(i,r):z(i,r)&&e.size===t.size}function pl(e,t){return hl(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function Z_(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&&pl(e.identity,t.identity)}async function Xt(e){let t,i;try{let r=await rn(e,my,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Yt?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${my} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:Q_(JSON.parse(t.toString("utf8")),e),identity:yy(i)}}async function eT(e){return(await Xt(e))?.owner??null}function ph(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==wy.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=oT(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function tT(e,t){try{await xt.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await xt.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function ml(e,t){let i=await Xt(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!pl(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await xt.mkdir(t,{recursive:!0});let r=pe.join(t,`${pe.basename(e.file)}.${e.owner.id}.${gy()}.removed`);try{await xt.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Xt(r);if(!n||n.owner.id!==e.owner.id||!hl(n.identity,e.identity))throw await tT(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await xt.rm(r,{force:!0}),"removed"}function Ny(e){return{id:gy(),pid:process.pid,hostname:wy.hostname(),createdAt:new Date().toISOString(),operation:e}}async function by(e,t){let i;try{i=await xt.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await eT(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let r;try{await i.writeFile(JSON.stringify(t,null,2)+`
|
|
173
|
-
`,"utf8"),await i.sync(),r=
|
|
174
|
-
${
|
|
172
|
+
`)}function j_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||ur.posix.isAbsolute(i)||ur.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Un(e){let t=j_(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ly(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function ol(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||ur.posix.isAbsolute(r)||ur.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function _i(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function uy(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function sl(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>nl)throw new Error(`${t} exceeds ${nl} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>al)throw new Error(`${t} contains more than ${al} wildcard tokens`);return e}function ay(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>sl(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function ch(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function $_(e){if(e===void 0)return{...Yt,include:[...Yt.include],exclude:[...Yt.exclude]};let t=_i(e,"native.snapshot");return{include:ay(t.include,"native.snapshot.include",Yt.include),exclude:ay(t.exclude,"native.snapshot.exclude",Yt.exclude),max_files:ch(t.max_files,Yt.max_files,"native.snapshot.max_files"),max_total_bytes:ch(t.max_total_bytes,Yt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ch(t.max_duration_ms,Yt.max_duration_ms,"native.snapshot.max_duration_ms")}}function O_(e){if(e===void 0)return;let t=_i(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=_i(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Un(r),toArtifactRoot:Un(n),stage:a,...o?{cleanup:o}:{}}}function H_(e){if(e===void 0)return;let t=_i(e,"native.finish");if(t.pull_request===void 0)return{};let i=_i(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(ur.posix.isAbsolute(r[0])||ur.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??x_;if(!Number.isSafeInteger(n)||n<1||n>ny)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${ny}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function D_(e,t={}){let i=_i(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??oy;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=O_(i.pending_root_move),c=H_(i.finish);return{artifact_root:Un(r),language:uy(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:$_(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function L_(e){let t=_i(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:ly(t.artifact_layout),language:uy(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function M_(e){let i=_i(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>ol(r,`hook.allow_paths[${n}]`)))]}}function F_(e){if(e===void 0)return{...rl};let t=_i(e,"memory"),i=t.learning??rl.learning,r=t.retrieval??rl.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function lh(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function B_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||ur.posix.isAbsolute(i)||ur.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>iy)throw new Error(`${t} exceeds ${iy} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>ry)throw new Error(`${t} contains more than ${ry} wildcard tokens`);return i}function V_(e){let i=lh(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>B_(r,`knowledge.local.include[${n}]`)))]}}function q_(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function W_(e){let t=lh(e,"knowledge.remote"),i=q_(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function z_(e){if(e===void 0)return{...sy};let t=lh(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:V_(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:W_(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function J_(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function G_(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function Kn(e,t={}){let i=(0,To.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=J_(n.ambient_resume),o=n.hook===void 0?void 0:M_(n.hook),s=F_(n.memory),c=z_(n.knowledge),l=n.native===void 0?void 0:D_(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:L_(n.classic),d=G_(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 dy(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 fy(e){let t=e.knowledge??{...sy};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...rl},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...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.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:dy(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}}:{}}}function gt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Oo(e,t){let i=fy(t),r=Kn((0,To.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.hook&&(n.hook={...gt(e.hook),allow_paths:[...r.hook.allow_paths]}),r.memory){let a=gt(e.memory);n.memory={...a,learning:r.memory.learning,retrieval:r.memory.retrieval}}if(r.knowledge){let a=gt(e.knowledge),o={...a,provider:r.knowledge.provider};if(r.knowledge.local&&r.knowledge.local.include.length>0?o.local={...gt(a.local),include:[...r.knowledge.local.include]}:delete o.local,r.knowledge.remote){let c={...gt(a.remote),endpoint:r.knowledge.remote.endpoint,timeout_ms:r.knowledge.remote.timeout_ms,...r.knowledge.remote.token_env===void 0?{}:{token_env:r.knowledge.remote.token_env},...r.knowledge.remote.scope===void 0?{}:{scope:r.knowledge.remote.scope}};r.knowledge.remote.token_env===void 0&&delete c.token_env,r.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(r.native){let a=gt(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(r.native.finish?.pull_request){let s=gt(a.finish);o.finish={...s,pull_request:{...gt(s.pull_request),provider:r.native.finish.pull_request.provider,command:[...r.native.finish.pull_request.command],timeout_ms:r.native.finish.pull_request.timeout_ms}}}else{let s={...gt(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,r.native.pending_root_move){let s=gt(a.pending_root_move),c=dy(r.native.pending_root_move),l=gt(s.cleanup),u=gt(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...gt(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}import{createHash as K_}from"crypto";import{promises as ul}from"fs";import dr from"path";import{constants as cl,promises as an}from"fs";var Xt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function uh(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function hy(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ho(e){return{dev:e.dev,ino:e.ino,birthtime:uh(e)}}function ll(e,t){let i=Ho(e),r=Ho(t);return vt(i,r)?z(i,r):z(i,r)&&uh(e)===uh(t)&&hy(e)===hy(t)&&e.size===t.size}async function on(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await an.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Xt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Xt("too-large",`${r} exceeds ${t} bytes`);let o=await an.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Ho(a)});let s=process.platform==="win32"?cl.O_RDONLY:cl.O_RDONLY|cl.O_NOFOLLOW|cl.O_NONBLOCK,c;try{c=await an.open(e,s)}catch(l){throw l.code==="ELOOP"?new Xt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),an.lstat(e,{bigint:n}),an.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ll(a,l)||!ll(a,u))throw new Xt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Ho(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-h,{bytesRead:S}=await c.read(v,0,Math.min(v.length,g),null);if(S===0)break;if(h+=S,h>t)throw new Xt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,S)))}await i.hooks?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([c.stat({bigint:n}),an.lstat(e,{bigint:n}),an.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||b!==o||!ll(a,m)||!ll(a,p))throw new Xt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:Ho(m)}),{bytes:Buffer.concat(f,h),stat:m,realPath:b}}finally{await c.close()}}function U_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function dh(e,t){let i=dr.relative(e,t);return i===""||!dr.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${dr.sep}`)}async function py(e,t){let i=dr.resolve(e),r=await ul.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ul.realpath(i)}async function my(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=dr.join(n,i[a]);let o;try{o=await ul.lstat(n)}catch(u){if(U_(u))return{exists:!1,kind:"missing"};throw u}let s=dr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await ul.realpath(n);if(!dh(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Yn(e,t,i){let r=ol(t,i.label),n=dr.resolve(e),a=await py(n,i.label),o=r.split("/"),s=dr.resolve(n,...o);if(!dh(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await my(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function fr(e,t,i,r){let n=await Yn(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await py(n.projectRoot,r.label);return on(n.target,i,{...r,verify:async(o,s)=>{if(!dh(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await my(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var Do=".comet/config.yaml";function fh(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function Y_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function dl(e,t={}){return(await Lo(e,t)).document}async function vy(e){try{return(await fr(e,Do,jo,{label:Do})).bytes}catch(t){if(Y_(t))return null;throw t}}function gy(e){return e?{exists:!0,sha256:K_("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function fl(e){return gy(await vy(e))}async function Lo(e,t={}){let i=await vy(e);return{document:i?Kn(i.toString("utf8"),t):null,identity:gy(i)}}async function hh(e){return(await dl(e))?.config??null}var mq=16*1024;async function ph(e,t){if(!t)return;let i=await fl(e);if(!fh(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as wy,promises as hr}from"fs";import K from"path";import eI from"os";var hl=".comet/config.yaml",tI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function mh(e){try{return await hr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function iI(e){try{let t=await hr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Qn(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}async function Xn(e){let t=[],i=e;for(;!await mh(i);){let n=K.dirname(i);if(n===i)break;t.push(K.basename(i)),i=n}let r=await hr.realpath(i);return K.resolve(r,...t.reverse())}async function vh(e){try{return(await hr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function gh(e){let t=K.resolve(e);try{(await hr.stat(t)).isDirectory()||(t=K.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=K.resolve(eI.homedir());for(;;){if(!(t===r&&i!==r)){let o=K.join(t,...hl.split("/")),s=t===i||await iI(o);if(await mh(o)&&s)return t}if(await mh(K.join(t,".git")))return t;let a=K.dirname(t);if(a===t)return i;t=a}}function pl(e){return Un(e)}async function rI(e,t){let i=pl(t),r=K.resolve(e,...i.split("/")),n=await hr.realpath(e),a=await Xn(r);if(!Qn(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function qe(e,t){let i=pl(t),r=await rI(e,i),n=K.join(r,"comet");if(await vh(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Xn(r),Xn(n)]);if(!Qn(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 vh(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([hr.realpath(s),Xn(c)]);if(!Qn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:K.join(e,...hl.split("/")),artifactRoot:r,artifactRootRef:i,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 Ny(e){if(!tI.test(e))throw new Error(`Invalid Native change name: ${e}`)}function We(e,t){Ny(t);let i=K.join(e.changesRuntimeDir,t);if(!O(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function sn(e,t){Ny(t);let i=K.join(e.changesDir,t,"runtime");if(!O(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function D(e,t){let i=We(e,t);if(wy(i))return i;let r=sn(e,t);return wy(r)?r:i}async function yy(e){try{let t=await hr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Fo(e,t){let i=We(e,t),r=sn(e,t),[n,a]=await Promise.all([yy(i),yy(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function pr(e,t){if(!t.startsWith("runtime/")||K.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=K.resolve(e,...t.slice(8).split("/"));if(!O(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=K.resolve(t);if(O(e.runtimeDir,i))return e.runtimeDir;if(O(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function O(e,t){return Qn(K.resolve(e),K.resolve(t))}async function I(e,t){let i=K.resolve(e),r=K.resolve(t);if(!Qn(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await vh(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Xn(i),Xn(r)]);if(!Qn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var wh=Yt;var ml=sl;async function ye(e){let t=(await dl(e))?.config??null;return t?.native?t:null}async function Zn(e){let t=await ye(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 mr(e,t,i={}){let r=await Lo(e,{allowPartialProject:!0}),n=Oo(r.document?.value??{},t),a=nI.join(e,...hl.split("/"));await he(a,$o(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await ph(e,r.identity)}})}import{promises as ej}from"fs";import tj from"path";import{AsyncLocalStorage as aI}from"async_hooks";import{randomUUID as Ey}from"crypto";import{promises as xt}from"fs";import Py from"os";import pe from"path";var ky=16*1024,yh=".coordinator",oI=5e3,Sy=new aI,vl=new Map;function sI(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function cI(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function Ry(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 gl(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return vt(i,r)?z(i,r):z(i,r)&&e.size===t.size}function wl(e,t){return gl(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function lI(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&wl(e.identity,t.identity)}async function Qt(e){let t,i;try{let r=await on(e,ky,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Xt?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${ky} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:cI(JSON.parse(t.toString("utf8")),e),identity:Ry(i)}}async function uI(e){return(await Qt(e))?.owner??null}function Nh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Py.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=vI(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function dI(e,t){try{await xt.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await xt.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function yl(e,t){let i=await Qt(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!wl(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await xt.mkdir(t,{recursive:!0});let r=pe.join(t,`${pe.basename(e.file)}.${e.owner.id}.${Ey()}.removed`);try{await xt.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Qt(r);if(!n||n.owner.id!==e.owner.id||!gl(n.identity,e.identity))throw await dI(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await xt.rm(r,{force:!0}),"removed"}function Cy(e){return{id:Ey(),pid:process.pid,hostname:Py.hostname(),createdAt:new Date().toISOString(),operation:e}}async function xy(e,t){let i;try{i=await xt.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await uI(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let r;try{await i.writeFile(JSON.stringify(t,null,2)+`
|
|
173
|
+
`,"utf8"),await i.sync(),r=Ry(await i.stat({bigint:!0}))}finally{await i.close()}let n=await Qt(e);if(!r||!n||n.owner.id!==t.id||!gl(n.identity,r))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function fI(e,t){let i=await I(e.runtimeDir,e.locksDir);await xt.mkdir(i,{recursive:!0});let r=await I(e.runtimeDir,pe.join(i,yh));await xt.mkdir(r,{recursive:!0});let n=Cy(t),a=pe.join(r,`.${n.id}.tmp`),o=pe.join(r,`${n.id}.claim`);try{let s=await xy(a,n);await xt.rename(a,o);let c=await Qt(o);if(!c||!gl(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await xt.rm(a,{force:!0})}}async function hI(e){let t=pe.dirname(e.file),i=!1,r=pe.basename(e.file);for(let n of await xt.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=pe.join(t,n.name);if(pe.resolve(a)!==pe.resolve(e.file))try{let o=await Qt(a),s=Nh(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await yl(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function Ay(e){let t=await Qt(e.file);if(t){if(t.owner.id!==e.owner.id||!wl(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await yl(t,pe.dirname(e.file))}}async function pI(e,t){let i=Date.now()+oI;for(;;){let r=await fI(e,t);if(!await hI(r))return r;if(await Ay(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function mI(e){let t=vl.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return vl.set(e,n),await t,()=>{i(),vl.get(e)===n&&vl.delete(e)}}async function Nl(e,t,i){let r=pe.resolve(e.locksDir),n=Sy.getStore();if(n?.has(r))return i();let a=await mI(r);try{let o=await pI(e,t),s=new Map(n??[]);return s.set(r,o),await Sy.run(s,async()=>{try{return await i()}finally{await Ay(o)}})}finally{a()}}async function ea(e,t,i){let r=[...new Map(e.map(a=>[pe.resolve(a.locksDir),a])).values()].sort((a,o)=>pe.resolve(a.locksDir).localeCompare(pe.resolve(o.locksDir))),n=async a=>{let o=r[a];return o?Nl(o,t,()=>n(a+1)):i()};return n(0)}async function vr(e,t,i){return Nl(e,`acquire ${t}`,async()=>{let r=await I(e.runtimeDir,e.locksDir);await xt.mkdir(r,{recursive:!0});let n=await I(e.runtimeDir,pe.join(r,sI(t))),a=Cy(i),o=await xy(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function gr(e){await Qt(e.file)&&await Nl({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${pe.basename(e.file)}`,async()=>{let t=await Qt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!wl(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=pe.join(e.locksDir,yh);await yl(t,i)})}function vI(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Bo(e){return Nh(await Qt(e))}async function bh(e,t,i){return Nl(e,`take over ${pe.basename(t)}`,async()=>{let r=await I(e.runtimeDir,e.locksDir),n=await I(e.runtimeDir,t);if(pe.resolve(pe.dirname(n))!==pe.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await Qt(n),o=Nh(a);if(o.status==="missing")return{status:"missing"};if(i&&!lI(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=pe.join(r,yh);return await yl(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as bT}from"node:fs";import Th from"node:path";import oT from"node:path";import Fy from"node:path";import _y from"node:path";import{createHash as gI}from"crypto";function Zt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function wI(e,t){t.has(e)&&Zt("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||Zt("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&Zt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Zt("symbol properties are not supported"),`[${e.map(r=>kh(r,t)).join(",")}]`}finally{t.delete(e)}}function yI(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Zt("only plain objects are supported"),t.has(e)&&Zt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Zt("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&Zt("accessor properties are not supported"),`${JSON.stringify(o)}:${kh(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function kh(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)||Zt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?wI(e,t):yI(e,t);case"bigint":case"function":case"symbol":case"undefined":return Zt(`${typeof e} values are not supported`)}return Zt("unsupported value type")}function Vo(e){return kh(e,new Set)}function H(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 gI("sha256").update(`${e}
|
|
174
|
+
${Vo(t)}`).digest("hex")}var NI="comet.native.acceptance.v1",bI=/^acceptance-[a-f0-9]{64}$/u,kI=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),SI=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,EI=/^[a-f0-9]{64}$/u,PI=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function RI(e,t){return e<t?-1:e>t?1:0}var Ii=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Wo=Object.freeze({maxCriteria:1024}),Iy="<!-- comet-native:acceptance-evidence:start -->",Ty="<!-- comet-native:acceptance-evidence:end -->";function jy(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function $y(e,t){let i=t.toString(36),r=H("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function CI(e){if(!EI.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=PI.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==H("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function xI(e,t){let i=jy(e.text,Ii.maxTextBytes),r=e.context.slice(0,Ii.maxContextItems).map(n=>jy(n,Ii.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function Hy(e){let t=CI({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(RI),n=r.slice(0,Ii.maxFailedCheckIds),a=e.criteria.slice(t,t+Ii.maxItems);for(let c of a){let l=[...i,xI(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?$y(e.acceptanceHash,u):null,limits:{...Ii}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Ii.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?$y(e.acceptanceHash,o):null,limits:{...Ii}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Ii.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Eh(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 Sh(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function Oy(e){return e.includes("-->")||e.includes("--!>")}function*ta(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
175
175
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
176
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=
|
|
177
|
-
`),[],r)),"Brief",r)}function
|
|
178
|
-
`),o.context,r)),o=null}};for(let{line:c,body:l}of
|
|
179
|
-
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=Ty(o),c=ET(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function ET(e){let t=Ty([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var PT=/^A[1-9]\d*$/u;function $y(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||jy.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||jy.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function RT(e,t){return e.localeCompare(t,"en")}function yl(e){let t=$y(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>RT(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=gl(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=$y(a.source,`Native spec source for ${a.capability}`);r.push(...wl(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=Fo(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function Oy(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!PT.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Hy(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var kl=Tn(en(),1);import{promises as CT}from"node:fs";var Zn="comet.native.v4",Vo="comet.native.local-execution.v4";var Dy=["multi-session","single-session"];function bh(){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 xT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,AT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_T=/^A[1-9][0-9]*$/u,TT=/^[a-f0-9]{64}$/u,IT=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),bl=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Xe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qe(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Te(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Sh(e,t){return e===null?null:Te(e,t)}function jT(e,t){let i=Te(e,t);if(!TT.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function ea(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function me(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function $T(e,t){return e===null?null:me(e,t,Number.MIN_SAFE_INTEGER)}function Se(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ui(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function Sl(e,t){return ui(e,t,(i,r)=>Te(i,`${t}[${r}]`))}function an(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function ta(e,t){let i=Te(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Eh(e,t,i=!1){let r=Te(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function At(e,t){let i=Xe(e,t);return Qe(i,new Set(["text","truncated"]),t),{text:Te(i.text,`${t}.text`,{empty:!0}),truncated:ea(i.truncated,`${t}.truncated`)}}function OT(e,t){let i=`Native spec_changes[${t}]`,r=Xe(e,i);Qe(r,new Set(["capability","operation","source"]),i);let n=Te(r.capability,`${i}.capability`);if(!AT.test(n))throw new Error(`${i}.capability is invalid`);let a=Se(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Eh(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function HT(e){let t="Native workspace",i=Xe(e,t);Qe(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=Se(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Sh(i.change_branch,`${t}.change_branch`),a=Sh(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:Se(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function DT(e){let t="Native loop",i=Xe(e,t);Qe(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=Sl(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);an(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:Se(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Se(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:me(i.goal_cycle,`${t}.goal_cycle`,1),iteration:me(i.iteration,`${t}.iteration`),attempt:me(i.attempt,`${t}.attempt`),retry_epoch:me(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:me(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:me(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:me(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Sh(i.next_action,`${t}.next_action`)}}function LT(e,t){let i=`Native acceptance[${t}]`,r=Xe(e,i);Qe(r,new Set(["id","source","text","result","reason"]),i);let n=Te(r.id,`${i}.id`);if(!_T.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Eh(r.source,`${i}.source`),text:Te(r.text,`${i}.text`),result:Se(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:At(r.reason,`${i}.reason`)}}function MT(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["name","result","note"]),i),{name:At(r.name,`${i}.name`),result:Se(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:At(r.note,`${i}.note`)}}function FT(e){let t="Native builder_handoff",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=Sl(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);an(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:Xe(i.review,`${t}.review`);return n&&Qe(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:Te(i.candidate_id,`${t}.candidate_id`),identity_provider:Te(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:Te(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),summary:At(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ui(i.checks,`${t}.checks`,MT),checks_truncated:ea(i.checks_truncated,`${t}.checks_truncated`),known_limits:ui(i.known_limits,`${t}.known_limits`,(a,o)=>At(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ea(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:Se(n.status,["passed"],`${t}.review.status`),summary:At(n.summary,`${t}.review.summary`),reviewer_execution_ref:Te(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:ta(i.submitted_at,`${t}.submitted_at`)}}function BT(e,t){let i=`Native blockers[${t}]`,r=Xe(e,i);Qe(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Sl(r.acceptance_ids,`${i}.acceptance_ids`);return an(n,`${i}.acceptance_ids`),{owner:Se(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:At(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:Se(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function VT(e,t){let i=`Native verification.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:Te(r.id,`${i}.id`),name:At(r.name,`${i}.name`),argv_display:ui(r.argv_display,`${i}.argv_display`,(n,a)=>At(n,`${i}.argv_display[${a}]`)),argv_truncated:ea(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Eh(r.cwd_ref,`${i}.cwd_ref`,!0),status:Se(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:$T(r.exit_code,`${i}.exit_code`),duration_ms:me(r.duration_ms,`${i}.duration_ms`)}}function qT(e){let t="Native verification",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ui(i.checks,`${t}.checks`,VT);an(r.map(a=>a.id),`${t}.checks IDs`);let n=Te(i.identity_provider,`${t}.identity_provider`);return{candidate_id:Te(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Te(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),attempt:me(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Se(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Se(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:At(i.summary,`${t}.summary`),risks:ui(i.risks,`${t}.risks`,(a,o)=>At(a,`${t}.risks[${o}]`)),risks_truncated:ea(i.risks_truncated,`${t}.risks_truncated`),completed_at:ta(i.completed_at,`${t}.completed_at`)}}function Ly(e,t){let i=`Native history[${t}]`,r=Xe(e,i);Qe(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Sl(r.unresolved_ids,`${i}.unresolved_ids`);return an(n,`${i}.unresolved_ids`),{goal_cycle:me(r.goal_cycle,`${i}.goal_cycle`,1),iteration:me(r.iteration,`${i}.iteration`),attempt:me(r.attempt,`${i}.attempt`),outcome:Se(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:At(r.summary,`${i}.summary`),completed_at:ta(r.completed_at,`${i}.completed_at`)}}function WT(e){let t="Native history_overflow.outcome_counts",i=Xe(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Qe(i,new Set(r),t),{pass:me(i.pass,`${t}.pass`),fail:me(i.fail,`${t}.fail`),blocked:me(i.blocked,`${t}.blocked`),"execution-error":me(i["execution-error"],`${t}.execution-error`),recovery:me(i.recovery,`${t}.recovery`)}}function zT(e){let t="Native history_overflow",i=Xe(e,t);Qe(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=me(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:ta(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:ta(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=WT(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function JT(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function GT(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function ct(e){let t=Xe(e,"Native portable state");if(Qe(t,IT,"Native portable state"),t.schema!==Zn)throw new Error(`Native portable state schema must be ${Zn}`);let i=Te(t.name,"Native state name");if(!xT.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ui(t.spec_changes,"Native spec_changes",OT);an(r.map(s=>s.capability),"Native spec change capabilities");let n=ui(t.acceptance,"Native acceptance",LT);an(n.map(s=>s.id),"Native acceptance IDs");let a=ui(t.history,"Native history",Ly);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Zn,name:i,language:Se(t.language,["en","zh-CN"],"Native state language"),phase:Se(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Se(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:me(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:jT(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:Se(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:HT(t.workspace),loop:DT(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:FT(t.builder_handoff),blockers:ui(t.blockers,"Native blockers",BT),verification:t.verification===null?null:qT(t.verification),history:a,history_overflow:zT(t.history_overflow),verification_result:Se(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Se(t.verification_report,["verification.md"],"Native verification_report"),archived:ea(t.archived,"Native archived"),created_at:ta(t.created_at,"Native created_at")};return JT(o),GT(o),o}function on(e,t){let i=ct(e),r=Ly(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.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 ct({...i,history:n,history_overflow:a})}function UT(e,t){let i=(0,kl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Ze(e){let t=await CT.readFile(e,"utf8");return ct(UT(t,"Native portable state"))}async function El(e,t,i={}){let r=ct(t);await he(e,(0,kl.stringify)(r),i)}var Nl=new Map;async function KT(e,t){let i=Nl.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Nl.set(e,a),await i;try{return await t()}finally{r(),Nl.get(e)===a&&Nl.delete(e)}}async function sn(e){return KT(e.file,async()=>{let t=me(e.expectedStateVersion,"Native expected state version",1),i=ct(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ze(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new bl(t,r.state_version);return await El(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ze(e.file);if(n.state_version!==t)throw new bl(t,n.state_version)}}),i})}function YT(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function Ii(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(YT(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var Ne="comet.native.v3",be="comet.native.v2",et="comet.native.v1",vr="comet.native.transition.v3",ji="comet.native.transition.v2",cn="comet.native.transition.v1";var Pl="comet.native.portable-migration.v1",QT=new Set(["schema","id","change","fromSchema","status","createdAt"]),ZT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eI=/^[a-z0-9][a-z0-9-]{7,127}$/u,tI=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),iI=new Set([et,be,Ne]);function rI(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function nI(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function aI(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function oI(e){return e.schema===et?ln(e):e.schema===be?di(e):lt(e)}function sI(e){return XT.posix.normalize(e.replaceAll("\\","/"))}function cI(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:sI(t.source)})}function lI(e){return e==="shape"?"shape":"build"}function uI(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function dI(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function My(e){let t=oI(e.state);Oy(e.acceptance);let i=lI(t.phase),r=i==="shape"?0:1,n=nI(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 ct({schema:Zn,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:cI(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:uI(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:Ii(dI(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:bh(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Ph(e){let t=rI(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!QT.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Pl)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!eI.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"||!iI.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!tI.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Pl,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:aI(t.createdAt,"Native portable migration transaction createdAt")}}function Fy(e){switch(Ph(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 Rl="comet.native.archive-transaction.v4",By="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",hI=new RegExp(`^portable-archive-(${By})\\.json$`,"u"),pI=new RegExp(`^portable-migration-(${By})\\.json$`,"u"),mI=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,vI=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gI=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),wI=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),yI=new Set(["capability","operation","source","content"]),Vy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function qy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Wy(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function NI(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=qy(e,i);if(Wy(r,yI,i),typeof r.capability!="string"||!Vy.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function bI(e){let t=qy(e,"Native portable Archive transaction");if(Wy(t,wI,"Native portable Archive transaction"),t.schema!==Rl)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!mI.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Vy.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"||!vI.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"||!gI.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 i=t.spec_changes.map(NI);if(new Set(i.map(({capability:n})=>n)).size!==i.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)>i.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 r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Rl,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:i,created_at:t.created_at}}function un(e){let t=hI.exec(e);if(t)return{kind:"archive",change:t[1]};let i=pI.exec(e);return i?{kind:"migration",change:i[1]}:null}function gr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=un(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Rh.join(e.transactionsDir,i)}async function qo(e,t){let i=un(t);if(!i)return null;let r=await Z({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Rh.join(e.transactionsDir,t);if(i.kind==="archive"){let s=bI(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=Ph(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function ia(e,t){let i=gr(e,t);try{return await qo(e,Rh.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function zy(e){let t;try{t=await fI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>un(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function Jy(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as Wo}from"fs";import _t from"path";import{TextDecoder as RI}from"util";import{createHash as kI}from"node:crypto";import{constants as Cl,promises as W}from"node:fs";import Y from"node:path";import{TextDecoder as SI}from"node:util";function ze(e,t){let i=Y.relative(e,t);return i===""||!Y.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Y.sep}`)}function Gy(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function na(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Uy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ra(e,t){return z({...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 wr(e,t){let i=await W.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await W.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function yr(e,t,i){let r=Y.resolve(e),n=Y.resolve(t);if(!ze(r,n))throw new Error(`${i} is outside its managed root`);let a=[await wr(r,i)],o=r;for(let s of Y.relative(r,n).split(Y.sep).filter(Boolean)){await we(a,i),o=Y.join(o,s);let c=await wr(o,i);if(!ze(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await we(a,i),a}async function we(e,t){for(let i of e){let r=await W.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!na(i,r)||await W.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function EI(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function re(e){let t=Gy(e.maxBytes),i=Y.resolve(e.file),r=await yr(e.root,Y.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>wr(Y.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await we(r,e.label);let a=await W.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=Uy(a),s=await W.realpath(i);if(!ze(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ze(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Cl.O_RDONLY:Cl.O_RDONLY|Cl.O_NOFOLLOW|Cl.O_NONBLOCK,l=await W.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([W.lstat(i),W.realpath(i)]);if(await we(r,e.label),await we(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!ra(o,u)||!ra(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await EI(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([l.stat(),W.lstat(i),W.realpath(i)]);if(await we(r,e.label),await we(n,e.label),!m.isFile()||m.isSymbolicLink()||p!==s||!ra(o,v)||!ra(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:kI("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function xl(e){let t=await re(e),i;try{i=new SI("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function wt(e){let t=await yr(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await W.readdir(e.directory,{withFileTypes:!0});else{let r=Gy(e.maxEntries);i=[];let n=await W.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await we(t,e.label),{entries:i,verify:()=>we(t,e.label)}}async function Zt(e){let t=await yr(e.root,e.directory,e.label);return{verify:()=>we(t,e.label)}}async function PI(e){let t=Y.resolve(e.directory),i=Y.resolve(e.quarantine);if(Y.dirname(i)!==Y.dirname(t)||!ze(Y.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await yr(e.root,Y.dirname(t),e.label),n=await wr(t,e.label);if(!ze(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await we(r,e.label);let a=await W.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!na(n,a)||await W.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await W.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await W.rename(t,i),await we(r,e.label);let o=await W.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!na(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await W.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function Ky(e){await PI(e)}async function Al(e){let t=Y.resolve(e.file),i=await yr(e.root,Y.dirname(t),e.label),r=await W.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=Uy(r),a=await W.realpath(t);if(!ze(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await re({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!ra(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await we(i,e.label);let[l,u]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!ra(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await W.rm(t),await we(i,e.label)}async function Ch(e){let t=Y.resolve(e.directory),i=await yr(e.root,Y.dirname(t),e.label),r=await wr(t,e.label);if(!ze(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await we(i,e.label);let n=await W.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!na(r,n)||await W.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await W.rmdir(t),await we(i,e.label)}async function fi(e){let t=Y.resolve(e.root),i=Y.resolve(e.directory);if(!ze(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await wr(t,e.label)],n=t;for(let a of Y.relative(t,i).split(Y.sep).filter(Boolean)){await we(r,e.label),n=Y.join(n,a);try{await W.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await wr(n,e.label);if(!ze(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await we(r,e.label)}async function xh(e){let t=Y.resolve(e.root),i=Y.resolve(e.source),r=Y.resolve(e.target);if(i===r||!ze(t,i)||!ze(t,r)||ze(i,r)||ze(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await fi({root:t,directory:Y.dirname(r),label:`${e.label} target parent`});let n=await yr(t,Y.dirname(i),e.label),a=await yr(t,Y.dirname(r),e.label),o=await wr(i,e.label);if(!ze(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await W.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([we(n,e.label),we(a,e.label)]);let s=await W.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!na(o,s)||await W.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await W.rename(i,r),await Promise.all([we(n,e.label),we(a,e.label)]);let c=await W.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!na(o,c)||!ze(n[0].realPath,await W.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await W.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Nr(e){let t=await re({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await Uw(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await W.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await re({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await re({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var CI=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),xI=new Set(["id","type","source","target","staged","backup"]),AI=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),_I=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),TI=new Set(["sequence","timestamp","type","operationId"]),Zy=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),eN=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),II=256*1024,jI=1024*1024,tN=16*1024,Tl=1024,Th=64*1024*1024,$I=2e4,iN=new RI("utf-8",{fatal:!0});function zo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Jo(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function oa(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ah(e,t){if(typeof e!="string"||e.length===0||_t.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function _l(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Yy(e,t){if(Ah(e,t),e.includes("\\")||e!==_t.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 OI(e,t){let i=zo(e,`transaction operations[${t}]`);if(Jo(i,xI,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Ah(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ah(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function jl(e){let t=zo(e,"Native Archive transaction journal");if(Jo(t,AI,"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"||!Zy.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(!oa(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(_l(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 i=t.operations.map((s,c)=>{let l=zo(s,`Archive transaction operations[${c}]`);if(Jo(l,_I,`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`);Yy(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Yy(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&_l(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(_l(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`);_l(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.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)||i.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 i.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:i}}function Ih(e){let t=zo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return jl(t);if(Jo(t,CI,"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"||!Zy.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!_t.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!_t.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(!oa(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 i=t.operations.map(OI),r=i.map(n=>n.id);if(new Set(r).size!==r.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:i}}function rN(e,t){let i=zo(e,`Native transaction event at line ${t}`);if(Jo(i,TI,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!oa(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!eN.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function HI(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;r<e.length;r+=1){let n=t[r],a=e[r];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[r,n,a,o]of i){if(e.length<=r)continue;let s=e.slice(r,Math.min(r+n,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!oa(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||oa(e)}function aa(e,t){return e.length<t.length&&t.startsWith(e)}function DI(e){let t='","operationId":"';if(aa(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),r=i.indexOf('"');if(r===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let n=i.slice(0,r);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?aa(i.slice(r),'"}'):!1}function LI(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>tN)return!1;let i=`{"sequence":${t},"timestamp":"`;if(aa(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!HI(n))return!1;if(r.length<24)return!0;if(!oa(n))return!1;let a='","type":"',o=r.slice(24);if(aa(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of eN){if(aa(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(DI(l))return!0}else if(aa(l,'"}'))return!0}return!1}function MI(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>tN)throw new Error(`Native transaction event at line ${t} is too large`);return rN(JSON.parse(e),t)}function FI(e){let t=e.split(`
|
|
180
|
-
`),i=t.at(-1)==="";if(i&&t.pop(),t.length>
|
|
176
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=Sh(l,t);else if(i)Oy(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=Sh(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Oy(f))i=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);h&&n.has(h[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(f)&&(r=h[1])}}}if(c===-1)break;o=c+1}}function AI(e){return[...ta(e)].map(({line:t,body:i})=>({line:t,body:i}))}function qo(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function _I(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Ph(e,t,i,r=[],n="content-hash"){let a=qo(i),o=t.replaceAll("\\","/").trim(),s=r.map(qo);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-${H(NI,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Rh(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function II(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of ta(e)){n=s+1;let c=o?Eh(a):null;c?.level===1&&(ec(c.text)==="acceptanceExamples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function bl(e,t="brief.md",i=Wo.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=II(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of ta(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let h=f[1].length;a=a===null?h:Math.min(a,h)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of ta(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),Rh(o.map(l=>Ph("brief-example",t,l.join(`
|
|
177
|
+
`),[],r)),"Brief",r)}function kl(e,t="spec.md",i=Wo.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Ph("spec-scenario",t,[o.title,...o.body].join(`
|
|
178
|
+
`),o.context,r)),o=null}};for(let{line:c,body:l}of ta(e)){let u=l?Eh(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=qo(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(h=>h.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),Rh(n,"Specification",r)}function Dy(e,t="spec.md",i=Wo.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Ph("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of ta(e)){let f=d?Eh(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let h=u.trim();if(!d||o!==null||l()){c();continue}if(h.length===0||Sh(u,null)!==null||h.startsWith("<!--")||h==="-->"||h==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(h)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(h)||/^(?:[-*_]\s*){3,}$/u.test(h)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(h)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(m=>m.text)};continue}if(/^\|.*\|$/u.test(h)){c(),s={parts:[h],context:a.map(m=>m.text)},c();continue}s===null?s={parts:[h],context:a.map(m=>m.text)}:s.parts.push(h)}return c(),Rh(n,"Specification mandatory requirements",r)}function TI(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||_I(i)||_y.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=_y.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!SI.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function jI(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!kI.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function Ly(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=jI(i,r),a=n.acceptance_id;if(typeof a!="string"||!bI.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return TI(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function My(e){let t=AI(e);if(t.some(({line:l,body:u})=>!u&&(l===Iy||l===Ty)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===Iy?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===Ty?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
|
|
179
|
+
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=Ly(o),c=$I(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function $I(e){let t=Ly([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var OI=/^A[1-9]\d*$/u;function By(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Fy.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Fy.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function HI(e,t){return e.localeCompare(t,"en")}function Sl(e){let t=By(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>HI(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=bl(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=By(a.source,`Native spec source for ${a.capability}`);r.push(...kl(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=qo(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function Vy(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!OI.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function qy(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var Rl=$n(nn(),1);import{promises as DI}from"node:fs";var ia="comet.native.v4",zo="comet.native.local-execution.v4";var Wy=["multi-session","single-session"];function Ch(){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 LI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,MI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FI=/^A[1-9][0-9]*$/u,BI=/^[a-f0-9]{64}$/u,VI=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Pl=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Xe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qe(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ie(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Ah(e,t){return e===null?null:Ie(e,t)}function zy(e,t){let i=Ie(e,t);if(!BI.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function ra(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function me(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function qI(e,t){return e===null?null:me(e,t,Number.MIN_SAFE_INTEGER)}function Se(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function di(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function Cl(e,t){return di(e,t,(i,r)=>Ie(i,`${t}[${r}]`))}function cn(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function na(e,t){let i=Ie(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function _h(e,t,i=!1){let r=Ie(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function At(e,t){let i=Xe(e,t);return Qe(i,new Set(["text","truncated"]),t),{text:Ie(i.text,`${t}.text`,{empty:!0}),truncated:ra(i.truncated,`${t}.truncated`)}}function WI(e,t){let i=`Native spec_changes[${t}]`,r=Xe(e,i);Qe(r,new Set(["capability","operation","source"]),i);let n=Ie(r.capability,`${i}.capability`);if(!MI.test(n))throw new Error(`${i}.capability is invalid`);let a=Se(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:_h(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function zI(e){let t="Native workspace",i=Xe(e,t);Qe(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=Se(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Ah(i.change_branch,`${t}.change_branch`),a=Ah(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:Se(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function JI(e){let t="Native loop",i=Xe(e,t);Qe(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=Cl(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);cn(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:Se(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Se(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:me(i.goal_cycle,`${t}.goal_cycle`,1),iteration:me(i.iteration,`${t}.iteration`),attempt:me(i.attempt,`${t}.attempt`),retry_epoch:me(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:me(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:me(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:me(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Ah(i.next_action,`${t}.next_action`)}}function GI(e,t){let i=`Native acceptance[${t}]`,r=Xe(e,i);Qe(r,new Set(["id","source","text","result","reason"]),i);let n=Ie(r.id,`${i}.id`);if(!FI.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:_h(r.source,`${i}.source`),text:Ie(r.text,`${i}.text`),result:Se(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:At(r.reason,`${i}.reason`)}}function UI(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["name","result","note"]),i),{name:At(r.name,`${i}.name`),result:Se(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:At(r.note,`${i}.note`)}}function KI(e){let t="Native builder_handoff",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=Cl(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);cn(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:Xe(i.review,`${t}.review`);return n&&Qe(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:Ie(i.candidate_id,`${t}.candidate_id`),identity_provider:Ie(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:Ie(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),summary:At(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:di(i.checks,`${t}.checks`,UI),checks_truncated:ra(i.checks_truncated,`${t}.checks_truncated`),known_limits:di(i.known_limits,`${t}.known_limits`,(a,o)=>At(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ra(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:Se(n.status,["passed"],`${t}.review.status`),summary:At(n.summary,`${t}.review.summary`),reviewer_execution_ref:Ie(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:na(i.submitted_at,`${t}.submitted_at`)}}function YI(e,t){let i=`Native blockers[${t}]`,r=Xe(e,i);Qe(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Cl(r.acceptance_ids,`${i}.acceptance_ids`);return cn(n,`${i}.acceptance_ids`),{owner:Se(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:At(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:Se(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function XI(e,t){let i=`Native verification.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:Ie(r.id,`${i}.id`),name:At(r.name,`${i}.name`),argv_display:di(r.argv_display,`${i}.argv_display`,(n,a)=>At(n,`${i}.argv_display[${a}]`)),argv_truncated:ra(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:_h(r.cwd_ref,`${i}.cwd_ref`,!0),status:Se(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:qI(r.exit_code,`${i}.exit_code`),duration_ms:me(r.duration_ms,`${i}.duration_ms`)}}function QI(e){let t="Native verification",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=di(i.checks,`${t}.checks`,XI);cn(r.map(a=>a.id),`${t}.checks IDs`);let n=Ie(i.identity_provider,`${t}.identity_provider`);return{candidate_id:Ie(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Ie(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),attempt:me(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Se(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Se(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:At(i.summary,`${t}.summary`),risks:di(i.risks,`${t}.risks`,(a,o)=>At(a,`${t}.risks[${o}]`)),risks_truncated:ra(i.risks_truncated,`${t}.risks_truncated`),completed_at:na(i.completed_at,`${t}.completed_at`)}}function Jy(e,t){let i=`Native history[${t}]`,r=Xe(e,i);Qe(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Cl(r.unresolved_ids,`${i}.unresolved_ids`);return cn(n,`${i}.unresolved_ids`),{goal_cycle:me(r.goal_cycle,`${i}.goal_cycle`,1),iteration:me(r.iteration,`${i}.iteration`),attempt:me(r.attempt,`${i}.attempt`),outcome:Se(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:At(r.summary,`${i}.summary`),completed_at:na(r.completed_at,`${i}.completed_at`)}}function ZI(e){let t="Native history_overflow.outcome_counts",i=Xe(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Qe(i,new Set(r),t),{pass:me(i.pass,`${t}.pass`),fail:me(i.fail,`${t}.fail`),blocked:me(i.blocked,`${t}.blocked`),"execution-error":me(i["execution-error"],`${t}.execution-error`),recovery:me(i.recovery,`${t}.recovery`)}}function eT(e){let t="Native history_overflow",i=Xe(e,t);Qe(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=me(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:na(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:na(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=ZI(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function tT(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function iT(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function ct(e){let t=Xe(e,"Native portable state");if(Qe(t,VI,"Native portable state"),t.schema!==ia)throw new Error(`Native portable state schema must be ${ia}`);let i=Ie(t.name,"Native state name");if(!LI.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=di(t.spec_changes,"Native spec_changes",WI);cn(r.map(s=>s.capability),"Native spec change capabilities");let n=di(t.acceptance,"Native acceptance",GI);cn(n.map(s=>s.id),"Native acceptance IDs");let a=di(t.history,"Native history",Jy);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:ia,name:i,language:Se(t.language,["en","zh-CN"],"Native state language"),phase:Se(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Se(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:me(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:zy(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:zy(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:Se(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:zI(t.workspace),loop:JI(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:KI(t.builder_handoff),blockers:di(t.blockers,"Native blockers",YI),verification:t.verification===null?null:QI(t.verification),history:a,history_overflow:eT(t.history_overflow),verification_result:Se(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Se(t.verification_report,["verification.md"],"Native verification_report"),archived:ra(t.archived,"Native archived"),created_at:na(t.created_at,"Native created_at")};return tT(o),iT(o),o}function ln(e,t){let i=ct(e),r=Jy(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.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 ct({...i,history:n,history_overflow:a})}function rT(e,t){let i=(0,Rl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Ze(e){let t=await DI.readFile(e,"utf8");return ct(rT(t,"Native portable state"))}async function xl(e,t,i={}){let r=ct(t);await he(e,(0,Rl.stringify)(r),i)}var El=new Map;async function nT(e,t){let i=El.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);El.set(e,a),await i;try{return await t()}finally{r(),El.get(e)===a&&El.delete(e)}}async function un(e){return nT(e.file,async()=>{let t=me(e.expectedStateVersion,"Native expected state version",1),i=ct(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ze(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new Pl(t,r.state_version);return await xl(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ze(e.file);if(n.state_version!==t)throw new Pl(t,n.state_version)}}),i})}function aT(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function Ti(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(aT(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var Ne="comet.native.v3",be="comet.native.v2",et="comet.native.v1",wr="comet.native.transition.v3",ji="comet.native.transition.v2",dn="comet.native.transition.v1";var Al="comet.native.portable-migration.v1",sT=new Set(["schema","id","change","fromSchema","status","createdAt"]),cT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lT=/^[a-z0-9][a-z0-9-]{7,127}$/u,uT=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),dT=new Set([et,be,Ne]);function fT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hT(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function pT(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function mT(e){return e.schema===et?fn(e):e.schema===be?fi(e):lt(e)}function vT(e){return oT.posix.normalize(e.replaceAll("\\","/"))}function gT(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:vT(t.source)})}function wT(e){return e==="shape"?"shape":"build"}function yT(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function NT(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function Gy(e){let t=mT(e.state);Vy(e.acceptance);let i=wT(t.phase),r=i==="shape"?0:1,n=hT(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 ct({schema:ia,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:gT(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:yT(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:Ti(NT(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Ch(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Ih(e){let t=fT(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!sT.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Al)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!lT.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!cT.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"||!uT.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Al,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:pT(t.createdAt,"Native portable migration transaction createdAt")}}function Uy(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 _l="comet.native.archive-transaction.v4",Ky="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",kT=new RegExp(`^portable-archive-(${Ky})\\.json$`,"u"),ST=new RegExp(`^portable-migration-(${Ky})\\.json$`,"u"),ET=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,PT=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,RT=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),CT=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),xT=new Set(["capability","operation","source","content"]),Yy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Xy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qy(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function AT(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Xy(e,i);if(Qy(r,xT,i),typeof r.capability!="string"||!Yy.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function _T(e){let t=Xy(e,"Native portable Archive transaction");if(Qy(t,CT,"Native portable Archive transaction"),t.schema!==_l)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!ET.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Yy.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"||!PT.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"||!RT.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 i=t.spec_changes.map(AT);if(new Set(i.map(({capability:n})=>n)).size!==i.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)>i.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 r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:_l,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:i,created_at:t.created_at}}function hn(e){let t=kT.exec(e);if(t)return{kind:"archive",change:t[1]};let i=ST.exec(e);return i?{kind:"migration",change:i[1]}:null}function yr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=hn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Th.join(e.transactionsDir,i)}async function Jo(e,t){let i=hn(t);if(!i)return null;let r=await Z({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Th.join(e.transactionsDir,t);if(i.kind==="archive"){let s=_T(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=Ih(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function aa(e,t){let i=yr(e,t);try{return await Jo(e,Th.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Zy(e){let t;try{t=await bT.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>hn(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function eN(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as Go}from"fs";import _t from"path";import{TextDecoder as OT}from"util";import{createHash as IT}from"node:crypto";import{constants as Il,promises as W}from"node:fs";import Y from"node:path";import{TextDecoder as TT}from"node:util";function ze(e,t){let i=Y.relative(e,t);return i===""||!Y.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Y.sep}`)}function tN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function sa(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function iN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function oa(e,t){return z({...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 Nr(e,t){let i=await W.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await W.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function br(e,t,i){let r=Y.resolve(e),n=Y.resolve(t);if(!ze(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Nr(r,i)],o=r;for(let s of Y.relative(r,n).split(Y.sep).filter(Boolean)){await we(a,i),o=Y.join(o,s);let c=await Nr(o,i);if(!ze(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await we(a,i),a}async function we(e,t){for(let i of e){let r=await W.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!sa(i,r)||await W.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function jT(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function re(e){let t=tN(e.maxBytes),i=Y.resolve(e.file),r=await br(e.root,Y.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Nr(Y.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await we(r,e.label);let a=await W.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=iN(a),s=await W.realpath(i);if(!ze(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ze(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Il.O_RDONLY:Il.O_RDONLY|Il.O_NOFOLLOW|Il.O_NONBLOCK,l=await W.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([W.lstat(i),W.realpath(i)]);if(await we(r,e.label),await we(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!oa(o,u)||!oa(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await jT(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([l.stat(),W.lstat(i),W.realpath(i)]);if(await we(r,e.label),await we(n,e.label),!m.isFile()||m.isSymbolicLink()||p!==s||!oa(o,v)||!oa(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:IT("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Tl(e){let t=await re(e),i;try{i=new TT("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function wt(e){let t=await br(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await W.readdir(e.directory,{withFileTypes:!0});else{let r=tN(e.maxEntries);i=[];let n=await W.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await we(t,e.label),{entries:i,verify:()=>we(t,e.label)}}async function ei(e){let t=await br(e.root,e.directory,e.label);return{verify:()=>we(t,e.label)}}async function $T(e){let t=Y.resolve(e.directory),i=Y.resolve(e.quarantine);if(Y.dirname(i)!==Y.dirname(t)||!ze(Y.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await br(e.root,Y.dirname(t),e.label),n=await Nr(t,e.label);if(!ze(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await we(r,e.label);let a=await W.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!sa(n,a)||await W.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await W.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await W.rename(t,i),await we(r,e.label);let o=await W.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!sa(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await W.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function rN(e){await $T(e)}async function jl(e){let t=Y.resolve(e.file),i=await br(e.root,Y.dirname(t),e.label),r=await W.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=iN(r),a=await W.realpath(t);if(!ze(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await re({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!oa(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await we(i,e.label);let[l,u]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!oa(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await W.rm(t),await we(i,e.label)}async function jh(e){let t=Y.resolve(e.directory),i=await br(e.root,Y.dirname(t),e.label),r=await Nr(t,e.label);if(!ze(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await we(i,e.label);let n=await W.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!sa(r,n)||await W.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await W.rmdir(t),await we(i,e.label)}async function hi(e){let t=Y.resolve(e.root),i=Y.resolve(e.directory);if(!ze(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await Nr(t,e.label)],n=t;for(let a of Y.relative(t,i).split(Y.sep).filter(Boolean)){await we(r,e.label),n=Y.join(n,a);try{await W.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await Nr(n,e.label);if(!ze(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await we(r,e.label)}async function $h(e){let t=Y.resolve(e.root),i=Y.resolve(e.source),r=Y.resolve(e.target);if(i===r||!ze(t,i)||!ze(t,r)||ze(i,r)||ze(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await hi({root:t,directory:Y.dirname(r),label:`${e.label} target parent`});let n=await br(t,Y.dirname(i),e.label),a=await br(t,Y.dirname(r),e.label),o=await Nr(i,e.label);if(!ze(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await W.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([we(n,e.label),we(a,e.label)]);let s=await W.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!sa(o,s)||await W.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await W.rename(i,r),await Promise.all([we(n,e.label),we(a,e.label)]);let c=await W.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!sa(o,c)||!ze(n[0].realPath,await W.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await W.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function kr(e){let t=await re({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await ty(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await W.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await re({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await re({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var HT=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),DT=new Set(["id","type","source","target","staged","backup"]),LT=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),MT=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),FT=new Set(["sequence","timestamp","type","operationId"]),sN=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),cN=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),BT=256*1024,VT=1024*1024,lN=16*1024,Ol=1024,Dh=64*1024*1024,qT=2e4,uN=new OT("utf-8",{fatal:!0});function Uo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ko(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function la(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Oh(e,t){if(typeof e!="string"||e.length===0||_t.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function $l(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function nN(e,t){if(Oh(e,t),e.includes("\\")||e!==_t.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 WT(e,t){let i=Uo(e,`transaction operations[${t}]`);if(Ko(i,DT,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Oh(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Oh(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function Dl(e){let t=Uo(e,"Native Archive transaction journal");if(Ko(t,LT,"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"||!sN.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(!la(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if($l(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 i=t.operations.map((s,c)=>{let l=Uo(s,`Archive transaction operations[${c}]`);if(Ko(l,MT,`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`);nN(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&nN(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&$l(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($l(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`);$l(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.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)||i.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 i.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:i}}function Lh(e){let t=Uo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Dl(t);if(Ko(t,HT,"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"||!sN.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!_t.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!_t.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(!la(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 i=t.operations.map(WT),r=i.map(n=>n.id);if(new Set(r).size!==r.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:i}}function dN(e,t){let i=Uo(e,`Native transaction event at line ${t}`);if(Ko(i,FT,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!la(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!cN.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function zT(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;r<e.length;r+=1){let n=t[r],a=e[r];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[r,n,a,o]of i){if(e.length<=r)continue;let s=e.slice(r,Math.min(r+n,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!la(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||la(e)}function ca(e,t){return e.length<t.length&&t.startsWith(e)}function JT(e){let t='","operationId":"';if(ca(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),r=i.indexOf('"');if(r===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let n=i.slice(0,r);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?ca(i.slice(r),'"}'):!1}function GT(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>lN)return!1;let i=`{"sequence":${t},"timestamp":"`;if(ca(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!zT(n))return!1;if(r.length<24)return!0;if(!la(n))return!1;let a='","type":"',o=r.slice(24);if(ca(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of cN){if(ca(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(JT(l))return!0}else if(ca(l,'"}'))return!0}return!1}function UT(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>lN)throw new Error(`Native transaction event at line ${t} is too large`);return dN(JSON.parse(e),t)}function KT(e){let t=e.split(`
|
|
180
|
+
`),i=t.at(-1)==="";if(i&&t.pop(),t.length>Ol)throw new Error(`Native transaction event log exceeds ${Ol} events`);let r=[];for(let n=0;n<t.length;n+=1){let a=n+1,o=t[n],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&n===t.length-1;try{r.push(UT(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&>(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return r}function fN(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
181
181
|
`)}
|
|
182
|
-
`}function BI(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return _t.join(e.transactionsDir,t)}function $l(e,t){let i=BI(e,t);return{directory:i,journal:_t.join(i,"transaction.json"),events:_t.join(i,"events.jsonl"),staged:_t.join(i,"staged"),backups:_t.join(i,"backups")}}async function hi(e,t){let i=$l(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function VI(e,t){if(t.length===0||_t.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=_t.resolve(n,...a.split(/[\\/]/u));if(!O(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function br(e,t){let i=VI(e,t);return T(j(e,i),i)}async function dn(e){try{return await Wo.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jh(e,t,i={}){let r=await hi(e,t);try{await Wo.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await re({root:e.runtimeDir,file:r.events,maxBytes:jI,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=iN.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=FI(a),s=nN(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function Xy(e,t,i){let r=await jh(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Tt(e,t,i,r){let n=await hi(e,t),a=await jh(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await he(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>Xy(e,t,a)}),o;if(a.events.length>=Tl)throw new Error(`Native transaction event log ${t} exceeds ${Tl} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return rN(s,s.sequence),await Wo.mkdir(n.directory,{recursive:!0}),await he(n.events,nN([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>Xy(e,t,a)}),s}async function aN(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=Ih(t);let i=await hi(e,t.id);await Wo.mkdir(i.staged,{recursive:!0}),await Wo.mkdir(i.backups,{recursive:!0}),await ee(i.journal,t,{containedRoot:e.runtimeDir}),await Tt(e,t.id,"prepared")}async function yt(e,t,i={}){let r=await hi(e,t),n=await re({root:e.runtimeDir,file:r.journal,maxBytes:II,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(iN.decode(n.bytes)),o=Ih(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function kr(e,t,i={}){return(await jh(e,t,i)).events}async function Il(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=Ih({...t,status:i});return await ee((await hi(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function _h(e,t,i){try{return await re({root:j(e,t),file:t,maxBytes:Th,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function $h(e,t,i,r){let n=await _h(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await _h(e,i,`${r} target`);await fi({root:j(e,i),directory:_t.dirname(i),label:`${r} target parent`}),await Nr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:Th,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function oN(e,t,i){let r=await _h(e,t,i);r&&await Al({root:j(e,t),file:t,maxBytes:Th,expectedHash:r.hash,expectedSize:r.size,label:i})}async function Qy(e,t){if(!t.backup)return;let i=await br(e,t.target),r=await br(e,t.backup);!await dn(i)||await dn(r)||await $h(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function qI(e,t){let i=await br(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await Qy(e,t),await $h(e,await br(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await Qy(e,t),await oN(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await br(e,t.source),[n,a]=await Promise.all([dn(r),dn(i)]);if(!n&&a){await(await wt({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:$I})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await xh({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function sN(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await Il(e,t,"applying"):t,n=await kr(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await Tt(e,r.id,"operation-started",s.id),await qI(e,s),await Tt(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await yt(e,r.id),r}async function WI(e,t){let i=await br(e,t.target),r=t.backup?await br(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await br(e,t.source);if(await dn(i)){if(await dn(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await xh({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await dn(r)?await $h(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await oN(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function Ol(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await kr(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await Il(e,t,"rolling-back");await Tt(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await WI(e,a);return await Tt(e,r.id,"rollback-completed"),r=await Il(e,r,"rolled-back"),r}async function sa(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Tt(e,t.id,i),i==="commit"?Il(e,t,"committed"):t}async function GI(e,t,i){let r;try{r=await zI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await yt(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(un(n.name))try{let a=await qo(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Jy(a))return!0}catch{return!0}return!1}async function UI(e,t){let i=Date.now()+5e3,r=JI.join(e.locksDir,"root-move.lock");for(;;)try{return await pr(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Lo(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function se(e,t,i,r){let n=await UI(e,t);try{if(await Yn(e.projectRoot),await GI(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await mr(n)}}function cN(e){return Number.isSafeInteger(e)&&e>=1}async function lN(e){if(!cN(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!cN(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Fl}from"crypto";import{spawn as yN}from"node:child_process";import{promises as ce}from"fs";import V from"path";import{createHash as uN}from"crypto";import{createReadStream as KI}from"fs";async function ei(e){let t=uN("sha256");for await(let i of KI(e))t.update(i);return t.digest("hex")}function L(e){return uN("sha256").update(e).digest("hex")}var Hl={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Fh=1e3,YI=8*1024*1024,XI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,QI=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),ZI=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),ej=new Set(["schema","include","exclude","hash"]),tj=new Set(["provider","gitSelection","physicalSelection","projection"]),ij=new Set(["provider","selection"]),rj=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),nj=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),aj=new Set(["schema","status","before","after"]),oj=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),sj=new Set(["path","hash","size","type","gitObjectId"]),cj=new Set(["path","size","type","reason"]),lj=new Set(["ref","hash","count"]),uj=new Set(["change-created","legacy-migration","explicit"]),dj=new Set(["file","directory","other"]),fj=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"]),Bl=/^[a-f0-9]{64}$/u,NN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,hj=new Set(["EACCES","EPERM"]),fa=64*1024,Lh=64*1024,pj=6e4,mj=1e3,vj=2,Bh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},gj={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function bN(e){let t=e.deadlineMs??pj;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function ti(e){return Math.max(0,e.deadlineAt-Date.now())}function M(e){return ti(e)>=1}function Oh(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function ua(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function wj(e){let t={...gj,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function yj(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&V.win32.isAbsolute(r)?V.win32.resolve(r):"C:\\Windows",a=V.win32.join(n,"System32","taskkill.exe");if(!V.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=yN(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),mj),u.unref()}catch{d(!1)}});for(let s=0;s<vj;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function Vh(e,t,i,r){let n=ti(e);if(n<1)throw Oh();let a=e.gitProcess,o=yN(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",h=>{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=yj(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let v=await l;throw v?.error?Oh(v.error):Oh()}return{code:h,spawnError:s}});return{child:o,completion:f}}function kN(e){let t={...Bh,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Dl(e,t,i,r=Lh){let{child:n,completion:a}=Vh(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(h).subarray(0,v)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=fa)return;let v=fa-c,m=Buffer.from(h).subarray(0,v);s.push(m),c+=m.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Hh(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Uo(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Vh(e,t,i,r.stdin!==void 0),c=[],l=Fl("sha256"),u=[],d=0,f=0,h=0,v=0,m=Buffer.alloc(0),p=!1,b=!1,g=!1,y=E=>{let k=0;for(;k<E.byteLength;){let S=E.indexOf(0,k),R=S<0?E.byteLength:S,N=E.subarray(k,R);if(!p&&N.byteLength>0&&(m.byteLength+N.byteLength>r.maxRecordBytes?(m=Buffer.alloc(0),p=!0,b=!0):m=Buffer.concat([m,N])),S<0)break;v+=1,m.byteLength===0&&!p&&(g=!0);let w=m.byteLength+1;!p&&v<=r.maxRecords&&h+w<=r.maxBytes?(c.push(m),h+=w):b=!0,m=Buffer.alloc(0),p=!1,k=S+1}};o.stdout.on("data",E=>{l.update(E),f+=E.byteLength,f>r.maxBytes&&(b=!0);let k=r.outputChunkBytes;if(k===void 0){y(E);return}for(let S=0;S<E.byteLength;S+=k)y(E.subarray(S,Math.min(E.byteLength,S+k)))}),o.stderr.on("data",E=>{if(d>=fa)return;let k=fa-d,S=Buffer.from(E).subarray(0,k);u.push(S),d+=S.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:E,spawnError:k})=>{let S=r.acceptedExitCodes??[0];if(E!==null&&S.includes(E)&&k===null&&!g&&m.byteLength===0&&!p){n({records:c,digest:l.digest("hex"),overflow:b,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:g||m.byteLength>0||p?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function Ll(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function Nj(e,t,i){if(i.length===0)return new Set;let r=await Uo(e,t,["check-ignore","--no-index","-z","--stdin"],{...Bh,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=Ll(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function bj(e,t,i){let{child:r,completion:n}=Vh(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=fa)return;let d=fa-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function da(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||V.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||V.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function kj(e,t){return e.map(i=>{let r=da(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function Sj(e){let t=V.resolve(e);for(;;){try{return await ce.lstat(V.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=V.dirname(t);if(i===t)return!1;t=i}}async function SN(e,t,i,r={}){let n=V.resolve(t.projectRoot),a=V.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=V.relative(n,V.resolve(f)).replaceAll("\\","/"),v=da(h);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Uo(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Uo(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Uo(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function EN(e){return{stageBefore:Hh(e.stagedBefore),combined:Hh(e.combined),stageAfter:Hh(e.stagedAfter)}}async function PN(e,t,i=Bh,r={}){let n=V.resolve(t.projectRoot);if(!await Sj(n))return null;let a;try{a=await Dl(e,n,["rev-parse","--is-inside-work-tree"])}catch(g){throw ua(g)?g:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:g})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await SN(e,t,i,r)}catch(g){throw ua(g)?g:new Error("Native Git snapshot provider failed after repository detection",{cause:g})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=g=>{for(let y of g){let E=Ll(y),k=E.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let S=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(E.slice(0,k))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=da(E.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),S.stage==="0"&&d.set(R,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let v=c.records.map(Ll),m=kj(v,"combined"),p=new Set(m.filter(g=>!u.has(g))),b=new Set(m.filter((g,y)=>!u.has(g)&&v[y].endsWith("/")));for(let g of f)b.delete(g);return{tracked:u,trackedObjectIds:d,untracked:p,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:EN(o)}}function Er(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function dN(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function Ej(e,t){return!Er(e.stageBefore,e.stageAfter)||!Er(e.stageAfter,t.stageBefore)||!Er(e.combined,t.combined)||!Er(t.stageBefore,t.stageAfter)}async function RN(e,t,i,r,n){let a;try{a=await SN(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw ua(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=EN(a),c=dN(o)||dN(s),l=Ej(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:L(`comet.native.git-selection-overflow.v2
|
|
183
|
-
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var
|
|
182
|
+
`}function YT(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return _t.join(e.transactionsDir,t)}function Ll(e,t){let i=YT(e,t);return{directory:i,journal:_t.join(i,"transaction.json"),events:_t.join(i,"events.jsonl"),staged:_t.join(i,"staged"),backups:_t.join(i,"backups")}}async function pi(e,t){let i=Ll(e,t);return await Promise.all(Object.values(i).map(r=>I(e.runtimeDir,r))),i}function XT(e,t){if(t.length===0||_t.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=_t.resolve(n,...a.split(/[\\/]/u));if(!O(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function Sr(e,t){let i=XT(e,t);return I(j(e,i),i)}async function pn(e){try{return await Go.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Mh(e,t,i={}){let r=await pi(e,t);try{await Go.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await re({root:e.runtimeDir,file:r.events,maxBytes:VT,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=uN.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=KT(a),s=fN(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function aN(e,t,i){let r=await Mh(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function It(e,t,i,r){let n=await pi(e,t),a=await Mh(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await he(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>aN(e,t,a)}),o;if(a.events.length>=Ol)throw new Error(`Native transaction event log ${t} exceeds ${Ol} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return dN(s,s.sequence),await Go.mkdir(n.directory,{recursive:!0}),await he(n.events,fN([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>aN(e,t,a)}),s}async function hN(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=Lh(t);let i=await pi(e,t.id);await Go.mkdir(i.staged,{recursive:!0}),await Go.mkdir(i.backups,{recursive:!0}),await ee(i.journal,t,{containedRoot:e.runtimeDir}),await It(e,t.id,"prepared")}async function yt(e,t,i={}){let r=await pi(e,t),n=await re({root:e.runtimeDir,file:r.journal,maxBytes:BT,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(uN.decode(n.bytes)),o=Lh(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Er(e,t,i={}){return(await Mh(e,t,i)).events}async function Hl(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=Lh({...t,status:i});return await ee((await pi(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function Hh(e,t,i){try{return await re({root:j(e,t),file:t,maxBytes:Dh,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Fh(e,t,i,r){let n=await Hh(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await Hh(e,i,`${r} target`);await hi({root:j(e,i),directory:_t.dirname(i),label:`${r} target parent`}),await kr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:Dh,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function pN(e,t,i){let r=await Hh(e,t,i);r&&await jl({root:j(e,t),file:t,maxBytes:Dh,expectedHash:r.hash,expectedSize:r.size,label:i})}async function oN(e,t){if(!t.backup)return;let i=await Sr(e,t.target),r=await Sr(e,t.backup);!await pn(i)||await pn(r)||await Fh(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function QT(e,t){let i=await Sr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await oN(e,t),await Fh(e,await Sr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await oN(e,t),await pN(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await Sr(e,t.source),[n,a]=await Promise.all([pn(r),pn(i)]);if(!n&&a){await(await wt({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:qT})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await $h({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function mN(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await Hl(e,t,"applying"):t,n=await Er(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await It(e,r.id,"operation-started",s.id),await QT(e,s),await It(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await yt(e,r.id),r}async function ZT(e,t){let i=await Sr(e,t.target),r=t.backup?await Sr(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await Sr(e,t.source);if(await pn(i)){if(await pn(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await $h({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await pn(r)?await Fh(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await pN(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function Ml(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await Er(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await Hl(e,t,"rolling-back");await It(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await ZT(e,a);return await It(e,r.id,"rollback-completed"),r=await Hl(e,r,"rolled-back"),r}async function ua(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await It(e,t.id,i),i==="commit"?Hl(e,t,"committed"):t}async function ij(e,t,i){let r;try{r=await ej.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await yt(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(hn(n.name))try{let a=await Jo(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(eN(a))return!0}catch{return!0}return!1}async function rj(e,t){let i=Date.now()+5e3,r=tj.join(e.locksDir,"root-move.lock");for(;;)try{return await vr(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Bo(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function se(e,t,i,r){let n=await rj(e,t);try{if(await Zn(e.projectRoot),await ij(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await gr(n)}}function vN(e){return Number.isSafeInteger(e)&&e>=1}async function gN(e){if(!vN(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!vN(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Wl}from"crypto";import{spawn as CN}from"node:child_process";import{promises as ce}from"fs";import V from"path";import{createHash as wN}from"crypto";import{createReadStream as nj}from"fs";async function ti(e){let t=wN("sha256");for await(let i of nj(e))t.update(i);return t.digest("hex")}function L(e){return wN("sha256").update(e).digest("hex")}var Fl={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Jh=1e3,aj=8*1024*1024,oj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sj=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),cj=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),lj=new Set(["schema","include","exclude","hash"]),uj=new Set(["provider","gitSelection","physicalSelection","projection"]),dj=new Set(["provider","selection"]),fj=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),hj=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),pj=new Set(["schema","status","before","after"]),mj=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),vj=new Set(["path","hash","size","type","gitObjectId"]),gj=new Set(["path","size","type","reason"]),wj=new Set(["ref","hash","count"]),yj=new Set(["change-created","legacy-migration","explicit"]),Nj=new Set(["file","directory","other"]),bj=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"]),zl=/^[a-f0-9]{64}$/u,xN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,kj=new Set(["EACCES","EPERM"]),ma=64*1024,Wh=64*1024,Sj=6e4,Ej=1e3,Pj=2,Gh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Rj={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function AN(e){let t=e.deadlineMs??Sj;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function ii(e){return Math.max(0,e.deadlineAt-Date.now())}function M(e){return ii(e)>=1}function Bh(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function ha(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function Cj(e){let t={...Rj,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function xj(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&V.win32.isAbsolute(r)?V.win32.resolve(r):"C:\\Windows",a=V.win32.join(n,"System32","taskkill.exe");if(!V.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=CN(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),Ej),u.unref()}catch{d(!1)}});for(let s=0;s<Pj;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function Uh(e,t,i,r){let n=ii(e);if(n<1)throw Bh();let a=e.gitProcess,o=CN(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",h=>{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=xj(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let v=await l;throw v?.error?Bh(v.error):Bh()}return{code:h,spawnError:s}});return{child:o,completion:f}}function _N(e){let t={...Gh,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Bl(e,t,i,r=Wh){let{child:n,completion:a}=Uh(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(h).subarray(0,v)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=ma)return;let v=ma-c,m=Buffer.from(h).subarray(0,v);s.push(m),c+=m.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Vh(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Xo(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Uh(e,t,i,r.stdin!==void 0),c=[],l=Wl("sha256"),u=[],d=0,f=0,h=0,v=0,m=Buffer.alloc(0),p=!1,b=!1,g=!1,S=N=>{let k=0;for(;k<N.byteLength;){let E=N.indexOf(0,k),R=E<0?N.byteLength:E,y=N.subarray(k,R);if(!p&&y.byteLength>0&&(m.byteLength+y.byteLength>r.maxRecordBytes?(m=Buffer.alloc(0),p=!0,b=!0):m=Buffer.concat([m,y])),E<0)break;v+=1,m.byteLength===0&&!p&&(g=!0);let w=m.byteLength+1;!p&&v<=r.maxRecords&&h+w<=r.maxBytes?(c.push(m),h+=w):b=!0,m=Buffer.alloc(0),p=!1,k=E+1}};o.stdout.on("data",N=>{l.update(N),f+=N.byteLength,f>r.maxBytes&&(b=!0);let k=r.outputChunkBytes;if(k===void 0){S(N);return}for(let E=0;E<N.byteLength;E+=k)S(N.subarray(E,Math.min(N.byteLength,E+k)))}),o.stderr.on("data",N=>{if(d>=ma)return;let k=ma-d,E=Buffer.from(N).subarray(0,k);u.push(E),d+=E.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:k})=>{let E=r.acceptedExitCodes??[0];if(N!==null&&E.includes(N)&&k===null&&!g&&m.byteLength===0&&!p){n({records:c,digest:l.digest("hex"),overflow:b,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:g||m.byteLength>0||p?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function Vl(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function Aj(e,t,i){if(i.length===0)return new Set;let r=await Xo(e,t,["check-ignore","--no-index","-z","--stdin"],{...Gh,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=Vl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function _j(e,t,i){let{child:r,completion:n}=Uh(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=ma)return;let d=ma-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function pa(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||V.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||V.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function Ij(e,t){return e.map(i=>{let r=pa(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function Tj(e){let t=V.resolve(e);for(;;){try{return await ce.lstat(V.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=V.dirname(t);if(i===t)return!1;t=i}}async function IN(e,t,i,r={}){let n=V.resolve(t.projectRoot),a=V.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=V.relative(n,V.resolve(f)).replaceAll("\\","/"),v=pa(h);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Xo(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Xo(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Xo(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function TN(e){return{stageBefore:Vh(e.stagedBefore),combined:Vh(e.combined),stageAfter:Vh(e.stagedAfter)}}async function jN(e,t,i=Gh,r={}){let n=V.resolve(t.projectRoot);if(!await Tj(n))return null;let a;try{a=await Bl(e,n,["rev-parse","--is-inside-work-tree"])}catch(g){throw ha(g)?g:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:g})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await IN(e,t,i,r)}catch(g){throw ha(g)?g:new Error("Native Git snapshot provider failed after repository detection",{cause:g})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=g=>{for(let S of g){let N=Vl(S),k=N.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let E=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(N.slice(0,k))?.groups;if(!E)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=pa(N.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),E.stage==="0"&&d.set(R,E.objectId),E.mode==="160000"&&E.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let v=c.records.map(Vl),m=Ij(v,"combined"),p=new Set(m.filter(g=>!u.has(g))),b=new Set(m.filter((g,S)=>!u.has(g)&&v[S].endsWith("/")));for(let g of f)b.delete(g);return{tracked:u,trackedObjectIds:d,untracked:p,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:TN(o)}}function Rr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function yN(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function jj(e,t){return!Rr(e.stageBefore,e.stageAfter)||!Rr(e.stageAfter,t.stageBefore)||!Rr(e.combined,t.combined)||!Rr(t.stageBefore,t.stageAfter)}async function $N(e,t,i,r,n){let a;try{a=await IN(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw ha(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=TN(a),c=yN(o)||yN(s),l=jj(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:L(`comet.native.git-selection-overflow.v2
|
|
183
|
+
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var $j=(1n<<256n)-1n;function Oj(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function NN(e){let t=V.resolve(e.paths.projectRoot),i=V.resolve(e.paths.nativeRoot),r=V.resolve(e.paths.runtimeDir),n=V.resolve(e.paths.configFile),a=V.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,v=!1,m=!1,p=()=>ii(e.execution)>=1?!0:(h=!0,m=!0,!1),b=N=>{let k=Buffer.from(`${N.type}\0${N.path}`,"utf8"),E=Wl("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;R<c.length;R+=1)c[R]^=E[R];if(l=l+BigInt(`0x${E.toString("hex")}`)&$j,d+=1,f+=k.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){h=!0,m=!0;return}o.push(N)},g=async N=>{if(m||!p())return;let k;try{k=await ce.opendir(N)}catch(P){if(!p())return;if(!Pe(P)&&!Ee(P)||N===t&&Pe(P))throw P;v||=Ee(P),h||=Pe(P),m=!0;return}if(!p()){try{await k.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let E=!1,R;try{for(;!m&&p();){let P;try{P=await k.read()}catch(te){if(!p())break;if(!Pe(te)&&!Ee(te)||N===t&&Pe(te))throw te;v||=Ee(te),h||=Pe(te),m=!0;break}if(!p()||P===null)break;if(u+=1,u>e.limits.maxNodes){h=!0,m=!0;break}let F=V.join(N,P.name),$=Dj(t,F);if(F===n||F===a||ri(i,F)||ri(r,F)||e.denylist.some(te=>ri(te,F))||ui($)!==null)continue;if(!p())break;let Be;try{Be=await ce.lstat(F)}catch(te){if(!p())break;if(!Pe(te)&&!Ee(te))throw te;if(v=!0,b({path:$,type:"other"}),s.push({path:$,size:null,type:"file",reason:Pe(te)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),m||!p())break;continue}if(!p())break;let ue=Oj(Be);if(ue==="directory"){if(Bj(e.policy,$))continue;if(!p())break;let te;try{te=await ce.realpath(F)}catch(si){if(!p())break;if(!Pe(si)&&!Ee(si))throw si;if(v=!0,b({path:$,type:ue}),s.push({path:$,size:null,type:"directory",reason:Pe(si)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),m||!p())break;continue}if(!p())break;if(!O(e.physicalProjectRoot,te)||ri(e.physicalNativeRoot,te))continue;if(b({path:$,type:ue}),await e.hooks?.afterNode?.($),!p()||(await g(F),m))break;continue}if(b({path:$,type:ue}),await e.hooks?.afterNode?.($),!p()||m)break}}catch(P){E=!0,R=P}let y;try{await k.close()}catch(P){y=P}let w=p();if(E)throw R;if(w&&y!==void 0&&y.code!=="ERR_DIR_CLOSED")throw y};await g(t),p(),h?(o.length=0,d=0,f=0):(o.sort((N,k)=>N.path.localeCompare(k.path,"en")),s.sort((N,k)=>N.path.localeCompare(k.path,"en")));let S=h?L(`comet.native.physical-selection-incomplete.v1
|
|
184
184
|
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):L(`comet.native.physical-selection.v1
|
|
185
|
-
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:
|
|
186
|
-
`)}function
|
|
187
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function
|
|
185
|
+
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:S,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:v}}}function ON(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 Hj(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!ON(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function HN(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function bN(e,t){let r=(await Bl(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!xN.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return L(`gitlink:${r}`)}async function kN(e,t){let i=await bN(e,t),r=await _j(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await bN(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function Yo(e,t){if(ui(t)!==null)return!1;let i=V.resolve(e.projectRoot,...t.split("/"));return!ri(V.resolve(e.nativeRoot),i)&&!ri(V.resolve(e.runtimeDir),i)}function Kh(e,t={}){let i=$i(e),r=t.maxRecordedPaths??20;if(!Number.isSafeInteger(r)||r<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=i.omitted.slice(0,r).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.length<i.omittedCount}}function Dj(e,t){return V.relative(e,t).split(V.sep).join("/")}function Lj(e,t){return t.map(i=>V.resolve(e,...i.split(/[\\/]/u)))}function ri(e,t){let i=V.resolve(e),r=V.resolve(t);return r===i||O(i,r)}function Pe(e){return kj.has(e.code??"")}function Ee(e){return e.code==="ENOENT"}function Yh(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
186
|
+
`)}function Mj(e,t){return L(`comet.native.snapshot-policy.v1
|
|
187
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function qh(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function Fj(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function SN(e){let t=ml(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?Fj(n):void 0;if(a&&!a())return!1;let o=qh(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=qh(i,c,a),o===null||o.size===0)return!1}return qh(i,o,a)?.has(i.length)??!1}}function DN(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>ml(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>ml(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=Mj(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(SN),excludeMatchers:i.map(SN),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function Bj(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function EN(e,t,i){if(!e)return!0;let r=()=>M(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function Qo(e,t,i){let r=JSON.stringify(i);return L(`${e}
|
|
188
188
|
${Buffer.byteLength(t)}:${t}
|
|
189
|
-
${Buffer.byteLength(r)}:${r}`)}function Mh(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Ml(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Mh(i))return e.splice(t,1),i}return null}function Sr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function jj(e,t,i,r){if(!M(r))return{status:"budget-exhausted"};let n;try{n=await ce.open(e,"r")}catch(c){if(!M(r))return{status:"budget-exhausted"};throw c}if(!M(r))return await n.close(),{status:"budget-exhausted"};let a=Fl("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!M(r))return{status:"budget-exhausted"};let c=await n.stat();if(!M(r))return{status:"budget-exhausted"};if(!c.isFile()||!Sr(i,c))return{status:"changed"};for(;;){if(!M(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!M(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!M(r))return{status:"budget-exhausted"};let d=await n.stat();return M(r)?!d.isFile()||!Sr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function It(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jt(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function la(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function pi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function _N(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=V.posix.normalize(e);if(i!==e||V.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function $j(e,t){let i=It(e,`Native snapshot entry ${t}`);jt(i,sj,`Native snapshot entry ${t}`);let r=_N(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Bl.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:pi(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!NN.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function Oj(e,t){let i=It(e,`Native snapshot omission ${t}`);if(jt(i,cj,`Native snapshot omission ${t}`),!dj.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!fj.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:_N(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:pi(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function Hj(e){let t=It(e,"Native snapshot omission overflow");if(jt(t,lj,"Native snapshot omission overflow"),typeof t.hash!="string"||!Bl.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:la(t.count,"Native snapshot omission overflow count")}}function ca(e,t){let i=It(e,t);if(jt(i,nj,t),typeof i.hash!="string"||!Bl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=pi(i.recordCount,`${t} recordCount`),n=pi(i.storedRecordCount,`${t} storedRecordCount`),a=pi(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function gN(e){let t=It(e,"Native Git selection evidence");if(jt(t,rj,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=ca(t.stageBefore,"Native Git selection stageBefore"),r=ca(t.combined,"Native Git selection combined"),n=ca(t.stageAfter,"Native Git selection stageAfter"),a=ca(t.finalStageBefore,"Native Git selection finalStageBefore"),o=ca(t.finalCombined,"Native Git selection finalCombined"),s=ca(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!Er(i,n)||!Er(n,a)||!Er(r,o)||!Er(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function wN(e,t){let i=It(e,t);if(jt(i,oj,t),typeof i.hash!="string"||!Bl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=pi(i.visitedNodeCount,`${t} visitedNodeCount`),n=pi(i.recordCount,`${t} recordCount`),a=pi(i.storedRecordCount,`${t} storedRecordCount`),o=pi(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function Dj(e){let t=It(e,"Native physical selection evidence");if(jt(t,aj,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=wN(t.before,"Native physical selection before"),r=wN(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!CN(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function $i(e){let t=It(e,"Native content snapshot manifest");if(jt(t,QI,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!uj.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let S=It(t.capture,"Native content snapshot capture");if(jt(S,tj,"Native content snapshot capture"),S.provider!=="git"&&S.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=S.gitSelection===void 0?void 0:gN(S.gitSelection),N=S.physicalSelection===void 0?void 0:Dj(S.physicalSelection),w=null;if(S.projection!==void 0){let P=It(S.projection,"Native content snapshot projection");if(jt(P,ij,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...P.selection===void 0?{}:{selection:gN(P.selection)}}}if(S.provider==="git"){if(N||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=It(t.limits,"Native content snapshot limits");jt(r,ZI,"Native content snapshot limits");let n={maxFiles:la(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:la(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:la(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:la(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:la(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let S=It(t.policy,"Native snapshot policy");if(jt(S,ej,"Native snapshot policy"),S.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(S.include)||!Array.isArray(S.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=AN({include:S.include,exclude:S.exclude,hash:S.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($j),s=t.omitted.map(Oj),c=pi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:Hj(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(S=>S.size>n.maxFileBytes)||o.reduce((S,R)=>S+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(S=>S.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Fh||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(S=>S.reason==="git-enumeration-limit"),f=s.filter(S=>S.reason==="git-selection-changed");for(let S of[...d,...f])if(S.path!=="."||S.size!==null||S.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",m=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(m!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let p=s.filter(S=>S.reason==="physical-enumeration-limit"),b=s.filter(S=>S.reason==="physical-selection-changed");for(let S of[...p,...b])if(S.path!=="."||S.size!==null||S.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||b.length>1)throw new Error("Native physical selection omissions must not be duplicated");let g=i?.physicalSelection,y=g?.status==="overflow"||g?.status==="overflow-and-changed",E=g?.status==="changed"||g?.status==="overflow-and-changed";if(y!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(E!==(b.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Wh(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function Vl(e,t,i={}){let r=$i(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=V.resolve(e.projectRoot),a=bN(i),o=kN(i.gitSelectionLimits),s=await PN(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(xN(s).filter(N=>Go(e,N))),l=[...s.gitlinks].filter(N=>c.has(N)),u=[...s.nestedRepositories].filter(N=>Go(e,N)),d=(N,w)=>w.some(P=>N===P||N.startsWith(`${P}/`)),f=N=>d(N,l),h=N=>d(N,u),v=[...r.entries.map(N=>N.path),...r.omitted.flatMap(N=>N.type==="directory"?[N.path,`${N.path}/`]:[N.path])].filter(N=>!c.has(N)&&!f(N)&&!h(N)),m=await Nj(a,n,v),p=r.entries.filter(N=>!f(N.path)&&!h(N.path)&&Go(e,N.path)&&(c.has(N.path)||!m.has(N.path)));await RN(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let N of l)b.push({path:N,size:null,type:"directory",reason:"legacy-gitlink-boundary"});p.sort((N,w)=>N.path.localeCompare(w.path,"en"));let g=r.omitted.filter(N=>f(N.path)||h(N.path)||!Go(e,N.path)?!1:m.has(N.path)?c.has(N.path)||[...c].some(w=>w.startsWith(`${N.path}/`)):!0);for(let N of b)g.some(w=>w.path===N.path&&w.reason===N.reason)||g.push(N);g.sort((N,w)=>N.path.localeCompare(w.path,"en"));let y=r.omissionOverflow?.count??0,E=r.omissionOverflow?.hash??L("comet.native.snapshot-omission-overflow.v1");s.overflow&&(y+=s.overflow.count,E=Ko(E,"git-selection",{source:"git-selection",...s.overflow}));let k=N=>{y+=1,E=Ko(E,"omission",N)};for(;g.length>Fh;){let N=Ml(g);if(N===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(N)}let S=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:g.length+y===0,entries:p,omitted:g,omittedCount:g.length+y,...y>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:y}}:{}}),R=S();for(;Wh(R)>r.limits.maxManifestBytes;){let N=Ml(g);if(N===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(N),R=S()}return $i(R)}function TN(e,t){if(!XI.test(t))throw new Error(`Invalid Native change name: ${t}`);return V.join(H(e,t),"baseline-manifest.json")}async function ql(e,t={}){let i={maxFiles:t.limits?.maxFiles??Hl.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Hl.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Hl.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Hl.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=AN(t.policy),n=bN({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=kN(t.gitSelectionLimits),o=wj(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=V.resolve(e.projectRoot),c=await ce.realpath(s),l=V.resolve(e.nativeRoot),u=await ce.realpath(l),d=V.resolve(e.runtimeDir),f=V.resolve(e.configFile),h=V.join(s,".comet","current-change.json"),v=Aj(s,t.denylist??[]),m=[],p=[],b=new Map,g=new Map,y=0,E=0,k=L("comet.native.snapshot-omission-overflow.v1"),S=0,R=!1,N=null,w=_=>{E+=1,k=Ko(k,"omission",_)},P=_=>{if(y+=1,p.length<Fh){p.push(_);return}if(Mh(_)){let A=Ml(p);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),p.push(_);return}w(_)},F=_=>{y+=_.count,E+=_.count,k=Ko(k,"git-selection",{source:"git-selection",..._})},$=_=>{E+=1,k=Ko(k,"manifest-entry",{reason:"manifest-size",entry:_})},Be=async(_,A)=>{m.push(_),S+=_.size,b.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},ue=(_,A)=>{let I=m.findIndex(oe=>oe.path===_);if(I<0)return;let[q]=m.splice(I,1);S-=q.size,b.delete(_),P(A)},te=async(_,A,I,q)=>{if(!I.isFile()||I.isSymbolicLink()||!M(n))return;let oe;try{oe=await ce.realpath(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:I.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n)||!O(c,oe)||ii(u,oe))return;if(m.length>=i.maxFiles){P({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){P({path:A,size:I.size,type:"file",reason:"file-size"});return}if(S+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let U,B,ve;try{if(U=await jj(oe,I.size,I,n),U.status==="budget-exhausted"||!M(n))return;if(U.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!M(n)||(ve=await ce.realpath(_),!M(n)))return;B=await ce.lstat(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:I.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(M(n)){if(U.bytes!==I.size||ve!==oe||!Sr(I,U.finalStat)||!Sr(U.finalStat,B)||!B.isFile()||B.isSymbolicLink()||B.size!==I.size||B.mtimeMs!==I.mtimeMs||B.ctimeMs!==I.ctimeMs){P({path:A,size:B.isFile()?B.size:null,type:B.isFile()?"file":"other",reason:"changed-during-read"});return}M(n)&&await Be({path:A,hash:U.hash,size:B.size,type:"file",...q===void 0?{}:{gitObjectId:q}},{kind:"file",target:_,realTarget:oe,stat:B})}},oi=async(_,A,I)=>{if(!M(n))return;let q,oe,U;try{if(q=await ce.readlink(_,{encoding:"buffer"}),!M(n)||(U=await ce.lstat(_),!M(n)))return;oe=await ce.readlink(_,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:null,type:"other",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n))return;if(!U.isSymbolicLink()||!Sr(I,U)||U.mtimeMs!==I.mtimeMs||U.ctimeMs!==I.ctimeMs||!q.equals(oe)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let B=q.byteLength;if(m.length>=i.maxFiles){P({path:A,size:B,type:"other",reason:"file-count"});return}if(B>i.maxFileBytes){P({path:A,size:B,type:"other",reason:"file-size"});return}if(S+B>i.maxTotalBytes){P({path:A,size:B,type:"other",reason:"total-size"});return}let ve=Fl("sha256").update("symlink\0").update(q).digest("hex");M(n)&&await Be({path:A,hash:ve,size:B,type:"file"},{kind:"symlink",target:_,rawTarget:q,stat:U})},Vt=async()=>{for(let[_,A]of[...b]){if(!M(n))return;if(A.kind==="file"){let B,ve;try{if(B=await ce.realpath(A.target),!M(n))return;ve=await ce.lstat(A.target)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"file",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(B!==A.realTarget||!ve.isFile()||ve.isSymbolicLink()||!Sr(A.stat,ve)||ve.size!==A.stat.size||ve.mtimeMs!==A.stat.mtimeMs||ve.ctimeMs!==A.stat.ctimeMs)&&ue(_,{path:_,size:ve.isFile()?ve.size:null,type:ve.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let B,ve;try{if(B=await ce.lstat(A.target),!M(n))return;ve=await ce.readlink(A.target,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"other",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(!B.isSymbolicLink()||!Sr(A.stat,B)||B.mtimeMs!==A.stat.mtimeMs||B.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ve))&&ue(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,q;try{if(I=await ce.realpath(A.target),!M(n))return;q=await ce.lstat(A.target)}catch{if(!M(n))return;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;if(!(I===A.realTarget&&q.isDirectory()&&!q.isSymbolicLink()&&Sr(A.stat,q)&&O(c,I)&&!ii(u,I))){ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let U;try{if(!M(n))return;U=await pN(n,I)}catch(B){if(ua(B))throw B;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;U.dirty?ue(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):U.hash!==A.hash&&ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of g){if(!M(n))return;try{let I=await ce.lstat(A);if(!M(n))return;P({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!M(n))return;if(Ee(I))continue;if(!Pe(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},pt=await PN(n,e,a,t.gitSelectionHooks);if(pt===null){let _=await fN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let q of _.records){if(q.type!=="file"&&q.type!=="symlink"||b.has(q.path))continue;if(ti(n)<1)break;if(!vN(r,q.path,n))continue;if(ti(n)<1)break;let oe=V.resolve(s,...q.path.split("/")),U;try{U=await ce.lstat(oe)}catch(B){if(!M(n))break;if(!Pe(B)&&!Ee(B))throw B;P({path:q.path,size:null,type:"file",reason:Ee(B)?"changed-during-read":"unreadable"});continue}if(ti(n)<1)break;if(q.type==="symlink"&&U.isSymbolicLink()){if(await oi(oe,q.path,U),ti(n)<1)break;continue}if(q.type!=="file"||!U.isFile()||U.isSymbolicLink()){P({path:q.path,size:U.isFile()?U.size:null,type:U.isDirectory()?"directory":U.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await te(oe,q.path,U),ti(n)<1)break}ti(n)>=1&&await Vt();let A=await fN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=Cj(_.evidence,A.evidence);N=I.evidence;for(let q of[..._.omissions,...A.omissions,...I.omissions])p.some(oe=>oe.path===q.path&&oe.reason===q.reason)||P(q)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let x=$i(_);for(let de of x.entries)de.gitObjectId!==void 0&&A.set(de.path,de);I=A.size>0}let q=new Set,oe=!0;try{let x=await Uo(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(x.overflow)I=!1,oe=!1,A.clear();else for(let de of x.records){let ge=Ll(de),Ye=ge.indexOf(" "),Ve=Ye<0?null:da(ge.slice(Ye+1));if(Ye!==1||Ve===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ge[0]!=="H"&&q.add(Ve)}}catch(x){if(ua(x))throw x;I=!1,oe=!1,A.clear()}let U=new Set;try{let x=await Dl(n,s,["ls-files","--modified","-z"],Lh);for(let de of x.toString("utf8").split("\0")){let ge=da(de);ge!==null&&U.add(ge)}}catch{I=!1,oe=!1,A.clear()}let B=new Set,ve=new Set;for(let x of xN(pt)){if(b.has(x)||!Go(e,x))continue;if(ti(n)<1)break;if(!vN(r,x,n))continue;if(ti(n)<1)break;let de=V.resolve(s,...x.split("/"));if(de===f||de===h||ii(d,de)||v.some(mt=>ii(mt,de)))continue;if(pt.gitlinks.has(x)){if(m.length>=i.maxFiles){P({path:x,size:0,type:"file",reason:"file-count"});continue}let mt,Us;try{[mt,Us]=await Promise.all([ce.realpath(de),ce.lstat(de)])}catch{P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Us.isSymbolicLink()||!Us.isDirectory()||!O(c,mt)||ii(u,mt)){P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let _n=await pN(n,mt);if(_n.dirty){P({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await Be({path:x,hash:_n.hash,size:0,type:"file"},{kind:"gitlink",target:de,realTarget:mt,stat:Us,hash:_n.hash})}catch(_n){if(ua(_n))throw _n;P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ge;try{ge=await ce.lstat(de)}catch(mt){if(Ee(mt)&&pt.tracked.has(x)){g.set(x,de);continue}if(!Pe(mt)&&!Ee(mt))throw mt;P({path:x,size:null,type:"file",reason:Ee(mt)?"changed-during-read":"unreadable"});continue}if(ge.isSymbolicLink()){await oi(de,x,ge);continue}if(!ge.isFile()){pt.nestedRepositories.has(x)||P({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let Ye=pt.trackedObjectIds.get(x),Ve=Ye?A.get(x):void 0;if(I&&Ve?.gitObjectId!==void 0&&Ve.gitObjectId===Ye&&!q.has(x)&&!U.has(x)){if(m.length>=i.maxFiles){P({path:x,size:Ve.size,type:"file",reason:"file-count"});continue}if(Ve.size>i.maxFileBytes){P({path:x,size:Ve.size,type:"file",reason:"file-size"});continue}if(S+Ve.size>i.maxTotalBytes){P({path:x,size:Ve.size,type:"file",reason:"total-size"});continue}m.push({...Ve}),S+=Ve.size,B.add(x);continue}let Wm=oe&&!q.has(x)&&!U.has(x)?Ye:void 0;await te(de,x,ge,Wm),Wm!==void 0&&ve.add(x)}if(await Vt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await RN(n,e,a,pt,t.gitSelectionHooks?.outputChunkBytes),B.size>0||I&&ve.size>0){let x=await Dl(n,s,["ls-files","--modified","-z"],Lh),de=new Set;for(let ge of x.toString("utf8").split("\0")){let Ye=da(ge);Ye!==null&&de.add(Ye)}for(let ge of B){if(!de.has(ge))continue;let Ye=m.find(Ve=>Ve.path===ge);ue(ge,{path:ge,size:Ye?.size??null,type:"file",reason:"changed-during-read"})}for(let ge of ve){if(!de.has(ge))continue;let Ye=m.find(Ve=>Ve.path===ge);Ye&&delete Ye.gitObjectId}}for(let x of pt.omissions)P(x);pt.overflow&&F(pt.overflow)}m.sort((_,A)=>_.path.localeCompare(A.path,"en")),p.sort((_,A)=>_.path.localeCompare(A.path,"en"));let gP=pt===null?{provider:"physical-tree",...N?{physicalSelection:N}:{}}:{provider:"git",...pt.evidence?{gitSelection:pt.evidence}:{}},qm=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:gP,createdAt:(t.now??new Date).toISOString(),complete:y===0,limits:i,...r?{policy:r.manifest}:{},entries:m,omitted:p,omittedCount:y,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:E}}:{}}),fd=qm();for(;Wh(fd)>i.maxManifestBytes;){if(p.filter(A=>!Mh(A)).length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let I=0;I<A;I+=1){let q=Ml(p);if(q===null)break;w(q)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I of m.splice(-A))y+=1,$(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");fd=qm()}return fd}async function zh(e,t,i={}){let n=(await ye(e.projectRoot))?.native.snapshot??fh;return ql(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Jh(e,t,i){let r=TN(e,t);await T(j(e,r),r),await ee(r,$i(i))}async function ha(e,t){let i=TN(e,t),r=j(e,i);await T(r,i);try{let n=await xl({root:r,file:i,maxBytes:YI,label:"Native baseline snapshot manifest"});return $i(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as r$}from"crypto";import n$ from"path";var Nt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as Xj}from"node:crypto";import{constants as zl,promises as tt}from"node:fs";import bt from"node:path";import{TextDecoder as Qj}from"node:util";import Gj from"path";var qj=Tn(en(),1);var Qq=4*1024*1024;var Wj=null;function zj(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function IN(e,t){return(...i)=>{let r=Wj;if(r===null)return t(...i);let n=zj(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var rW=IN("hookWritePolicy",async e=>(await sh(e))?.hook??{allow_paths:[]});var jN=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Xo(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Yo(e,t){let i=Xo(e,t);if(Gj.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function Uj(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function $N(e){if(!e.run_id)return null;let t=Xo(e,"run_id"),i=Xo(e,"skill"),r=Xo(e,"skill_version"),n=Xo(e,"skill_hash"),a=Yo(e,"pending_ref"),o=Yo(e,"trajectory_ref"),s=Yo(e,"context_ref"),c=Yo(e,"artifacts_ref"),l=Yo(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:jN(e,"current_step"),iteration:u,pending:jN(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:Uj(e)}}var ZW=256*1024;var Kj=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function Yj(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=$N(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Wl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!Kj.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return Yj(t)}var Je={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Zo(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}function HN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Qo(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Zj(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pr(e,t,i){let r=Nt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=bt.resolve(e),a=bt.resolve(n,...r.slice(8).split("/"));if(!Zo(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function ON(e){let t=await tt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await tt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Gh(e,t){let i=bt.resolve(e),r=bt.resolve(t);if(!Zo(i,r))throw new Error("Native Run path is outside its change");let n=[await ON(i)],a=i;for(let o of bt.relative(i,r).split(bt.sep).filter(Boolean)){a=bt.join(a,o);let s;try{s=await ON(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Zo(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Jl(e){for(let t of e){let i=await tt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Zj(t,i)||await tt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function e$(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function fn(e,t,i,r,n){let a=await Gh(e,bt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await tt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=HN(o),c=await tt.realpath(t);if(!Zo(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?zl.O_RDONLY:zl.O_RDONLY|zl.O_NOFOLLOW|zl.O_NONBLOCK,u;try{u=await tt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Jl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Qo(s,d)||!Qo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await e$(u,i,r);await n?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Jl(a),!p.isFile()||p.isSymbolicLink()||b!==c||!Qo(s,m)||!Qo(s,p))throw new Error(`${r} changed while reading`);let g;try{g=new Qj("utf-8",{fatal:!0}).decode(v)}catch(y){throw new Error(`${r} is not valid UTF-8`,{cause:y})}return{text:g,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function t$(e,t,i){let r=await Gh(e,bt.dirname(t));if(!r)return{exists:!1};let n;try{n=await tt.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await tt.realpath(t);if(!Zo(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Jl(r),{exists:!0,identity:HN(n),realPath:a}}async function i$(e,t,i,r){let n=await Gh(e,bt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await tt.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Qo(i.identity,a)||await tt.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Jl(n)}async function Gl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await t$(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await he(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await i$(e.changeDir,e.file,i,e.label)}});let r=await fn(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function DN(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function LN(e){return`${JSON.stringify(e,null,2)}
|
|
190
|
-
`}function
|
|
191
|
-
`;if(Buffer.byteLength(a,"utf8")>Je.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Je.trajectoryEventBytes} bytes`);let o=await
|
|
192
|
-
`)])}catch(d){if(!
|
|
193
|
-
${t}`).digest("hex")}async function
|
|
189
|
+
${Buffer.byteLength(r)}:${r}`)}function zh(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function ql(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!zh(i))return e.splice(t,1),i}return null}function Pr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Vj(e,t,i,r){if(!M(r))return{status:"budget-exhausted"};let n;try{n=await ce.open(e,"r")}catch(c){if(!M(r))return{status:"budget-exhausted"};throw c}if(!M(r))return await n.close(),{status:"budget-exhausted"};let a=Wl("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!M(r))return{status:"budget-exhausted"};let c=await n.stat();if(!M(r))return{status:"budget-exhausted"};if(!c.isFile()||!Pr(i,c))return{status:"changed"};for(;;){if(!M(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!M(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!M(r))return{status:"budget-exhausted"};let d=await n.stat();return M(r)?!d.isFile()||!Pr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function Tt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jt(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function fa(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function mi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function LN(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=V.posix.normalize(e);if(i!==e||V.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function qj(e,t){let i=Tt(e,`Native snapshot entry ${t}`);jt(i,vj,`Native snapshot entry ${t}`);let r=LN(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!zl.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:mi(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!xN.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function Wj(e,t){let i=Tt(e,`Native snapshot omission ${t}`);if(jt(i,gj,`Native snapshot omission ${t}`),!Nj.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!bj.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:LN(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:mi(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function zj(e){let t=Tt(e,"Native snapshot omission overflow");if(jt(t,wj,"Native snapshot omission overflow"),typeof t.hash!="string"||!zl.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:fa(t.count,"Native snapshot omission overflow count")}}function da(e,t){let i=Tt(e,t);if(jt(i,hj,t),typeof i.hash!="string"||!zl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=mi(i.recordCount,`${t} recordCount`),n=mi(i.storedRecordCount,`${t} storedRecordCount`),a=mi(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function PN(e){let t=Tt(e,"Native Git selection evidence");if(jt(t,fj,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=da(t.stageBefore,"Native Git selection stageBefore"),r=da(t.combined,"Native Git selection combined"),n=da(t.stageAfter,"Native Git selection stageAfter"),a=da(t.finalStageBefore,"Native Git selection finalStageBefore"),o=da(t.finalCombined,"Native Git selection finalCombined"),s=da(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!Rr(i,n)||!Rr(n,a)||!Rr(r,o)||!Rr(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function RN(e,t){let i=Tt(e,t);if(jt(i,mj,t),typeof i.hash!="string"||!zl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=mi(i.visitedNodeCount,`${t} visitedNodeCount`),n=mi(i.recordCount,`${t} recordCount`),a=mi(i.storedRecordCount,`${t} storedRecordCount`),o=mi(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function Jj(e){let t=Tt(e,"Native physical selection evidence");if(jt(t,pj,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=RN(t.before,"Native physical selection before"),r=RN(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!ON(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function $i(e){let t=Tt(e,"Native content snapshot manifest");if(jt(t,sj,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!yj.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let E=Tt(t.capture,"Native content snapshot capture");if(jt(E,uj,"Native content snapshot capture"),E.provider!=="git"&&E.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=E.gitSelection===void 0?void 0:PN(E.gitSelection),y=E.physicalSelection===void 0?void 0:Jj(E.physicalSelection),w=null;if(E.projection!==void 0){let P=Tt(E.projection,"Native content snapshot projection");if(jt(P,dj,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...P.selection===void 0?{}:{selection:PN(P.selection)}}}if(E.provider==="git"){if(y||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(y&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...y?{physicalSelection:y}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=Tt(t.limits,"Native content snapshot limits");jt(r,cj,"Native content snapshot limits");let n={maxFiles:fa(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:fa(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:fa(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:fa(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:fa(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let E=Tt(t.policy,"Native snapshot policy");if(jt(E,lj,"Native snapshot policy"),E.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(E.include)||!Array.isArray(E.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=DN({include:E.include,exclude:E.exclude,hash:E.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(qj),s=t.omitted.map(Wj),c=mi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:zj(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(E=>E.size>n.maxFileBytes)||o.reduce((E,R)=>E+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(E=>E.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Jh||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(E=>E.reason==="git-enumeration-limit"),f=s.filter(E=>E.reason==="git-selection-changed");for(let E of[...d,...f])if(E.path!=="."||E.size!==null||E.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",m=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(m!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let p=s.filter(E=>E.reason==="physical-enumeration-limit"),b=s.filter(E=>E.reason==="physical-selection-changed");for(let E of[...p,...b])if(E.path!=="."||E.size!==null||E.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||b.length>1)throw new Error("Native physical selection omissions must not be duplicated");let g=i?.physicalSelection,S=g?.status==="overflow"||g?.status==="overflow-and-changed",N=g?.status==="changed"||g?.status==="overflow-and-changed";if(S!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(b.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Yh(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function Jl(e,t,i={}){let r=$i(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=V.resolve(e.projectRoot),a=AN(i),o=_N(i.gitSelectionLimits),s=await jN(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(HN(s).filter(y=>Yo(e,y))),l=[...s.gitlinks].filter(y=>c.has(y)),u=[...s.nestedRepositories].filter(y=>Yo(e,y)),d=(y,w)=>w.some(P=>y===P||y.startsWith(`${P}/`)),f=y=>d(y,l),h=y=>d(y,u),v=[...r.entries.map(y=>y.path),...r.omitted.flatMap(y=>y.type==="directory"?[y.path,`${y.path}/`]:[y.path])].filter(y=>!c.has(y)&&!f(y)&&!h(y)),m=await Aj(a,n,v),p=r.entries.filter(y=>!f(y.path)&&!h(y.path)&&Yo(e,y.path)&&(c.has(y.path)||!m.has(y.path)));await $N(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let y of l)b.push({path:y,size:null,type:"directory",reason:"legacy-gitlink-boundary"});p.sort((y,w)=>y.path.localeCompare(w.path,"en"));let g=r.omitted.filter(y=>f(y.path)||h(y.path)||!Yo(e,y.path)?!1:m.has(y.path)?c.has(y.path)||[...c].some(w=>w.startsWith(`${y.path}/`)):!0);for(let y of b)g.some(w=>w.path===y.path&&w.reason===y.reason)||g.push(y);g.sort((y,w)=>y.path.localeCompare(w.path,"en"));let S=r.omissionOverflow?.count??0,N=r.omissionOverflow?.hash??L("comet.native.snapshot-omission-overflow.v1");s.overflow&&(S+=s.overflow.count,N=Qo(N,"git-selection",{source:"git-selection",...s.overflow}));let k=y=>{S+=1,N=Qo(N,"omission",y)};for(;g.length>Jh;){let y=ql(g);if(y===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(y)}let E=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:g.length+S===0,entries:p,omitted:g,omittedCount:g.length+S,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:S}}:{}}),R=E();for(;Yh(R)>r.limits.maxManifestBytes;){let y=ql(g);if(y===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(y),R=E()}return $i(R)}function MN(e,t){if(!oj.test(t))throw new Error(`Invalid Native change name: ${t}`);return V.join(D(e,t),"baseline-manifest.json")}async function Gl(e,t={}){let i={maxFiles:t.limits?.maxFiles??Fl.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Fl.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Fl.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Fl.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=DN(t.policy),n=AN({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=_N(t.gitSelectionLimits),o=Cj(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=V.resolve(e.projectRoot),c=await ce.realpath(s),l=V.resolve(e.nativeRoot),u=await ce.realpath(l),d=V.resolve(e.runtimeDir),f=V.resolve(e.configFile),h=V.join(s,".comet","current-change.json"),v=Lj(s,t.denylist??[]),m=[],p=[],b=new Map,g=new Map,S=0,N=0,k=L("comet.native.snapshot-omission-overflow.v1"),E=0,R=!1,y=null,w=_=>{N+=1,k=Qo(k,"omission",_)},P=_=>{if(S+=1,p.length<Jh){p.push(_);return}if(zh(_)){let A=ql(p);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),p.push(_);return}w(_)},F=_=>{S+=_.count,N+=_.count,k=Qo(k,"git-selection",{source:"git-selection",..._})},$=_=>{N+=1,k=Qo(k,"manifest-entry",{reason:"manifest-size",entry:_})},Be=async(_,A)=>{m.push(_),E+=_.size,b.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},ue=(_,A)=>{let T=m.findIndex(oe=>oe.path===_);if(T<0)return;let[q]=m.splice(T,1);E-=q.size,b.delete(_),P(A)},te=async(_,A,T,q)=>{if(!T.isFile()||T.isSymbolicLink()||!M(n))return;let oe;try{oe=await ce.realpath(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:T.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n)||!O(c,oe)||ri(u,oe))return;if(m.length>=i.maxFiles){P({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){P({path:A,size:T.size,type:"file",reason:"file-size"});return}if(E+T.size>i.maxTotalBytes){P({path:A,size:T.size,type:"file",reason:"total-size"});return}let U,B,ve;try{if(U=await Vj(oe,T.size,T,n),U.status==="budget-exhausted"||!M(n))return;if(U.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!M(n)||(ve=await ce.realpath(_),!M(n)))return;B=await ce.lstat(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:T.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(M(n)){if(U.bytes!==T.size||ve!==oe||!Pr(T,U.finalStat)||!Pr(U.finalStat,B)||!B.isFile()||B.isSymbolicLink()||B.size!==T.size||B.mtimeMs!==T.mtimeMs||B.ctimeMs!==T.ctimeMs){P({path:A,size:B.isFile()?B.size:null,type:B.isFile()?"file":"other",reason:"changed-during-read"});return}M(n)&&await Be({path:A,hash:U.hash,size:B.size,type:"file",...q===void 0?{}:{gitObjectId:q}},{kind:"file",target:_,realTarget:oe,stat:B})}},si=async(_,A,T)=>{if(!M(n))return;let q,oe,U;try{if(q=await ce.readlink(_,{encoding:"buffer"}),!M(n)||(U=await ce.lstat(_),!M(n)))return;oe=await ce.readlink(_,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:null,type:"other",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n))return;if(!U.isSymbolicLink()||!Pr(T,U)||U.mtimeMs!==T.mtimeMs||U.ctimeMs!==T.ctimeMs||!q.equals(oe)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let B=q.byteLength;if(m.length>=i.maxFiles){P({path:A,size:B,type:"other",reason:"file-count"});return}if(B>i.maxFileBytes){P({path:A,size:B,type:"other",reason:"file-size"});return}if(E+B>i.maxTotalBytes){P({path:A,size:B,type:"other",reason:"total-size"});return}let ve=Wl("sha256").update("symlink\0").update(q).digest("hex");M(n)&&await Be({path:A,hash:ve,size:B,type:"file"},{kind:"symlink",target:_,rawTarget:q,stat:U})},qt=async()=>{for(let[_,A]of[...b]){if(!M(n))return;if(A.kind==="file"){let B,ve;try{if(B=await ce.realpath(A.target),!M(n))return;ve=await ce.lstat(A.target)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"file",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(B!==A.realTarget||!ve.isFile()||ve.isSymbolicLink()||!Pr(A.stat,ve)||ve.size!==A.stat.size||ve.mtimeMs!==A.stat.mtimeMs||ve.ctimeMs!==A.stat.ctimeMs)&&ue(_,{path:_,size:ve.isFile()?ve.size:null,type:ve.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let B,ve;try{if(B=await ce.lstat(A.target),!M(n))return;ve=await ce.readlink(A.target,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"other",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(!B.isSymbolicLink()||!Pr(A.stat,B)||B.mtimeMs!==A.stat.mtimeMs||B.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ve))&&ue(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let T,q;try{if(T=await ce.realpath(A.target),!M(n))return;q=await ce.lstat(A.target)}catch{if(!M(n))return;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;if(!(T===A.realTarget&&q.isDirectory()&&!q.isSymbolicLink()&&Pr(A.stat,q)&&O(c,T)&&!ri(u,T))){ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let U;try{if(!M(n))return;U=await kN(n,T)}catch(B){if(ha(B))throw B;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;U.dirty?ue(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):U.hash!==A.hash&&ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of g){if(!M(n))return;try{let T=await ce.lstat(A);if(!M(n))return;P({path:_,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!M(n))return;if(Ee(T))continue;if(!Pe(T))throw T;P({path:_,size:null,type:"file",reason:"unreadable"})}}},pt=await jN(n,e,a,t.gitSelectionHooks);if(pt===null){let _=await NN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let q of _.records){if(q.type!=="file"&&q.type!=="symlink"||b.has(q.path))continue;if(ii(n)<1)break;if(!EN(r,q.path,n))continue;if(ii(n)<1)break;let oe=V.resolve(s,...q.path.split("/")),U;try{U=await ce.lstat(oe)}catch(B){if(!M(n))break;if(!Pe(B)&&!Ee(B))throw B;P({path:q.path,size:null,type:"file",reason:Ee(B)?"changed-during-read":"unreadable"});continue}if(ii(n)<1)break;if(q.type==="symlink"&&U.isSymbolicLink()){if(await si(oe,q.path,U),ii(n)<1)break;continue}if(q.type!=="file"||!U.isFile()||U.isSymbolicLink()){P({path:q.path,size:U.isFile()?U.size:null,type:U.isDirectory()?"directory":U.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await te(oe,q.path,U),ii(n)<1)break}ii(n)>=1&&await qt();let A=await NN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),T=Hj(_.evidence,A.evidence);y=T.evidence;for(let q of[..._.omissions,...A.omissions,...T.omissions])p.some(oe=>oe.path===q.path&&oe.reason===q.reason)||P(q)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,T=!1;if(_){let x=$i(_);for(let de of x.entries)de.gitObjectId!==void 0&&A.set(de.path,de);T=A.size>0}let q=new Set,oe=!0;try{let x=await Xo(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(x.overflow)T=!1,oe=!1,A.clear();else for(let de of x.records){let ge=Vl(de),Ye=ge.indexOf(" "),Ve=Ye<0?null:pa(ge.slice(Ye+1));if(Ye!==1||Ve===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ge[0]!=="H"&&q.add(Ve)}}catch(x){if(ha(x))throw x;T=!1,oe=!1,A.clear()}let U=new Set;try{let x=await Bl(n,s,["ls-files","--modified","-z"],Wh);for(let de of x.toString("utf8").split("\0")){let ge=pa(de);ge!==null&&U.add(ge)}}catch{T=!1,oe=!1,A.clear()}let B=new Set,ve=new Set;for(let x of HN(pt)){if(b.has(x)||!Yo(e,x))continue;if(ii(n)<1)break;if(!EN(r,x,n))continue;if(ii(n)<1)break;let de=V.resolve(s,...x.split("/"));if(de===f||de===h||ri(d,de)||v.some(mt=>ri(mt,de)))continue;if(pt.gitlinks.has(x)){if(m.length>=i.maxFiles){P({path:x,size:0,type:"file",reason:"file-count"});continue}let mt,Qs;try{[mt,Qs]=await Promise.all([ce.realpath(de),ce.lstat(de)])}catch{P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Qs.isSymbolicLink()||!Qs.isDirectory()||!O(c,mt)||ri(u,mt)){P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let jn=await kN(n,mt);if(jn.dirty){P({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await Be({path:x,hash:jn.hash,size:0,type:"file"},{kind:"gitlink",target:de,realTarget:mt,stat:Qs,hash:jn.hash})}catch(jn){if(ha(jn))throw jn;P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ge;try{ge=await ce.lstat(de)}catch(mt){if(Ee(mt)&&pt.tracked.has(x)){g.set(x,de);continue}if(!Pe(mt)&&!Ee(mt))throw mt;P({path:x,size:null,type:"file",reason:Ee(mt)?"changed-during-read":"unreadable"});continue}if(ge.isSymbolicLink()){await si(de,x,ge);continue}if(!ge.isFile()){pt.nestedRepositories.has(x)||P({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let Ye=pt.trackedObjectIds.get(x),Ve=Ye?A.get(x):void 0;if(T&&Ve?.gitObjectId!==void 0&&Ve.gitObjectId===Ye&&!q.has(x)&&!U.has(x)){if(m.length>=i.maxFiles){P({path:x,size:Ve.size,type:"file",reason:"file-count"});continue}if(Ve.size>i.maxFileBytes){P({path:x,size:Ve.size,type:"file",reason:"file-size"});continue}if(E+Ve.size>i.maxTotalBytes){P({path:x,size:Ve.size,type:"file",reason:"total-size"});continue}m.push({...Ve}),E+=Ve.size,B.add(x);continue}let Xm=oe&&!q.has(x)&&!U.has(x)?Ye:void 0;await te(de,x,ge,Xm),Xm!==void 0&&ve.add(x)}if(await qt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await $N(n,e,a,pt,t.gitSelectionHooks?.outputChunkBytes),B.size>0||T&&ve.size>0){let x=await Bl(n,s,["ls-files","--modified","-z"],Wh),de=new Set;for(let ge of x.toString("utf8").split("\0")){let Ye=pa(ge);Ye!==null&&de.add(Ye)}for(let ge of B){if(!de.has(ge))continue;let Ye=m.find(Ve=>Ve.path===ge);ue(ge,{path:ge,size:Ye?.size??null,type:"file",reason:"changed-during-read"})}for(let ge of ve){if(!de.has(ge))continue;let Ye=m.find(Ve=>Ve.path===ge);Ye&&delete Ye.gitObjectId}}for(let x of pt.omissions)P(x);pt.overflow&&F(pt.overflow)}m.sort((_,A)=>_.path.localeCompare(A.path,"en")),p.sort((_,A)=>_.path.localeCompare(A.path,"en"));let CP=pt===null?{provider:"physical-tree",...y?{physicalSelection:y}:{}}:{provider:"git",...pt.evidence?{gitSelection:pt.evidence}:{}},Ym=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:CP,createdAt:(t.now??new Date).toISOString(),complete:S===0,limits:i,...r?{policy:r.manifest}:{},entries:m,omitted:p,omittedCount:S,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:N}}:{}}),wd=Ym();for(;Yh(wd)>i.maxManifestBytes;){if(p.filter(A=>!zh(A)).length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let T=0;T<A;T+=1){let q=ql(p);if(q===null)break;w(q)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))S+=1,$(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");wd=Ym()}return wd}async function Xh(e,t,i={}){let n=(await ye(e.projectRoot))?.native.snapshot??wh;return Gl(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Qh(e,t,i){let r=MN(e,t);await I(j(e,r),r),await ee(r,$i(i))}async function va(e,t){let i=MN(e,t),r=j(e,i);await I(r,i);try{let n=await Tl({root:r,file:i,maxBytes:aj,label:"Native baseline snapshot manifest"});return $i(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as f$}from"crypto";import h$ from"path";var Nt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as o$}from"node:crypto";import{constants as Kl,promises as tt}from"node:fs";import bt from"node:path";import{TextDecoder as s$}from"node:util";import i$ from"path";var Qj=$n(nn(),1);var wW=4*1024*1024;var Zj=null;function e$(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function FN(e,t){return(...i)=>{let r=Zj;if(r===null)return t(...i);let n=e$(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var SW=FN("hookWritePolicy",async e=>(await hh(e))?.hook??{allow_paths:[]});var BN=(e,t)=>{let i=e[t];return i==null?null:String(i)};function es(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Zo(e,t){let i=es(e,t);if(i$.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function r$(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function VN(e){if(!e.run_id)return null;let t=es(e,"run_id"),i=es(e,"skill"),r=es(e,"skill_version"),n=es(e,"skill_hash"),a=Zo(e,"pending_ref"),o=Zo(e,"trajectory_ref"),s=Zo(e,"context_ref"),c=Zo(e,"artifacts_ref"),l=Zo(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:BN(e,"current_step"),iteration:u,pending:BN(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:r$(e)}}var y2=256*1024;var n$=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function a$(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=VN(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Ul(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!n$.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return a$(t)}var Je={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function is(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}function WN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ts(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function c$(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Cr(e,t,i){let r=Nt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=bt.resolve(e),a=bt.resolve(n,...r.slice(8).split("/"));if(!is(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function qN(e){let t=await tt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await tt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Zh(e,t){let i=bt.resolve(e),r=bt.resolve(t);if(!is(i,r))throw new Error("Native Run path is outside its change");let n=[await qN(i)],a=i;for(let o of bt.relative(i,r).split(bt.sep).filter(Boolean)){a=bt.join(a,o);let s;try{s=await qN(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!is(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Yl(e){for(let t of e){let i=await tt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!c$(t,i)||await tt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function l$(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function mn(e,t,i,r,n){let a=await Zh(e,bt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await tt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=WN(o),c=await tt.realpath(t);if(!is(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Kl.O_RDONLY:Kl.O_RDONLY|Kl.O_NOFOLLOW|Kl.O_NONBLOCK,u;try{u=await tt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Yl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!ts(s,d)||!ts(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await l$(u,i,r);await n?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Yl(a),!p.isFile()||p.isSymbolicLink()||b!==c||!ts(s,m)||!ts(s,p))throw new Error(`${r} changed while reading`);let g;try{g=new s$("utf-8",{fatal:!0}).decode(v)}catch(S){throw new Error(`${r} is not valid UTF-8`,{cause:S})}return{text:g,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function u$(e,t,i){let r=await Zh(e,bt.dirname(t));if(!r)return{exists:!1};let n;try{n=await tt.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await tt.realpath(t);if(!is(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Yl(r),{exists:!0,identity:WN(n),realPath:a}}async function d$(e,t,i,r){let n=await Zh(e,bt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await tt.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!ts(i.identity,a)||await tt.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Yl(n)}async function Xl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await u$(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await he(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await d$(e.changeDir,e.file,i,e.label)}});let r=await mn(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function zN(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function JN(e){return`${JSON.stringify(e,null,2)}
|
|
190
|
+
`}function xr(e){return Ul(e)}async function Oe(e,t){let i=Cr(e,"stateRef"),r=await mn(e,i,Je.runStateBytes,"Native Run state",t);return r?Ul(zN(r.text,"Native Run state")):null}async function vn(e,t,i){let r=Ul(t);await Xl({changeDir:e,file:Cr(e,"stateRef"),content:JN(r),maxBytes:Je.runStateBytes,label:"Native Run state",hooks:i})}async function it(e,t,i){let r=Cr(e,"trajectoryRef",t),n=await mn(e,r,Je.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Je.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Je.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function GN(e,t,i){return(await mn(e,Cr(e,"trajectoryRef",t),Je.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function UN(e,t,i,r,n){if(!/^[a-f0-9]{64}$/u.test(r))throw new Error("Native Run trajectory expected hash is invalid");let a=Cr(e,"trajectoryRef",t),o=await mn(e,a,Je.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(o$("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await Xl({changeDir:e,file:a,content:i,maxBytes:Je.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function KN(e,t,i,r){let n=Cr(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
|
|
191
|
+
`;if(Buffer.byteLength(a,"utf8")>Je.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Je.trajectoryEventBytes} bytes`);let o=await mn(e,n,Je.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Je.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Je.trajectoryEvents} events`);await Xl({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:Je.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function ga(e,t,i){let r=await mn(e,Cr(e,"checkpointRef",t),Je.checkpointBytes,"Native Run checkpoint",i);return r?zN(r.text,"Native Run checkpoint"):null}async function YN(e,t,i,r){await Xl({changeDir:e,file:Cr(e,"checkpointRef",t),content:JN(i),maxBytes:Je.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var p$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ql=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function ep(e){return f$("sha256").update(e).digest("hex")}function m$(e,t){if(!p$.test(t))throw new Error(`Invalid Native change name: ${t}`);return h$.join(D(e,t),"trajectory.jsonl")}function v$(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function g$(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function w$(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=v$(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
|
|
192
|
+
`)])}catch(d){if(!g$(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:ep(t),targetHash:ep(l),tailHash:ep(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function XN(e,t){let i=m$(e,t);await I(j(e,i),i);let r=D(e,t),n=await GN(r,Nt.trajectoryRef);return n===null?{status:"clean",file:i}:w$(i,Buffer.from(n))}async function wa(e,t){let i=await XN(e,t);return"inspection"in i?i.inspection:i}async function Zl(e,t){let i=await wa(e,t);if(i.status!=="clean")throw new Ql(i)}async function QN(e,t,i){return se(e,`repair trajectory tail for ${t}`,async()=>{let r=await XN(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new Ql(r)}try{await UN(D(e,t),Nt.trajectoryRef,r.targetContent,r.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await wa(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return r.inspection})}import{createHash as y$}from"node:crypto";import{promises as eu}from"node:fs";import Oi from"node:path";var rs=/^[a-f0-9]{64}$/u,ZN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,N$=16*1024,ip=process.platform,b$=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function ya(e){return b$.has(e)}function ib(e,t){let i=Oi.relative(e,t);return Oi.isAbsolute(i)||i===".."||i.startsWith(`..${Oi.sep}`)?null:i.replaceAll("\\","/")||"."}function rb(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function nb(e,t){if(e.length===0||rb(e)||e.includes("\\")||Oi.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Oi.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function rp(e,t){return y$("sha256").update(`${e}
|
|
193
|
+
${t}`).digest("hex")}async function eb(e,t){let i=await eu.realpath(t),r=await eu.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=ip==="win32"?Oi.normalize(i).toLowerCase():i;return rp(e,`${n}
|
|
194
194
|
${r.dev}
|
|
195
195
|
${r.ino}
|
|
196
|
-
${r.birthtimeMs}`)}async function
|
|
196
|
+
${r.birthtimeMs}`)}async function tb(e,t){let i=await eu.realpath(t),r=await eu.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=ip==="win32"?Oi.normalize(i).toLowerCase():i;return rp(e,n)}function k$(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 tp(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||rb(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function ab(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(tp(e.changeBranch,"Native workspace change branch"),tp(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 S$(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!ZN.test(t.baseCommit)||typeof t.targetCommit!="string"||!ZN.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");tp(t.targetBranch,"Native workspace Git target branch")}function ns(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!rs.test(String(t.projectRootId))||!rs.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");k$(t.capturedAt),nb(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&&!rs.test(String(t.projectRootPathId))||a&&!rs.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!rs.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&S$(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(ab(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 Na(e,t){return Oi.join(D(e,t),"workspace.json")}function E$(e,t){let i=Na(e,t),r=j(e,i),n=ib(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:nb(n,"Native workspace file ref")}}async function ob(e,t){try{let i=E$(e,t),r=await Z({root:i.root,ref:i.ref,maxBytes:N$});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function sb(e,t){let i=fe(e.projectRoot),r={projectRoot:Oi.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await kt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await ba({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function np(e,t){let i=await ob(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(ns(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function cb(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=ib(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=fe(e.paths.projectRoot),r=i.isGitWorktree?Ai(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:Ai(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([eb("comet.native.workspace-project-root.v2",e.paths.projectRoot),eb("comet.native.workspace-native-root.v2",e.paths.nativeRoot),tb("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),tb("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&ab(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:rp("comet.native.workspace-session.v2",`${s}
|
|
197
197
|
${c}
|
|
198
|
-
${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return ts(h),h}async function Xl(e){let t=await eb(e),i=ga(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await ee(i,t,{containedRoot:r}),t}async function kt(e,t){let i=await QN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(ts(i),i)}async function tb(e){return await Qh(e.paths,e.name)?Xl(e):null}async function is(e){ts(e.identity);let t=await eb({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Yh==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function wa(e){if(ts(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await is(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=fe(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function ib(e,t){let i=await kt(e,t);if(i===null)return null;let r=await wa({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var nb=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],v$=new Set(nb),ab=new Set([...nb,"minimum_runtime_version","revision"]),g$=new Set([...ab,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),w$=new Set(["capability","operation","source","base_hash"]),y$=new Set(["shape","build","verify","archive"]),N$=new Set(["implicit","confirmed"]),b$=new Set(["pending","pass","fail"]),Ie="comet-state.yaml",ep=/^[a-f0-9]{64}$/u,ob=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,k$=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,rs=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},mn=class extends Error{constructor(i,r){super(i!==Ne||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},ns=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},as=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},ya=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},G2=Xs("en");function ss(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function sb(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Zl(e){if(!ob.test(e))throw new Error(`Invalid Native change name: ${e}`)}function S$(e){if(!ob.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function cb(e,t){if(e.length===0||mi.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function E$(e,t){let i=ss(e,`spec_changes[${t}]`);if(sb(i,w$,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(S$(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&cb(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!ep.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!ep.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function P$(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 tp(e,t){if(sb(e,t,Ie),typeof e.name!="string")throw new Error("Native change name is required");if(Zl(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"||!y$.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&&!N$.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(E$),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!b$.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"&&cb(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!P$(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function ln(e){let t=ss(e,Ie);if(t.schema!==et)throw new Error(`Expected ${et}`);return{schema:et,...tp(t,v$)}}function os(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Zh(e,t,i){if(e===null)return null;let r=typeof e=="string"?k$.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function R$(e){if(e==null)return null;if(typeof e!="string"||!ep.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function C$(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 di(e){let t=ss(e,Ie);if(t.schema!==be)throw new Error(`Expected ${be}`);if(os(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${be} minimum_runtime_version must be 2`);return{schema:be,minimum_runtime_version:2,revision:os(t.revision,"Native v2 revision"),...tp(t,ab)}}function lt(e){let t=ss(e,Ie);if(t.schema!==Ne){if(t.schema===et||t.schema===be){let o=t.schema===et?ln(t):di(t);throw new rs(o.name,o.schema)}throw new mn(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=os(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new mn(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=os(t.revision,"Native revision"),n=tp(t,g$),a=R$(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ne,minimum_runtime_version:3,revision:r,verification_protocol:C$(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Zh(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Zh(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Zh(t.partial_allowance,"Native partial_allowance","allowances")}}function lb(e){let t=ss(e,Ie);if(t.schema===et){let n=ln(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema===be){let n=di(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema!==Ne){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 mn(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=os(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new mn(t.schema,i).message};let r=lt(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function pn(e){let t=lt(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function eu(e){let t=di(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function ne(e,t){Zl(t);let i=mi.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Na(e,t){let i=H(e,t),r=mi.join(i,"schema-migration.json");await T(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await rb.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function ba(e,t){let i=H(e,t),r=mi.join(i,"checkpoint-journal.json");await T(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await rb.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function tu(e,t=mi.dirname(e)){let i=mi.relative(t,e).split(mi.sep).join("/"),r=await Z({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,Ql.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function vi(e,t){let i=mi.join(ne(e,t),Ie);await T(e.nativeRoot,i);let r=lb(await tu(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Na(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await x$(e,r.state),r)}async function iu(e,t){let i=mi.join(ne(e,t),Ie);await T(e.nativeRoot,i);let r=lb(await tu(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function x$(e,t){if(await ha(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function De(e,t){let i=await vi(e,t);if(i.status==="migration-required")throw new rs(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new mn(i.schema,i.minimumRuntimeVersion);return await ib(e,t),i.state}async function ub(e,t,i){let r={...t,schema:Ne,minimum_runtime_version:3,revision:i+1},n=await lN({expectedRevision:i,next:r,read:async()=>{let a=lt(await tu(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>he(e,(0,Ql.stringify)(pn(a))),equals:(a,o)=>JSON.stringify(pn(a))===JSON.stringify(pn(o)),conflict:a=>new ns(t.name,i,a)});return Object.assign(t,n),n}async function ru(e,t,i,r){if(await Yn(e.projectRoot),await Na(e,t.name))throw new rs(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await ba(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await De(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Kl(e,t.name);let a=mi.join(ne(e,t.name),Ie);return await T(e.nativeRoot,a),ub(a,t,i)}async function db(e,t){return ub(e,t,t.revision)}async function fb(e){return lt(await tu(e))}var pb=["outcome","scope","nonGoals","acceptanceExamples"],A$=[...pb,"constraints","decisions","openQuestions","verificationExpectations"],_$=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],mb={maxFileBytes:xo};function vb(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
|
|
199
|
-
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function T$(e,t){let i=hb.resolve(e,...t.split(/[\\/]/u));if(!O(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await ip.realpath(e),n=await ip.realpath(i);if(!O(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await ip.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function cs(e){return{valid:e.length===0,findings:e}}async function rp(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:mb.maxFileBytes})).text}catch(o){return cs([{code:"brief-missing",message:o.message,path:t}])}let n=new Map;for(let[o,s]of vb(r))n.set(Ys(o)??o,s);for(let o of A$)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of pb)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("openQuestions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),cs(i)}async function np(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:mb.maxFileBytes})).text}catch(a){return cs([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of vb(r))n.set(ev(a)??a,o);for(let a of _$)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return cs(i)}function nu(e,t){return hb.join(e.specsDir,t,"spec.md")}async function gb(e,t){let i=[],r=ne(e,t.name);for(let n of t.spec_changes){let a=nu(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await ei(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await T$(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return cs(i)}import{promises as DH}from"node:fs";import eS from"node:path";import wb from"node:path";var I$="comet.native.archive-preflight.v1",j$="comet.native.archive-preflight.v1",$$="comet.native.archive-operation.v1",O$=/^[a-f0-9]{64}$/u,yb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,H$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function au(e,t){return e<t?-1:e>t?1:0}function D$(e,t){if(typeof e!="string"||!O$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Hi(e,t){return e===null?null:D$(e,t)}function L$(e,t){let i=wb.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||wb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function M$(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function F$(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function B$(e,t){if(!yb.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Hi(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Hi(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Hi(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function V$(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Hi(e.contractHash,"Native archive contract hash"),acceptanceHash:Hi(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Hi(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Hi(e.reportHash,"Native archive report hash"),envelopeHash:Hi(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Hi(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function q$(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!H$.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(au);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function W$(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(au)}function Nb(e){if(!yb.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(B$).sort((l,u)=>au(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:D($$,l)})),r=V$(e.evidence),n=F$(e.workspace),a=[...new Set([...q$(e.findingCodes??[]),...W$({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(au),o=M$(e.revision),s=L$(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:I$,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:D(j$,c)}}import{createHash as z$}from"node:crypto";import bb from"node:path";var J$="comet.native.conflict-radar.v1",ut=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}),G$="comet.native.conflict-radar.v1",U$="comet.native.conflict-radar-signals.v1",K$=/^[a-f0-9]{64}$/u,Eb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Y$=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),X$=new Set(["capability","operation","baseHash"]),Q$=new Set(["path","kind"]);function ka(e,t){return e<t?-1:e>t?1:0}function ap(e){return Buffer.byteLength(e,"utf8")}function op(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function sp(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(ap(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function Z$(e,t){let i=sp(e,t,ut.maxArtifactPathBytes),r=bb.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||bb.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Pb(e,t){if(typeof e!="string"||!K$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function eO(e,t){let i=op(e,X$,t),r=sp(i.capability,`${t} capability`,ut.maxCapabilityBytes);if(!Eb.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:Pb(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function tO(e,t){let i=op(e,Q$,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:Z$(i.path,`${t} path`),kind:i.kind}}function iO(e,t){let i=op(e,Y$,`Conflict radar change ${t}`),r=sp(i.name,`Conflict radar change ${t} name`,ut.maxNameBytes);if(!Eb.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>ut.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>ut.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>eO(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>ka(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>tO(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>ka(c.path,l.path)||ka(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:Pb(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function rO(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ut.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(iO).sort((n,a)=>ka(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>ut.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ut.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function nO(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function aO(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function oO(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function sO(e,t){let i=[],r=z$("sha256").update(`${U$}
|
|
200
|
-
[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(
|
|
201
|
-
`,"utf8")}function
|
|
202
|
-
${
|
|
203
|
-
`),e.omissionOverflow&&
|
|
204
|
-
`);let i=0;hp(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){Cr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)hs(o,n.path)&&(a+=1,Cr(t,"change-attribution",o));Cr(t,"change-end",{attributionCount:a}),a===0&&Cr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&Cr(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function qb(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=SO(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),N=new Set(o.changePaths),w=i.externalDrift.paths.filter(P=>!N.has(P)||n.some(F=>hs(F,P)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=D(ls,e),c=D(ls,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,N]of[["baseline",e],["current",t]])for(let w of N.omitted){if(l.length>=hO)break;l.push(Di({kind:"snapshot-omission",source:R,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${R} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...Ab("baseline",e),...Ab("current",t),...o.totalChanges===0&&a===null?[Di({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(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(N=>R.has(N)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(N=>!R.has(N))}},v=R=>{let N=o.candidates.slice(0,R.detailedChangeCount),w=N.filter(Vt=>Vt.attributedTo.length===0&&!u.has(Vt.path)),P=o.totalChanges-N.length,F=o.totalUnattributed-w.length,$=d-R.detailedOmissionCount,Be=F+$,ue=[...w.map(Vt=>Di({kind:"unattributed-change",source:"implementation-scope",path:Vt.path,evidence:{after:Vt.after,before:Vt.before,changeKind:Vt.kind}},`Changed path is not covered by a declared artifact: ${Vt.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...Be>0?[Vb(R.overflowHash,{changes:P,unattributed:F,unresolved:Be})]:[]],te=bO(ue),oi=R.includeGitAdvisory?h():void 0;return{schema:cp,contractHash:r,baselineProjectionRef:lp(s),baselineProjectionHash:s,currentProjectionRef:lp(c),currentProjectionHash:c,complete:te.length===0,declaredArtifacts:n,changes:N,unattributed:w,unresolvedScopes:te,noCodeReason:a,...oi?{gitAdvisory:oi}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},m=o.candidates.length,p=l.length,b=i.gitChangedPaths!==void 0,g="0".repeat(64);for(;;){let R=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:g});if(ds({...R,scopeHash:g})<=gn)break;if(b){b=!1;continue}if(p>0){p-=Math.max(1,Math.ceil(p/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 E=o.totalChanges>m||d>p?PO({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:m,detailedOmissionCount:p}):g,k=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:E}),S={...k,scopeHash:D(Hb,k)};if(ds(S)>gn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return S}function mp(e){let t=up(e.baseline),i=up(e.current),r=Bb(e);return{authority:r,baseline:t,current:i,scope:qb(t,i,r)}}var RO=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function gi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function wi(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function vn(e,t){if(typeof e!="string"||!fp.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Tb(e,t,i){let r=lp(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function Ea(e,t){let i=gi(e,"Native snapshot projection");if(wi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Ob)throw new Error("Native snapshot projection schema is invalid");let r=$i({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=up(r);if(D(ls,i)!==D(ls,n))throw new Error("Native snapshot projection is not canonical");let a=D(ls,n);if(t!==void 0&&vn(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function vp(e,t){let i=gi(e,`Declared artifact ${t}`);if(wi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:xr(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Ib(e,t){if(e===null)return null;let i=gi(e,t);return wi(i,["hash","size"],[],t),{hash:vn(i.hash,`${t} hash`),size:Sa(i.size,`${t} size`)}}function jb(e,t){let i=gi(e,`Implementation change ${t}`);if(wi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(vp),n=fs(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Ib(i.before,`Implementation change ${t} before`),o=Ib(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:xr(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function CO(e,t){let i=gi(e,`Unresolved scope ${t}`);wi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Db(i.path,`Unresolved scope ${t} path`):xr(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function us(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>xr(n,`${t} ${a}`)),r=[...new Set(i)].sort(Ge);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function Wb(e){let t=gi(e,"Native implementation external drift");if(wi(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=us(t.paths,"Native external drift paths");return Fb({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function Pa(e){let t=gi(e,"Native implementation scope"),i=[...RO].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(wi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==cp)throw new Error("Native implementation scope schema is invalid");let r=vn(t.contractHash,"Implementation scope contractHash"),n=vn(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Tb(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=vn(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Tb(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(vp);if(JSON.stringify(c)!==JSON.stringify(fs(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(jb),u=[...l].sort((w,P)=>Ge(w.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(P=>hs(P,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(jb),h=t.externalDrift===void 0?void 0:Wb(t.externalDrift),v=new Set(h?.paths??[]),m=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(m))throw new Error("Implementation scope unattributed changes are inconsistent");let p=t.unresolvedScopes.map(CO),b=p.filter(w=>w.kind==="scope-detail-overflow");if(b.length>1)throw new Error("Implementation scope has multiple detail overflow records");let g=b[0]===void 0?null:EO(b[0]);if(g&&(g.changes+g.unresolved===0||g.unattributed>g.changes||g.unattributed>g.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let y=t.noCodeReason,E=[...m.map(w=>Di({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(g?.changes??0)===0&&y===null?[Di({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")]:[]],k=p.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(p)!==JSON.stringify([...p].sort(dp))||new Set(p.map(w=>w.id)).size!==p.length||JSON.stringify(k)!==JSON.stringify(E.sort(dp))||t.complete!==(p.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 S;if(t.gitAdvisory!==void 0){let w=gi(t.gitAdvisory,"Implementation scope Git advisory");if(wi(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=us(w.changedPaths,"Git changed paths"),F=us(w.pathsPresentInSnapshotChanges,"Git present paths"),$=us(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),Be=[...F,...$].sort(Ge);if(JSON.stringify(Be)!==JSON.stringify(P)||$.some(ue=>l.some(te=>te.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");S={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:F,pathsAbsentFromSnapshotChanges:$}}let R={schema:cp,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:p,noCodeReason:y,...S?{gitAdvisory:S}:{},...h?{externalDrift:h}:{}},N=vn(t.scopeHash,"Implementation scope scopeHash");if(D(Hb,R)!==N)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:N}}function xO(e){let t=gi(e,"Native implementation scope authority");if(wi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(vp);if(JSON.stringify(i)!==JSON.stringify(fs(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=us(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:Wb(t.externalDrift),a=Bb({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function ps(e){let t=gi(e,"Native implementation scope bundle");wi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=xO(t.authority),r=Ea(t.baseline),n=Ea(t.current),a=Pa(t.scope),o=qb(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function zb(e){let t=Pa(e.scope);return ps({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})}import Jb from"node:path";var AO=/\b(Bearer|Basic)\s+[^\s"']+/giu,_O=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,TO=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,IO=/\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,jO=/("(?:[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,$O=/(["'])((?:[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,OO=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function $t(e){return e.replace(AO,"$1 [REDACTED]").replace(_O,"[REDACTED PRIVATE KEY]").replace(TO,"$1[REDACTED]@").replace(IO,"[REDACTED TOKEN]").replace(jO,'$1"[REDACTED]"').replace($O,"$1$2$1$3$4[REDACTED]$4").replace(OO,"$1$2[REDACTED]")}var Ub=/^[a-f0-9]{64}$/u;var HO="comet.native.acceptance-trace.v2",DO="comet.native.partial-allowance.v1",LO="comet.native.verification-evidence.v2";function Li(e,t){if(!Ub.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Kb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Yb(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 gp(e,t,i=2e3){let r=$t(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function ms(e,t){let i=Jb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Jb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function MO(e,t,i){let r=ms(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=li(r),a=r.toLowerCase(),o=i?ms(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function wp(e){let t=ms(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 Ra(e,t){return e<t?-1:e>t?1:0}function ou(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function su(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Xb(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Gb(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function FO(e){let t=ou(e,"Native acceptance trace");if(su(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"||!Ub.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=ms(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=ou(o,`Native acceptance trace entry ${s}`);if(su(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=>wp(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ra))||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:ms(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:gp(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>Ra(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Li(t.traceHash,"Native acceptance trace hash");if(D(HO,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function cu(e){let t=ou(e,"Native partial allowance");if(su(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(Ra))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:Yb(t.change),scopeHash:Li(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:gp(t.reason,"Partial allowance reason"),confirmedSummary:gp(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Kb(t.sourceRevision),confirmedAt:Xb(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Li(t.allowanceHash,"Native partial allowance hash");if(D(DO,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function vs(e){let t=ou(e,"Native verification evidence");if(su(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Li(t.implementationScopeHash,"Native verification implementation scope hash"),r=FO(t.acceptanceTrace),n=Li(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Li(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>wp(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Ra)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(Ra);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>wp(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ra)))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:Yb(t.change),sourceRevision:Kb(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Li(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Gb(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:MO(t.reportRef,"Native verification report ref"),reportHash:Li(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:Gb(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Xb(t.createdAt,"Native verification timestamp")},d=Li(t.envelopeHash,"Native verification envelope hash");if(D(LO,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import Qb from"node:path";var Zb="comet.native.check-receipt.v1",BO="comet.native.check-receipt.v1",Ca="scoped-text-safety",yp=1,dt=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),VO=/^[a-f0-9]{64}$/u,qO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WO="comet.native.checker-policy.v1",zO="comet.native.check-input.v1",JO=2048,ek=D(WO,{policy:Ca,version:yp,limits:dt,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),GO=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),tk=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],rk=["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"],UO=new Set(rk);function Ar(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _r(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Mi(e,t){if(typeof e!="string"||!VO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function St(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function nk(e,t){let i=St(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function ik(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function KO(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>JO||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=Qb.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Qb.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function YO(e){let t=Ar(e,"Native check receipt checker");_r(t,["policy","version","hash","limits"],"Native check receipt checker");let i=Ar(t.limits,"Native check receipt limits");if(_r(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Ca||t.version!==yp||t.hash!==ek||i.maxFiles!==dt.maxFiles||i.maxFileBytes!==dt.maxFileBytes||i.maxTotalBytes!==dt.maxTotalBytes||i.maxIssues!==dt.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Ca,version:yp,hash:ek,limits:{...dt}}}function XO(e){let t=Ar(e,"Native check receipt contract");return _r(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Mi(t.expectedHash,"Native check expected contract hash"),beforeHash:Mi(t.beforeHash,"Native check before contract hash"),afterHash:Mi(t.afterHash,"Native check after contract hash")}}function QO(e){let t=Ar(e,"Native check receipt implementation");return _r(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Mi(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Mi(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Mi(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Mi(t.afterSnapshotHash,"Native check after snapshot hash")}}function ZO(e,t){let i=Ar(e,`Native check batch ${t}`);_r(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:St(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:St(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:St(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:St(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:St(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:St(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>dt.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>dt.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function e0(e){let t=Ar(e,"Native check receipt counts");_r(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:St(t.filesSelected,"Native check filesSelected"),filesScanned:St(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:St(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:St(t.bytesScanned,"Native check bytesScanned"),issueCount:St(t.issueCount,"Native check issueCount"),recordedIssueCount:St(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(ZO):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>dt.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>dt.maxFiles||i.bytesScanned>dt.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function t0(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||tk.indexOf(e.kind)-tk.indexOf(t.kind)}function i0(e){if(!Array.isArray(e)||e.length>dt.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=Ar(r,`Native check issue ${n}`);if(_r(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!GO.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:KO(a.path,`Native check issue ${n} path`),line:nk(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(t0);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function r0(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!UO.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=rk.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function n0(e){return D(zO,e)}function lu(e){let t=Ar(e,"Native check receipt");if(_r(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Zb)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!qO.test(t.change))throw new Error("Native check receipt change name is invalid");let i=nk(t.sourceRevision,"Native check source revision"),r=YO(t.checker),n=XO(t.contract),a=QO(t.implementation),o=n0({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Mi(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=ik(t.startedAt,"Native check receipt startedAt"),c=ik(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=e0(t.counts),u=i0(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=r0(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>dt.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>dt.maxFiles&&!u.some(m=>m.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:Zb,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Mi(t.receiptHash,"Native check receipt content hash");if(D(BO,h)!==v)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:v}}var bp="comet.native.verification-receipt.v3",a0=bp,o0="comet.native.declared-artifacts.v1",s0=/^[a-f0-9]{64}$/u,c0=/^acceptance-[a-f0-9]{64}$/u,l0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,u0=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,d0=4096,f0=256,h0=1024;function xa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Tr(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Fi(e,t){if(typeof e!="string"||!s0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ri(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=$t(e).trim();if(!i||i.length>d0||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Np(e,t){let i=ri(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function gs(e,t,i=ri,r=!1,n=f0){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function p0(e,t){if(typeof e!="string"||!c0.test(e))throw new Error(`${t} is invalid`);return e}function m0(e){let t=xa(e,"Native verification receipt bindings");if(Tr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!l0.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:Fi(t.contractHash,"Native verification receipt contract hash"),scopeHash:Fi(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Fi(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Fi(t.artifactHash,"Native verification receipt artifact hash")}}function v0(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=u0.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function g0(e,t,i,r){let n=xa(t,`Native ${e} evidence`);if(e==="automated-check"){if(Tr(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=Np(n.startedAt,"Native automated-check start time"),o=Np(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=xa(n.worktree,"Native automated-check worktree");if(Tr(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=xa(n.afterFence,"Native automated-check after fence");if(Tr(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:ri(n.executable,"Native automated-check executable"),args:gs(n.args,"Native automated-check arguments",ri,!0),cwd:ri(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:ri(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Fi(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Fi(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Fi(n.outputHash,"Native automated-check output hash"),outputSummary:ri(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){Tr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=v0(n.checkReceiptRef);if(Fi(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:gs(n.subjects,"Native static inspection subjects",ri,r==="required-check"),rule:ri(n.rule,"Native static inspection rule"),resultSummary:ri(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Tr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:gs(n.steps,"Native manual evidence steps"),observations:gs(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function w0(e){let t=xa(e,"Native verification receipt");if(Tr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=ri(t.actor,"Native verification receipt actor"),o=gs(t.acceptanceIds,"Native receipt acceptance IDs",p0,r==="required-check",h0).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:bp,kind:i,role:r,status:n,bindings:m0(t.bindings),acceptanceIds:o,actor:a,issuedAt:Np(t.issuedAt,"Native verification receipt issue time"),evidence:g0(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Ca||s.actor!==`native-runtime:${Ca}`))throw new Error("Native required check policy identity is invalid");return s}function uu(e){let t=xa(e,"Native verification receipt");if(Tr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==bp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=w0(r),a=Fi(t.receiptHash,"Native verification receipt hash");if(D(a0,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function kp(e){return D(o0,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var ck=/^[a-f0-9]{64}$/u,Ir=gn,Lz=3*Ir;function Sp(e,t){let i=yi.relative(e,t);return i===""||!yi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${yi.sep}`)}function N0(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function du(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ak(e){let t=await ni.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ni.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function b0(e,t){let i=yi.resolve(e),r=yi.resolve(t);if(!Sp(i,r))throw new Error("Native evidence path is outside its change");let n=[await ak(i)],a=i;for(let o of yi.relative(i,r).split(yi.sep).filter(Boolean)){a=yi.join(a,o);let s=await ak(a);if(!Sp(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function ok(e){for(let t of e){let i=await ni.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!N0(t,i)||await ni.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function k0(e,t,i={}){let r=await b0(t,yi.dirname(e));await i.afterParentChainCaptured?.();let n=await ni.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ni.realpath(e);if(!Sp(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ni.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ni.lstat(e),ni.realpath(e)]);if(await ok(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!du(s,n)||!du(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Ir)throw new Error(`Native evidence document exceeds ${Ir} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let p=Ir+1-d,b=await o.read(f,0,Math.min(f.length,p),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>Ir)throw new Error(`Native evidence document exceeds ${Ir} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[h,v,m]=await Promise.all([o.stat(),ni.lstat(e),ni.realpath(e)]);if(await ok(r),!v.isFile()||v.isSymbolicLink()||m!==a||!du(s,h)||!du(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function _a(e,t){if(!ck.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function lk(e){return _a("reports",e)}async function S0(e,t,i,r,n){if(!ck.test(i))throw new Error("Native report evidence hash is invalid");let a=await wn({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||y0("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function Aa(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function E0(e,t,i,r,n){let a=_a(i,r);return n?yi.join(n,...a.split("/")):fr(H(e,t),a)}async function wn(e){let t=E0(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),k0(t,i,e.hooks)}function sk(e,t){return Ea(e,t)}function P0(e,t){let i=Pa(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function R0(e,t,i){let r=cu(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function C0(e,t,i){let r=vs(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function x0(e,t,i,r=!1,n){let a=await fu(e,t,i.implementationScopeRef,void 0,n);if(r&&await S0(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await uk(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function ws(e,t,i,r,n){let a=Aa(i,"scopes"),o=P0(await wn({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Aa(o.baselineProjectionRef,"snapshots"),c=Aa(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([wn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>sk(d,s)),wn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>sk(d,c))]);return zb({baseline:l,current:u,scope:o})}async function fu(e,t,i,r,n){return(await ws(e,t,i,r,n)).scope}async function uk(e,t,i,r,n){let a=Aa(i,"allowances");return R0(await wn({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function ys(e,t,i,r,n){let a=Aa(i,"receipts"),o=uu(await wn({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Ta(e,t,i,r,n){let a=Aa(i,"verifications"),o=C0(await wn({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await x0(e,t,o,!1,n),o}var A0=4096;async function _0(e,t=ut.maxChanges){try{let i=await wt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function dk(e,t){let i=await De(e,t),[r,n]=await Promise.all([i.implementation_scope?fu(e,t,i.implementation_scope):null,kt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function hu(e,t,i={}){let n=(await _0(e,A0)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await dk(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await dk(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Rb([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as G0}from"fs";import U0 from"path";import{isDeepStrictEqual as mu}from"util";var Ia={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var T0=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function I0(e,t){return e<t?-1:e>t?1:0}function j0(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!T0.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(I0)}function Ep(e=[]){return j0(e,"Native repair failed check IDs",Ia.maxFailedCheckIds,!0)}function fk(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function $0(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:fk(e.failedAcceptanceIds,t.failedAcceptanceIds)&&fk(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Pp(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if($0(r,a))break;i+=1,r=a}return i}function Rp(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var hk="repairStagnation",Et={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},H0=/^[a-f0-9]{64}$/u;var D0=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),L0=["data","runId","sequence","timestamp","type"],pk=["disposition","overrideSummaryHash","signatureHash"],M0=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],mk=12;function xp(e,t){return e<t?-1:e>t?1:0}function vk(e,t,i){let r=Object.keys(e).sort(xp);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function pu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Ns(e,t){if(typeof e!="string"||!H0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function F0(e){if(!Array.isArray(e)||e.length>Ia.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(xp)}function gk(e){if(typeof e!="string"||e.length===0||e.length>Et.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Cp(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Et.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Et.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Et.maxTextCharacters&&(!n||e.length>Et.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Et.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Et.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Cp(s,t+1,i,`${r}[${c}]`));return}let a=pu(e,r),o=Object.keys(a);if(o.length>Et.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Et.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Et.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Cp(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function B0(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function V0(e,t,i){let r=pu(e,`Native repair trajectory event ${t+1}`);if(vk(r,L0,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(B0(r.timestamp),typeof r.type!="string"||!D0.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(gk(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Cp(r.data,0,n,"Native trajectory event data"),pu(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Ap(e){let t=pu(e,"Native repair trajectory projection"),i=Object.keys(t).sort(xp),r=i.length===pk.length&&i.every((l,u)=>l===pk[u]);r||vk(t,M0,"Native repair trajectory projection");let n=Ns(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Ns(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Ns(t.contractHash,"Native repair trajectory contract hash"),s=F0(t.failedAcceptanceIds),c=Ep(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function q0(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function W0(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??mk;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Pp({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<Ia.warningAtConsecutiveFailures?"continue":a<Ia.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function z0(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??mk;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function wk(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Et.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=gk(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=V0(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Et.maxTotalDataNodes||c>Et.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?Ns(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Ns(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,hk)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Ap(f[hk]);if(q0(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),W0(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");z0(v,i,r);let m=i.at(-1);if(!m||m.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:m.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>Ia.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function yk(e){return wk(e).history}function Nk(e){let t=wk(e).latestProjection;return t?{...t}:null}var Ni={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:[]},bs=L("comet-native-runtime:v3:scope-reopen"),J0=[{skillVersion:"3",skillHash:L("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:L("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:L("comet-native-runtime:v1")}];function bk(e){return e.skillVersion===Ni.definition.metadata.version&&e.skillHash===bs||J0.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var _p={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function jr(e){let i={sequence:(await it(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await BN(e.changeDir,e.run.trajectoryRef,i),i}async function yn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:L(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await VN(e.changeDir,e.run.checkpointRef,t),t}function kk(e){return L(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var _k=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],K0=new Set(_k),Tk=new Set([..._k,"minimum_runtime_version","revision"]),Y0=new Set([...Tk,"operation"]),X0=512*1024,Tp=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Q0=new Set([...Tp,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),ks=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Ue(e,t){return U0.join(H(e,t),"transition.json")}function Z0(e){return`transition-${e}`}async function eH(e,t,i){let r=Z0(t);return pr(e,r,i)}async function Nn(e,t,i,r){let n=await eH(e,t,i);try{return await r()}finally{await mr(n)}}function gu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function jp(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function vu(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function bi(e,t){return mu(e,t)}function Ip(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!Q0.has(u)),a=[...Tp].find(u=>!Object.hasOwn(i,u)),o=Tp.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Rp(i.summary,"Native transition journal event summary"),$t(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Rp(i.noCodeReason,"Native transition journal event no-code reason"),$t(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Ap(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function tH(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return Ip({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Ip(e,t)}function $p(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?tH(e.eventData,e.evidenceHash):Ip(e.eventData,e.evidenceHash),n=Rr(e.nextRun),a=e.previousRun===null?null:Rr(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Sk(e,t,i=!1){if(e.skill!==Ni.definition.metadata.name||(i?!bk(e):e.skillVersion!==Ni.definition.metadata.version||e.skillHash!==bs)||e.orchestration!==Ni.definition.orchestration.mode||e.pendingRef!==Nt.pendingRef||e.trajectoryRef!==Nt.trajectoryRef||e.contextRef!==Nt.contextRef||e.artifactsRef!==Nt.artifactsRef||e.checkpointRef!==Nt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Ek(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Pk(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function Op(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Sk(o,"next Run",r||a!==null),Pk(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Sk(a,"previous Run",!0),Pk(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!mu(Ek(a),Ek(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function iH(e,t,i){return L(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Ik(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Rk(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Hp(e,t,i,r,n=!1){let a=i.eventData,o=Rk(e),s=Rk(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&mu(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&mu(e.spec_changes,t.spec_changes),l=kk({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=iH(e.name,a.summary,t.spec_changes),l=L(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function Dp(e,t){let i=gu(e);if(jp(i,Y0),i.schema!==vr)throw new Error(`Expected Native transition schema ${vr}`);let r=vu(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${vr} minimum_runtime_version must be ${3}`);let n=vu(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=$p(i,t),o=lt(i.previousState),s=lt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Hp(o,s,a,i.operation),Op(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:vr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function rH(e,t){let i=gu(e);if(jp(i,K0),i.schema!==cn)throw new Error(`Expected Native transition schema ${cn}`);let r=$p(i,t,!0),n=ln(i.previousState),a=ln(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Hp(n,a,r,Ik(n,a,r.eventData),!0),Op(n,a,r,!0),{schema:cn,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function Lp(e,t){let i=gu(e);if(jp(i,Tk),i.schema!==ji)throw new Error(`Expected Native transition schema ${ji}`);if(vu(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${ji} minimum_runtime_version must be 2`);let n=vu(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=$p(i,t,!0),o=di(i.previousState),s=di(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Hp(o,s,a,Ik(o,s,a.eventData),!0),Op(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:ji,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function nH(e,t){let i=gu(e);if(i.schema===vr)return{status:"current",journal:Dp(i,t)};if(i.schema===cn)return{status:"migration-required",journal:rH(i,t)};if(i.schema===ji)return{status:"migration-required",journal:Lp(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function Mp(e,t){let i=Ue(e,t),r=j(e,i);await T(r,i);try{let n=await re({root:r,file:i,maxBytes:X0,label:`Native transition journal ${t}`});return nH(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Bi(e,t){let i=await Mp(e,t);if(!i)return null;if(i.status==="migration-required")throw new ks(t);return i.journal}function Ck(e,t){if(bi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(bi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function xk(e,t){if(bi(e,t.nextState))return"next";if(bi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function aH(e){let{journal:t}=e;return jk({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function jk(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Ak(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=aH({sequence:a.index+1,journal:t,type:a.event.type});if(!bi(jk(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function wu(e,t,i){if(await Na(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Kl(e,t);let r=await Bi(e,t);if(!r)return null;let n=H(e,t),a=Ak(await it(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([Oe(n),De(e,t)]),c=Ck(o,r),l=xk(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await hn(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!bi(await Oe(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let p=await ru(e,r.nextState,r.previousState.revision);if(!bi(p,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!bi(await De(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Bi(e,t);if(!u||!bi(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=Ak(await it(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await jr({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await jr({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await yn({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[h,v]=await Promise.all([Oe(n),De(e,t)]);Ck(h,{...r,previousRun:r.nextRun}),xk(v,{...r,previousState:r.nextState});let m=await Bi(e,t);if(!m||!bi(m,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await G0.rm(Ue(e,t),{force:!0}),r.nextState}async function $k(e,t,i){return se(e,`continue transition ${t}`,()=>Nn(e,t,`continue transition ${t}`,()=>wu(e,t,i)))}import Ok from"node:path";var oH="comet.native.contract.v1",sH="comet.native.acceptance-set.v1",Hk=/^[a-f0-9]{64}$/u,Ss={maxAcceptanceCriteria:Bo.maxCriteria};function Dk(e,t){let i=Ok.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Ok.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Lk(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
205
|
-
`))}function cH(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(Hk))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(Hk))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Dk(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Lk(e.markdown)},markdown:e.markdown}}function lH(e,t){return Mk(e.id,t.id)}function Mk(e,t){return e<t?-1:e>t?1:0}function Fk(e){let t=Dk(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(cH).sort((d,f)=>Mk(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=gl(e.briefMarkdown,t,Ss.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...wl(f,d.source,Ss.maxAcceptanceCriteria-a.length)),a.push(..._y(f,d.source,Ss.maxAcceptanceCriteria-a.length)));if(a.sort(lH),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Ss.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Ss.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Lk(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=D(sH,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:D(oH,u)}}var yu={maxSpecs:64,maxFileBytes:xo,maxTotalBytes:4*1024*1024};async function ja(e){if(e.specChanges.length>yu.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await Z({root:e.changeDir,ref:e.briefRef,maxBytes:yu.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await Z({root:e.changeDir,ref:n.source,maxBytes:yu.maxFileBytes});if(i+=a.size,i>yu.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:Fk({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as xH}from"node:child_process";import{promisify as AH}from"node:util";var FJ=["$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{promises as vH}from"fs";import $a from"path";var Or={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Oa=/^[a-f0-9]{64}$/u;function Nu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function bu(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function $r(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Bk(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Fp(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function uH(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||$a.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=$a.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Bp(e,t){return $a.join(H(e,t),"checkpoints","progress.json")}function Hr(e,t){return $a.join(H(e,t),"checkpoint-journal.json")}function Vp(e,t,i){if(!Oa.test(i))throw new Error("Native checkpoint manifest hash is invalid");return $a.join(H(e,t),"checkpoints","manifests",`${i}.json`)}function dH(e){if(!Oa.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function qp(e,t,i){let r=await re({root:e,file:t,maxBytes:Or.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function fH(e,t){let i=Nu(e,`checkpoint manifest artifact ${t}`);bu(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=uH($r(i.path,`checkpoint artifact ${t} path`,4096)),n=li(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!Oa.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:Fp(i.size,`checkpoint artifact ${t} size`)}}function ku(e,t){let i=Nu(e,"Native checkpoint manifest");if(bu(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>Or.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(fH),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Fp(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Or.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Wp(e){return L(JSON.stringify(ku(e,e.change)))}function zp(e,t){let i=Nu(e,"Native progress checkpoint");if(bu(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Bk(i.previousRevision,"Native checkpoint previousRevision"),a=Bk(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=$r(i.manifestHash,"Native checkpoint manifestHash",64);if(!Oa.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=dH(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=$r(i.inputHash,"Native checkpoint inputHash",64);if(!Oa.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=$r(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Fp(i.artifactCount,"Native checkpoint artifactCount");if(u>Or.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=$r(i.summary,"Native checkpoint summary"),f=$r(i.nextAction,"Native checkpoint nextAction");if($t(d)!==d||$t(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:$r(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function hH(e,t){let i=Nu(e,"Native checkpoint journal");if(bu(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=lt(i.previousState),n=lt(i.nextState),a=zp(i.checkpoint,t),o=ku(i.manifest,t),s=$r(i.inputHash,"Native checkpoint journal inputHash",64),c=L(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Oa.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Wp(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function pH(e,t,i){let r=$a.resolve(e.projectRoot,...t.split("/"));if(!O(e.projectRoot,r)||O(e.nativeRoot,r)||O(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=eh(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await re({root:e.projectRoot,file:r,maxBytes:Or.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function mH(e,t){let i=Bp(e,t),r=j(e,i);await T(r,i);try{return zp(await qp(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Jp(e,t,i){let r=Vp(e,t,i),n=j(e,r);await T(n,r);let a=await qp(n,r,"Native checkpoint manifest"),o=ku(a,t);if(Gp(e,o),Wp(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Dr(e,t){let i=Hr(e,t),r=j(e,i);await T(r,i);try{let n=hH(await qp(r,i,"Native checkpoint journal"),t);return Gp(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Vk(e,t,i,r){let n=ku(i,t);Gp(e,n);let a=Wp(n),o=Vp(e,t,a),s=j(e,o);await T(s,o);try{let c=await Jp(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await ee(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function Gp(e,t){for(let i of t.artifacts){let r=eh(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function qk(e,t){let i=zp(t,t.change),r=await Jp(e,i.change,i.manifestHash),n=L(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=Bp(e,t.change),o=j(e,a);await T(o,a),await ee(a,i,{containedRoot:o})}async function Wk(e){let t;try{t=await mH(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Bp(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await Jp(e.paths,e.name,t.manifestHash);let a=L(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await pH(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Vp(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function zk(e,t,i){let r=await Dr(e,t);if(!r)return null;if(await Vk(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await ru(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await qk(e,r.checkpoint),await i?.afterProgressWritten?.(r),await vH.rm(Hr(e,t),{force:!0}),r}async function Jk(e,t,i){return se(e,`continue checkpoint ${t}`,()=>Nn(e,t,`continue checkpoint ${t}`,async()=>(await wu(e,t),zk(e,t,i))))}import{constants as Up,promises as Ot}from"node:fs";import Ha from"node:path";var gH=/^[a-f0-9]{64}$/u,wH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Es=512*1024;function yH(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Su(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function NH(e,t){let i=Ha.resolve(e),r=Ha.resolve(t);if(!O(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...Ha.relative(i,r).split(Ha.sep).filter(Boolean)]){o&&(a=Ha.join(a,o));let s=await Ot.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ot.realpath(a);if(n.length>0&&!O(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function Gk(e){for(let t of e){let i=await Ot.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!yH(t,i)||await Ot.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function bH(e){if(!gH.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function kH(e){let t=wH.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function SH(e,t,i){return fr(H(e,t),bH(i))}async function EH(e,t,i){let r=await NH(i,Ha.dirname(e)),n=await Ot.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Es)throw new Error(`Native check receipt exceeds ${Es} bytes`);let[a,o]=await Promise.all([Ot.realpath(t),Ot.realpath(e)]);if(!O(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Up.O_RDONLY|Up.O_NOFOLLOW|Up.O_NONBLOCK,c=await Ot.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await Gk(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Su(n,l)||!Su(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,v=Buffer.allocUnsafe(16*1024);for(;;){let g=Es+1-h,y=await c.read(v,0,Math.min(v.length,g),null);if(y.bytesRead===0)break;if(h+=y.bytesRead,h>Es)throw new Error(`Native check receipt exceeds ${Es} bytes`);f.push(Buffer.from(v.subarray(0,y.bytesRead)))}let[m,p,b]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await Gk(r),!p.isFile()||p.isSymbolicLink()||b!==o||!O(a,b)||!Su(l,m)||!Su(l,p))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function Uk(e,t,i){let r=kH(i),n=H(e,t),a=SH(e,t,r),o=j(e,a);await T(o,a);let s=lu(await EH(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var Ps=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var OG=64*1024;var HG=3600*1e3;var DG=AH(xH);var _H=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Kk(e,t){let i=[];for(let r of _H){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function Yk(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Uk(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var Lr=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function TH(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function IH(e){let t=TH(e.bundle.baseline),i=await zh(e.paths,t,{origin:"explicit",now:e.now});return mp({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function Qk(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await ws(e.paths,e.state.name,e.state.implementation_scope),i=await ja({changeDir:ne(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await IH({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function Zk(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Qk(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function jH(e){let t=await Z({root:ne(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Iy(t.text)}}function $H(e){let{receipt:t,implementationScope:i}=e,r=[],n=pp({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function OH(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:kp(e.implementationScope.scope.declaredArtifacts)}}async function Xk(e){let t=await ys(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=Kk(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new Lr([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await Yk({paths:e.paths,state:e.state,receipt:t});if(n){let a=$H({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function HH(e){let t=OH({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await Xk({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Lr)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await Xk({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Lr)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new Lr(i)}function Kp(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Eu(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Kp(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Qk(e),Ta(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:Kp(e.state.verification_result,"stale"),envelope:null};let r=await jH({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await HH({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:Kp(e.state.verification_result,"invalid"),envelope:null}}}function LH(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function tS(e){try{return await DH.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function MH(e,t){try{return(await Z({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function FH(e,t,i){let r=nu(e,i.capability);if(!O(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=eS.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await MH(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await Z({root:ne(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function BH(e,t){return tS(Ue(e,t))}async function Pu(e){let t=e.now??new Date,i=await De(e.paths,e.name),r=await kt(e.paths,e.name),n=await ye(e.paths.projectRoot),a=LH(i.name,t),o=eS.resolve(e.paths.nativeRoot,...a.split("/"));if(!O(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(v=>FH(e.paths,i.name,v))),Eu({paths:e.paths,state:i,now:t}),hu(e.paths,i.name),Na(e.paths,i.name),ba(e.paths,i.name),BH(e.paths,i.name),tS(o)]);return Nb({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as Yp}from"node:fs";import Vi from"node:path";var VH="comet.native.archive-tree.v1",qH={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function nS(e){let t={...qH,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function iS(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function rS(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function aS(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await wt({root:e,directory:t,label:`Native Archive content directory ${Vi.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=iS(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Vi.join(t,u.name),f=Vi.relative(e,d).replaceAll("\\","/"),h=await Yp.lstat(d);if(u.isSymbolicLink()||h.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&h.isDirectory()){rS(i,{ref:f,kind:"directory"},r,n),await aS(e,d,i,r,n,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let v=await re({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=v.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);rS(i,{ref:f,kind:"file",hash:v.hash,size:v.size},r,n),await o.verify()}await o.verify();let l=await wt({root:e,directory:t,label:`Native Archive content directory ${Vi.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(iS(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Vi.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function oS(e,t={}){let i=nS(t);e=Vi.resolve(e);let r=await Yp.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await aS(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return L(`${VH}\0${o}`)}async function ai(e,t={}){let i=nS(t);e=Vi.resolve(e);let r;try{r=await Yp.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await re({root:Vi.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Vi.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await oS(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as rt}from"node:fs";import Ae from"node:path";var Qp=16*1024*1024,WH=256*1024,zH=16*1024,Rs="comet.native.archive-cas.v1";function JH(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=Ae.resolve(n,...a.split("/"));if(!O(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function Le(e,t){let i=JH(e,t);return T(j(e,i),i)}function Mr(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function Da(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function ft(e){let t=await ai(e.target);if(!Mr(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Da(t)}`);return t}async function Zp(e,t){let i=await hi(e,t),r=await re({root:e.runtimeDir,file:i.journal,maxBytes:WH,label:`Native Archive transaction journal ${t}`}),n=jl(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function Ru(e,t,i){let r=jl({...t,status:i}),n=await hi(e,r.id);return await ee(n.journal,r,{containedRoot:e.runtimeDir}),r}function Cu(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function sS(e){return{...Cu(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Fr(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function GH(e,t){return Fr(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ie(e){try{return await rt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ki(e){let t=await rt.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=sS(t),r=await re({root:j(e.paths,e.file),file:e.file,maxBytes:Qp,label:e.label}),n=await rt.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!GH(i,sS(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Cu(n),size:r.size}}function UH(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==Rs||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:Rs,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Si(e,t,i,r){let n=await hi(e,t.id),a=Ae.join(n.backups,".cas"),o=`.${Ae.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:Ae.join(a,`${i.id}.original.json`),postRecord:Ae.join(a,`${i.id}.post.json`),candidate:Ae.join(a,`${i.id}.candidate`),originalQuarantine:Ae.join(Ae.dirname(r),`${o}.original`),rollbackQuarantine:Ae.join(Ae.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function Ht(e){if(!await ie(e.file))return null;let t=await re({root:e.paths.runtimeDir,file:e.file,maxBytes:zH,label:`Archive CAS ${e.operation.id} ${e.role} record`});return UH(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function xu(e){let t=await Ht(e);if(t){if(!Fr(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await fi({root:e.paths.runtimeDir,directory:Ae.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:Rs,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await ee(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await Ht(e);if(!r||!Fr(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Re(e){let t=await ki({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Fr(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function KH(e){let t=await ki({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await xu({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Re({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function YH(e){if(!await ie(e.quarantine)||await ie(e.target))return;let t=await Zt({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await rt.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([rt.lstat(e.quarantine),rt.lstat(e.target)]);if(!Fr(Cu(i),Cu(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await rt.unlink(e.quarantine),await t.verify()}async function dS(e){if(await ie(e.quarantine)){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Zt({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await rt.rename(e.target,e.quarantine),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await YH(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function bn(e){if(!await ie(e.file))return;await Re(e);let t=await Zt({root:j(e.paths,e.file),directory:Ae.dirname(e.file),label:e.label});await t.verify(),await Re(e),await rt.unlink(e.file),await t.verify()}async function cS(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await Le(e,t.target),n=await Le(e,t.backup),a=await ai(n);if(a!==null){if(!Mr(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await ft({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Nr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:Qp,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await ft({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function fS(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await Si(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ie(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Re({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await cS(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await ie(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await KH({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await cS(e.paths,e.operation,e.hooks),await dS({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function lS(e){let t=await Si(e.paths,e.journal,e.operation,e.target);return await ie(t.candidate)?(await ki({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await fi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Nr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:Qp,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function XH(e){let t=e.operation.stagedHash,i=await Si(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await ie(e.target))return await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await ie(i.candidate)&&await bn({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await ie(e.target)){let c=await lS(e),l=await ki({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await ki({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Fr(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await xu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await bn({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await lS(e),a=await ki({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await fi({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Zt({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Re({paths:e.paths,file:n,operation:e.operation,record:{schema:Rs,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await rt.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await ki({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Fr(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await xu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await bn({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function QH(e,t,i,r){let n=await Le(e,i.target),a=await Le(e,i.staged);if(await ft({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Si(e,t,i,n);(!await Ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ie(n))&&await fS({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await ai(n);if(o!==null&&!Mr(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${Da(o)}`)}await XH({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await ft({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function ZH(e,t,i,r){let n=await Le(e,i.target);await fS({paths:e,journal:t,operation:i,target:n,hooks:r}),await ft({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function eD(e,t){let i=await Le(e,t.source),r=await Le(e,t.target),[n,a]=await Promise.all([ai(i),ai(r)]);if(!(n===null&&Mr(a,t.expectedSourceHash,"directory"))){if(!Mr(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Da(n)}, target=${Da(a)}`);await rt.mkdir(Ae.dirname(r),{recursive:!0}),await rt.rename(i,r),await ft({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function tD(e,t,i,r){return i.type==="write"?QH(e,t,i,r):i.type==="remove"?ZH(e,t,i,r):eD(e,i)}function iD(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function rD(e,t,i,r){let n=await Le(e,i.target);if(i.type==="write"){let a=await Le(e,i.staged);await ft({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Si(e,t,i,n),s=await Ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Re({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await ft({target:await Le(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Ht({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await ie(o.originalQuarantine))await Re({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await ft({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await ft({target:await Le(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Si(e,t,i,n),o=await Ht({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await ie(a.originalQuarantine))await Re({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await ft({target:await Le(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await ft({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function hS(e,t,i){let r=t.status==="prepared"?await Ru(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await kr(e,r.id),a=iD({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await rD(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await Tt(e,r.id,"operation-started",l.id),await tD(e,r,l,i),await Tt(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await Zp(e,r.id),r}async function nD(e){try{return await Re(e),!0}catch{return!1}}async function aD(e){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Zt({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await rt.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function Xp(e){if(e.operation.type!=="write")return;let t=await Si(e.paths,e.journal,e.operation,e.target);if(!await ie(t.candidate))return;let i=await ki({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await bn({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Rs,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function oD(e,t,i,r){let n=await Le(e,i.target),a=await Si(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await Ht({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Ht({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ie(a.candidate)&&await ie(n)){let l=await ki({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await ki({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Fr(l.identity,u.identity)&&(c=await xu({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ie(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Re({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ie(n)&&!(s!==null&&await nD({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await ai(n);if(Mr(u,o)){await Xp({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await dS({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await ie(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ie(n)){if(!s||!await ie(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await aD({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await ie(a.originalQuarantine)&&await bn({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ie(a.rollbackQuarantine)&&await bn({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await Xp({paths:e,journal:t,operation:i,target:n}),await ft({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function sD(e,t){let i=await Le(e,t.source),r=await Le(e,t.target),[n,a]=await Promise.all([ai(i),ai(r)]);if(!(Mr(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Mr(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${Da(n)}, target=${Da(a)}`);await rt.mkdir(Ae.dirname(i),{recursive:!0}),await rt.rename(r,i)}}async function pS(e,t,i){let r=await kr(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await Ru(e,t,"rolling-back");await Tt(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await sD(e,o):await oD(e,n,o,i));return await Tt(e,n.id,"rollback-completed"),n=await Ru(e,n,"rolled-back"),n}async function uS(e,t,i){let r=await Le(e,i.target);if(i.type==="write"){let n=await Si(e,t,i,r),a=await Ht({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Re({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await ft({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function cD(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await Le(e,i.target),n=await Si(e,t,i,r);if(await ie(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await uS(e,t,i),i.expectedTargetHash!==null){let a=await Ht({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await ie(n.originalQuarantine)&&await bn({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await Xp({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await uS(e,t,i)}async function Au(e,t,i){return i==="commit"&&await cD(e,t),await Tt(e,t.id,i),i==="commit"?Ru(e,t,"committed"):t}var TU=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});import{promises as lD}from"fs";import uD from"path";var em="comet.selection.v2",dD=16*1024;function _u(e){return uD.join(e,".comet","current-change.json")}function fD(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function mS(e){return e===null||typeof e=="string"}function hD(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!fD(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!mS(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:em,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==em)throw new Error(`current change selection schema must be ${em}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!mS(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function tm(e){let t;try{let r=_u(e),{bytes:n}=await rn(r,dD,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...hD(t)}}async function vS(e){await lD.rm(_u(e),{force:!0})}async function gS(e,t,i){let r=await tm(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await vS(e),!0)}import{promises as Sn}from"node:fs";import qr from"node:path";var cm=Tn(en(),1);import{promises as DS}from"node:fs";import Dt from"node:path";import{execFileSync as pD}from"node:child_process";var mD=3e4,vD=8*1024*1024,im=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function gD(e,t){try{return pD("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:mD,maxBuffer:vD,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new im(e,t,r)}}function Ce(e,t){return gD(e,t).trim()}function Cs(e){return Ce(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}import Me from"node:path";import{promises as ju}from"node:fs";import Tu from"node:path";function wS(...e){if(e.length===0)return Tu.resolve();if(Tu.win32.isAbsolute(e[0])){let t=Tu.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Tu.resolve(...e)}var Iu=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var nm="comet.native.supervisor.v2",wD=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function yD(e,t){let i=Me.relative(Me.resolve(e),Me.resolve(t));return i===""||!Me.isAbsolute(i)&&!i.startsWith(`..${Me.sep}`)}function ND(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function bD(e,t,i){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(i))throw new Error("Native Supervisor parent and child names are invalid");return wS(e,".worktrees",`${t}-${i}`)}function kS(e,t){return Me.join(We(e,t),"supervisor")}function SS(e,t){return Me.join(kS(e,t),"state.json")}function ES(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!==nm)throw new Error(`Native Supervisor state schema must be ${nm}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(La(t.integration.targetCommit,"Native Supervisor target commit"),La(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&La(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(La(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Ei(e,t){try{let i=await ju.readFile(SS(e,t),"utf8"),r=JSON.parse(i);return ES(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function kn(e,t){ES(t),await ju.mkdir(e.changesRuntimeDir,{recursive:!0}),await ee(SS(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function La(e,t){if(!wD.test(e))throw new Error(`${t} must be a Git commit`)}function xs(e){return structuredClone(e)}function am(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function PS(e){La(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:nm,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function om(e){let t=ND(e.parent),i=Ai(e.paths.projectRoot,t);if(!i)return null;let r=Ai(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Jt(e.paths.projectRoot).map(o=>Me.resolve(o)).find(o=>fe(o).currentBranch===t);if(!n)return null;let a=PS({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return am(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function $u(e){if(!Cs(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=Ce(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Me.resolve(t)!==Me.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let i=Ce(e.integration.worktree,["branch","--show-current"]);if(i!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${i||"(detached)"}`);return Ce(e.integration.worktree,["rev-parse","HEAD"])}async function kD(e){let t=Ai(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let i=e.state;if($u(i)!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{Ce(i.integration.worktree,["merge","--no-edit",i.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${i.integration.worktree}`,{cause:o})}let n=Ce(i.integration.worktree,["rev-parse","HEAD"]),a=xs(i);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},am(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${i.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await kn(e.paths,a),a}function SD(e,t){if(La(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 i=xs(e);if(t.headCommit!==i.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(i.children.some(({status:r})=>r!=="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 i.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]}},i.stateVersion+=1,i}function RS(e){let t=$u(e);if(t===e.integration.headCommit)return e;try{Ce(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 i=xs(e);return i.integration.headCommit=t,am(i,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),i.stateVersion+=1,i}function CS(e,t){let i=t.verification;if(i===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let r=$u(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=i.checks.length>0&&i.checks.every(({status:o})=>o==="passed");return SD(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:i.summary.text,headCommit:r,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:i.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:i.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}async function As(e){let i=await Ei(e.paths,e.state.parent)??e.state;if(i.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(i.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!i.children.every(({status:v})=>v==="integrated"||v==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=Jt(e.paths.projectRoot).map(v=>Me.resolve(v)).find(v=>fe(v).currentBranch===i.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${i.integration.targetBranch}`);if(!Cs(n))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let a=Ce(n,["rev-parse","HEAD"]);if((()=>{try{return Ce(n,["merge-base","--is-ancestor",i.integration.headCommit,a]),!0}catch{return!1}})()){let v=await NS({paths:e.paths,state:i,targetCommit:a});if(await bS({paths:e.paths,plan:v}),i.children.every(({status:p})=>p==="archived"))return await rm(e.paths,i.parent),{state:i,targetRoot:n,targetCommit:a};let m=xs(i);for(let p of m.children)p.status="archived";return m.stateVersion+=1,await kn(e.paths,m),await rm(e.paths,i.parent),{state:m,targetRoot:n,targetCommit:a}}let c=$u(i);if(c!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let l=Ai(e.paths.projectRoot,i.integration.targetBranch),u=(()=>{if(!l)return!1;try{return Ce(i.integration.worktree,["merge-base","--is-ancestor",l,c]),!0}catch{return!1}})();if(l!==c&&!u&&l!==i.integration.targetCommit&&await kD({paths:e.paths,state:i}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let d=await NS({paths:e.paths,state:i,targetCommit:c});l!==c&&Ce(n,["merge","--ff-only",i.integration.branch]);let f=Ce(n,["rev-parse","HEAD"]);if(f!==c)throw new Error("Native Supervisor target did not receive the verified integration head");let h=xs(i);for(let v of h.children)v.status="archived";return await bS({paths:e.paths,plan:d}),h.stateVersion+=1,await kn(e.paths,h),await rm(e.paths,i.parent),{state:h,targetRoot:n,targetCommit:f}}function xS(e,t){return Me.join(kS(e,t),"cleanup.json")}function yS(e){let t=Jt(e.paths.projectRoot).map(s=>Me.resolve(s)),i=Me.resolve(process.cwd()),r=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s})=>({root:bD(e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:Me.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=r.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(yD(s.root,i))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!Cs(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=fe(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{Ce(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(Co(e.paths.projectRoot,s))try{Ce(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function NS(e){let t=xS(e.paths,e.state.parent);try{let r=JSON.parse(await ju.readFile(t,"utf8"));if(r.parent===e.state.parent&&r.targetCommit===e.targetCommit&&Array.isArray(r.worktrees)&&r.expectedBranches&&typeof r.expectedBranches=="object"&&Array.isArray(r.branches)){let n=yS(e);return{parent:r.parent,targetCommit:r.targetCommit,worktrees:[...new Set([...r.worktrees,...n.worktrees])],expectedBranches:{...r.expectedBranches,...n.expectedBranches},branches:[...new Set([...r.branches,...n.branches])]}}}catch(r){if(r.code!=="ENOENT")throw r}let i=yS(e);return await ee(t,i,{containedRoot:e.paths.changesRuntimeDir}),i}async function bS(e){for(let t of e.plan.worktrees){if(!Jt(e.paths.projectRoot).map(a=>Me.resolve(a)).includes(Me.resolve(t)))continue;let r=e.plan.expectedBranches[t];if(!r)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=fe(t).currentBranch;if(n!==r)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${r}`);Ce(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)Co(e.paths.projectRoot,t)&&Ce(e.paths.projectRoot,["branch","-d",t])}async function rm(e,t){await ju.rm(xS(e,t),{force:!0})}function AS(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var _S="children.yaml",_s="comet.native.children.v1",Ma="comet.native.children.v2",LS=Ma,ED=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,TS=new Set(["schema","children"]),PD=new Set(["schema","acceptance_index","children"]),RD=new Set(["name","depends_on","covers"]),CD=new Set(["name","summary","depends_on"]),xD=new Set(["name","depends_on","covers"]);function Hu(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function Ou(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function IS(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function sm(e,t){let i=Dt.normalize(Dt.resolve(e)),r=Dt.normalize(Dt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function AD(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function jS(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function _D(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===LS&&e.acceptance_index){let n=i.requiredAcceptanceIds??t??[],a=i.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);r.missing=n.filter(l=>!(l in e.acceptance_index)),r.extra=o.filter(l=>!a.includes(l));let s=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&r.mismatched.push(l)}let c=new Set(o);for(let l of e.children)r.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return r.uncovered=o.filter(l=>!$S(e.children,l)),OS(r)?r:null}if(e.schema===_s&&t){let n=new Set(t);for(let a of e.children)r.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return r.uncovered=t.filter(a=>!$S(e.children,a)),OS(r)?r:null}return null}function $S(e,t){return e.some(i=>i.covers.includes(t))}function OS(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function lm(e){let t=new Set(e.acceptance.map(({id:n})=>n)),i=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),r=new Set(i);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&r.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])i.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...i],allowedAcceptanceIds:[...r]}}function TD(e){let t=Hu(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=Hu(n,`Native children acceptance_index.${r}`);if(Ou(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function ID(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=i.allowedAcceptanceIds??r,a=Object.keys(e),o=r.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(h=>d[h]!==u[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function jD(e,t,i={}){let r=(0,cm.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=Hu(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==_s&&a!==Ma)throw Ou(n,TS,"Native children contract"),new Error(`Native children schema must be ${_s} or ${Ma}`);let o=a===_s?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Ou(n,o==="indexed-v2"?PD:TS,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,h)=>{let v=Hu(f,`Native child ${h}`);if(Ou(v,o==="indexed-v2"?xD:o==="summary-v2"?CD:RD,`Native ${s} child fields (child ${h})`),typeof v.name!="string"||!ED.test(v.name))throw new Error(`Native child ${h} name is invalid`);let m=o==="summary-v2";if(m){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:m?v.summary:null,depends_on:IS(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?IS(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let h=f.depends_on.filter(v=>!u.has(v));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}AD(c);let d=i.policy==="advisory";if(a===LS){if(o==="indexed-v2"){let f=TD(n.acceptance_index);d||ID(f,t,i);let h=Object.keys(f);return d||jS(c,h,h),{schema:Ma,acceptance_index:f,children:c}}return{schema:Ma,children:c}}return t&&!d&&jS(c,t),{schema:_s,children:c}}async function um(e){let t=Dt.join(e.changeDir,_S);try{await DS.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await Z({root:e.changeDir,ref:_S}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=jD(i.text,e.acceptanceIds,n);return{contract:a,size:i.size,drift:r?_D(a,e.acceptanceIds,e.validation??{}):null}}function $D(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function OD(e){let t=$D(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function MS(e){try{let t=await Z({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return OD(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function dm(e){return D("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function HD(e){let t=Jt(e.projectRoot);t.some(r=>sm(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Dt.resolve(n)))]){let n=await ye(r);n&&i.push({projectRoot:r,paths:await qe(r,n.native.artifact_root),parent:sm(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function DD(e,t){let i=Dt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ze(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function LD(e,t){let i;try{i=await DS.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Dt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ze(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function MD(e,t,i){let r=Dt.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Dt.sep}`))return null;let n=r.split(Dt.sep).join("/");try{let a=(0,cm.parseDocument)(Ce(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ct(a.toJS({mapAsMap:!1}))}catch{return null}}function FD(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function HS(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ts(e){let t=Dt.join(e.paths.changesDir,e.state.name),i=await MS(t),r=await um({changeDir:t,validation:lm(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{},policy:"advisory"});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=dm({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!r.drift;if(r.contract.schema===Ma){let p=await Ei(e.paths,e.state.name);if(!p){let y=e.state.workspace.target_branch??e.state.workspace.change_branch;if(y){let E=await om({paths:e.paths,parent:e.state.name,targetBranch:y,contract:r.contract});E&&(p=E,await kn(e.paths,E))}}if(p){let y=AS(p);return e.state.children_contract_hash!==n||r.drift?{...y,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(E=>({...E,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let b=new Map(r.contract.children.map(y=>[y.name,y])),g=r.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:o&&y.depends_on.every(E=>r.contract.children.filter(({name:k})=>k!==y.name).every(({name:k})=>k!==E))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let y of g){if(y.status!=="ready")continue;b.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let s=await HD(e.paths),c=new Set(r.contract.children.map(({name:p})=>p)),l=new Map,u=new Map;for(let p of s){let b=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await LD(p,c)){let y={...g,source:p,committedState:MD(p,g.file,b)};l.set(g.state.name,[...l.get(g.state.name)??[],y])}for(let g of c){let y=await DD(p,g);y&&u.set(g,[...u.get(g)??[],{source:p,state:y}])}}let d=new Map;for(let p of r.contract.children){let b=(l.get(p.name)??[]).find(({source:E,committedState:k})=>E.parent&&k?.name===p.name&&HS(k,a));if(b){d.set(p.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let g=l.get(p.name)?.[0];if(g){d.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let y=u.get(p.name)??[];y.length>1?d.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):y[0]&&d.set(p.name,FD(y[0].state,y[0].source,a))}let f=new Map(r.contract.children.map(p=>[p.name,p])),h=new Map,v=p=>{let b=h.get(p);if(b)return b;let g=f.get(p),E=g.depends_on.map(v).every(({status:P})=>P==="done"),k=d.get(p),S=k?.kind==="active"&&E?g.depends_on.filter(P=>!(l.get(P)??[]).some(({source:F,committedState:$})=>sm(F.projectRoot,k.projectRoot)&&$?.name===P&&HS($,a))):[],R,N=k?.message??null;k?.kind==="done"?(R=E?"done":"blocked",E||(N=`Native child ${p} was merged before its dependencies`)):k?.kind==="active"?(R=E&&S.length===0?"active":"blocked",E?S.length>0&&(N=`Native child ${p} does not include merged dependencies: ${S.join(", ")}`):N=`Native child ${p} started before its dependencies merged`):k?.kind==="blocked"?R="blocked":(R=o&&E?"ready":"pending",o||(N="Parent Shape confirmation is required"));let w={name:p,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:R,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:N};return h.set(p,w),w},m=r.contract.children.map(({name:p})=>v(p));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:m,readyChildren:m.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:m.every(({status:p})=>p==="done")}}var Is="skill-coordinated";function VD(e){return e.state_version+1}function qD(e){return e.map(t=>({...t,result:"pending",reason:null}))}function WD(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:Ii(e.summary),completed_at:e.completedAt}}function fm(e){let t=ct(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=on(t,WD({state:t,outcome:"recovery",summary:e.reason,completedAt:i})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?qD(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return ct({...r,phase:"build",status:"active",state_version:VD(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}import{promises as BS}from"node:fs";import js from"node:path";function Du(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Lu(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Pi(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function FS(e,t){return e===null?null:Pi(e,t)}function Fu(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function zD(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 JD(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Mu(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function hm(e,t){if(e===null)return null;let i=Pi(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function pm(e,t){let i=Pi(e,t);if(!js.isAbsolute(i))throw new Error(`${t} must be absolute`);return js.resolve(i)}function GD(e,t){let i=`Native local checks[${t}]`,r=Du(e,i);if(Lu(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>Pi(l,`${i}.argv[${u}]`,!0)),a=Mu(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=hm(r.startedAt,`${i}.startedAt`),s=hm(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=Fu(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Pi(r.id,`${i}.id`),name:Pi(r.name,`${i}.name`),operationId:Pi(r.operationId,`${i}.operationId`),status:a,repeatable:JD(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Fu(r.executionCount,`${i}.executionCount`),argv:n,cwd:pm(r.cwd,`${i}.cwd`),exitCode:zD(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Pi(r.log,`${i}.log`)}}function mm(e){let t="Native local execution state",i=Du(e,t);if(Lu(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Vo)throw new Error(`Native local execution schema must be ${Vo}`);let r=Du(i.workspace,"Native local workspace");Lu(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Du(i.execution,"Native local execution");Lu(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=hm(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Pi(o.operationId,"Native local execution.operationId"),stage:Mu(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Mu(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:FS(o.executionId,"Native local execution.executionId"),status:Mu(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Fu(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(GD);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:Vo,change:Pi(i.change,"Native local change"),basedOnStateVersion:Fu(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:pm(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:pm(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:FS(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function Br(e){return mm({schema:Vo,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:js.resolve(e.projectRoot),worktreeRoot:js.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Bu(e){let t;try{t=await BS.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return mm(i)}async function qi(e,t,i={}){let r=mm(t);await BS.mkdir(js.dirname(e),{recursive:!0}),await ee(e,r,i)}import{promises as UD}from"node:fs";function Vr(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
206
|
-
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Wi(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function
|
|
207
|
-
`),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(
|
|
208
|
-
`),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${
|
|
209
|
-
`),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${
|
|
210
|
-
`),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${Wi(
|
|
198
|
+
${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return ns(h),h}async function tu(e){let t=await cb(e),i=Na(e.paths,e.name),r=j(e.paths,i);return await I(r,i),await ee(i,t,{containedRoot:r}),t}async function kt(e,t){let i=await ob(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(ns(i),i)}async function lb(e){return await np(e.paths,e.name)?tu(e):null}async function as(e){ns(e.identity);let t=await cb({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),ip==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function ba(e){if(ns(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await as(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=fe(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function ub(e,t){let i=await kt(e,t);if(i===null)return null;let r=await ba({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var fb=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],P$=new Set(fb),hb=new Set([...fb,"minimum_runtime_version","revision"]),R$=new Set([...hb,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),C$=new Set(["capability","operation","source","base_hash"]),x$=new Set(["shape","build","verify","archive"]),A$=new Set(["implicit","confirmed"]),_$=new Set(["pending","pass","fail"]),Te="comet-state.yaml",op=/^[a-f0-9]{64}$/u,pb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,I$=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,os=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},wn=class extends Error{constructor(i,r){super(i!==Ne||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},ss=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},cs=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},ka=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},hz=tc("en");function us(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function mb(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function ru(e){if(!pb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function T$(e){if(!pb.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function vb(e,t){if(e.length===0||vi.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function j$(e,t){let i=us(e,`spec_changes[${t}]`);if(mb(i,C$,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(T$(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&vb(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!op.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!op.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function $$(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 sp(e,t){if(mb(e,t,Te),typeof e.name!="string")throw new Error("Native change name is required");if(ru(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"||!x$.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&&!A$.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(j$),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!_$.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"&&vb(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!$$(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function fn(e){let t=us(e,Te);if(t.schema!==et)throw new Error(`Expected ${et}`);return{schema:et,...sp(t,P$)}}function ls(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ap(e,t,i){if(e===null)return null;let r=typeof e=="string"?I$.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function O$(e){if(e==null)return null;if(typeof e!="string"||!op.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function H$(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function fi(e){let t=us(e,Te);if(t.schema!==be)throw new Error(`Expected ${be}`);if(ls(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${be} minimum_runtime_version must be 2`);return{schema:be,minimum_runtime_version:2,revision:ls(t.revision,"Native v2 revision"),...sp(t,hb)}}function lt(e){let t=us(e,Te);if(t.schema!==Ne){if(t.schema===et||t.schema===be){let o=t.schema===et?fn(t):fi(t);throw new os(o.name,o.schema)}throw new wn(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=ls(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new wn(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=ls(t.revision,"Native revision"),n=sp(t,R$),a=O$(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ne,minimum_runtime_version:3,revision:r,verification_protocol:H$(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:ap(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:ap(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:ap(t.partial_allowance,"Native partial_allowance","allowances")}}function gb(e){let t=us(e,Te);if(t.schema===et){let n=fn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema===be){let n=fi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema!==Ne){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 wn(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=ls(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new wn(t.schema,i).message};let r=lt(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function gn(e){let t=lt(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function nu(e){let t=fi(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function ne(e,t){ru(t);let i=vi.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Sa(e,t){let i=D(e,t),r=vi.join(i,"schema-migration.json");await I(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await db.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Ea(e,t){let i=D(e,t),r=vi.join(i,"checkpoint-journal.json");await I(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await db.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function au(e,t=vi.dirname(e)){let i=vi.relative(t,e).split(vi.sep).join("/"),r=await Z({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,iu.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function gi(e,t){let i=vi.join(ne(e,t),Te);await I(e.nativeRoot,i);let r=gb(await au(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Sa(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await D$(e,r.state),r)}async function ou(e,t){let i=vi.join(ne(e,t),Te);await I(e.nativeRoot,i);let r=gb(await au(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function D$(e,t){if(await va(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function De(e,t){let i=await gi(e,t);if(i.status==="migration-required")throw new os(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new wn(i.schema,i.minimumRuntimeVersion);return await ub(e,t),i.state}async function wb(e,t,i){let r={...t,schema:Ne,minimum_runtime_version:3,revision:i+1},n=await gN({expectedRevision:i,next:r,read:async()=>{let a=lt(await au(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>he(e,(0,iu.stringify)(gn(a))),equals:(a,o)=>JSON.stringify(gn(a))===JSON.stringify(gn(o)),conflict:a=>new ss(t.name,i,a)});return Object.assign(t,n),n}async function su(e,t,i,r){if(await Zn(e.projectRoot),await Sa(e,t.name))throw new os(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await Ea(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await De(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Zl(e,t.name);let a=vi.join(ne(e,t.name),Te);return await I(e.nativeRoot,a),wb(a,t,i)}async function yb(e,t){return wb(e,t,t.revision)}async function Nb(e){return lt(await au(e))}var kb=["outcome","scope","nonGoals","acceptanceExamples"],L$=[...kb,"constraints","decisions","openQuestions","verificationExpectations"],M$=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],Sb={maxFileBytes:Io};function Eb(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
|
|
199
|
+
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function F$(e,t){let i=bb.resolve(e,...t.split(/[\\/]/u));if(!O(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await cp.realpath(e),n=await cp.realpath(i);if(!O(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await cp.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function ds(e){return{valid:e.length===0,findings:e}}function lp(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),i=null;for(let r of e.split(/\r?\n/u)){let n=r.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];i===null?i=s:i===s&&(i=null);continue}if(i!==null)continue;let a=r.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function up(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:Sb.maxFileBytes})).text}catch(a){return ds([{code:"brief-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Eb(r))n.set(ec(a)??a,o);for(let a of L$)n.has(a)||i.push({code:"brief-section-missing",message:`Missing brief section: ${a}`,path:t});for(let a of kb)(n.get(a)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${a}`,path:t});return lp(r)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),ds(i)}async function dp(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:Sb.maxFileBytes})).text}catch(a){return ds([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Eb(r))n.set(sv(a)??a,o);for(let a of M$)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return ds(i)}function cu(e,t){return bb.join(e.specsDir,t,"spec.md")}async function Pb(e,t){let i=[],r=ne(e,t.name);for(let n of t.spec_changes){let a=cu(e,n.capability),o=null;try{await I(e.nativeRoot,a),o=await ti(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await F$(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return ds(i)}import{promises as JH}from"node:fs";import cS from"node:path";import Rb from"node:path";var B$="comet.native.archive-preflight.v1",V$="comet.native.archive-preflight.v1",q$="comet.native.archive-operation.v1",W$=/^[a-f0-9]{64}$/u,Cb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,z$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function lu(e,t){return e<t?-1:e>t?1:0}function J$(e,t){if(typeof e!="string"||!W$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Hi(e,t){return e===null?null:J$(e,t)}function G$(e,t){let i=Rb.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Rb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function U$(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function K$(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function Y$(e,t){if(!Cb.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Hi(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Hi(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Hi(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function X$(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Hi(e.contractHash,"Native archive contract hash"),acceptanceHash:Hi(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Hi(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Hi(e.reportHash,"Native archive report hash"),envelopeHash:Hi(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Hi(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function Q$(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!z$.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(lu);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function Z$(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(lu)}function xb(e){if(!Cb.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(Y$).sort((l,u)=>lu(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:H(q$,l)})),r=X$(e.evidence),n=K$(e.workspace),a=[...new Set([...Q$(e.findingCodes??[]),...Z$({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(lu),o=U$(e.revision),s=G$(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:B$,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:H(V$,c)}}import{createHash as eO}from"node:crypto";import Ab from"node:path";var tO="comet.native.conflict-radar.v1",ut=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}),iO="comet.native.conflict-radar.v1",rO="comet.native.conflict-radar-signals.v1",nO=/^[a-f0-9]{64}$/u,Tb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,aO=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),oO=new Set(["capability","operation","baseHash"]),sO=new Set(["path","kind"]);function Pa(e,t){return e<t?-1:e>t?1:0}function fp(e){return Buffer.byteLength(e,"utf8")}function hp(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function pp(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(fp(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function cO(e,t){let i=pp(e,t,ut.maxArtifactPathBytes),r=Ab.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||Ab.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function jb(e,t){if(typeof e!="string"||!nO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function lO(e,t){let i=hp(e,oO,t),r=pp(i.capability,`${t} capability`,ut.maxCapabilityBytes);if(!Tb.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:jb(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function uO(e,t){let i=hp(e,sO,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:cO(i.path,`${t} path`),kind:i.kind}}function dO(e,t){let i=hp(e,aO,`Conflict radar change ${t}`),r=pp(i.name,`Conflict radar change ${t} name`,ut.maxNameBytes);if(!Tb.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>ut.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>ut.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>lO(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>Pa(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>uO(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>Pa(c.path,l.path)||Pa(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:jb(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function fO(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ut.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(dO).sort((n,a)=>Pa(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>ut.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ut.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function hO(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function pO(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function mO(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function vO(e,t){let i=[],r=eO("sha256").update(`${rO}
|
|
200
|
+
[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(Vo(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<ut.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(hO(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=pO(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:mO(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function _b(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function gO(e,t){return _b(e.classification)-_b(t.classification)||Pa(e.left,t.left)||Pa(e.right,t.right)}function Ib(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:tO,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function $b(e){let t=fO(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(vO(t[s],t[c]));i.sort(gO);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=H(iO,{changes:t,relationships:r}),a=i.slice(0,ut.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Ib(t,i,a,n);for(;a.length>0&&fp(JSON.stringify(o))>ut.maxSerializedBytes;)a=a.slice(0,-1),o=Ib(t,i,a,n);if(fp(JSON.stringify(o))>ut.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as x0}from"node:crypto";import{promises as ai}from"node:fs";import Ni from"node:path";import{createHash as Vb}from"node:crypto";import Ob from"path";var mp="comet.native.implementation-scope.v2",qb="comet.native.content-snapshot-projection.v1",fs="comet.native.content-snapshot-projection.v1",Wb="comet.native.implementation-scope.v2",wO="comet.native.unresolved-scope-id.v1",yO="comet.native.scope-detail-overflow.v1",NO="comet.native.snapshot-projection-overflow.v2",yp=/^[a-f0-9]{64}$/u,Nn=1024*1024,bO=128,kO=128;function Ge(e,t){return e<t?-1:e>t?1:0}function vp(e){if(!yp.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function SO(e,t){return e===t?0:e===null?-1:t===null?1:Ge(e,t)}function _r(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=Ob.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Ob.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function zb(e,t){return e==="."?e:_r(e,t)}function Ra(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function EO(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:_r(e.path,`${t} path`),hash:e.hash,size:Ra(e.size,`${t} size`),type:"file"}}function PO(e,t){return{path:zb(e.path,`${t} path`),size:e.size===null?null:Ra(e.size,`${t} size`),type:e.type,reason:e.reason}}function RO(e,t){return Ge(e.path,t.path)||Ge(e.hash,t.hash)||e.size-t.size}function CO(e,t){return Ge(e.path,t.path)||Ge(e.reason,t.reason)||Ge(e.type,t.type)||(e.size??-1)-(t.size??-1)}function ps(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
201
|
+
`,"utf8")}function Ar(e,t,i){let r=`${t}
|
|
202
|
+
${Vo(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function xO(e){if(ps(e)<=Nn)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=Vb("sha256");a.update(`${NO}
|
|
203
|
+
`),e.omissionOverflow&&Ar(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,Ar(a,"omission",f)},s=f=>{r+=1,n+=1,Ar(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let h=i[f];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return i.splice(f,1),h}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;ps(u)>Nn;){if(i.filter(h=>h.reason!=="git-enumeration-limit"&&h.reason!=="git-selection-changed"&&h.reason!=="physical-enumeration-limit"&&h.reason!=="physical-selection-changed").length>0){let h=Math.max(1,Math.ceil(i.length/4));for(let v=0;v<h;v+=1){let m=c();if(m===null)break;o(m,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-h))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function gp(e){let t=$i(e),i=t.entries.map((n,a)=>EO(n,`Snapshot entry ${a}`));if(i.sort(RO),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>PO(n,`Snapshot omission ${a}`));return r.sort(CO),xO({schema:qb,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function ms(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:_r(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>Ge(i.path,r.path)||Ge(i.kind,r.kind))}function vs(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Hb(e){return e?{hash:e.hash,size:e.size}:null}function Np(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Ge(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:Hb(c),after:Hb(l)})}}function Jb(e,t){return{...e,attributedTo:t.filter(i=>vs(i,e.path))}}function bp(e){let t=ms(e.declaredArtifacts),i=[];return Np(e.baseline,e.current,r=>{i.push(Jb(r,t))}),i}function Di(e,t){return{id:`scope:${H(wO,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function AO(e,t){let i=t.omitted.map(r=>Di({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(Di({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Di({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function Db(e,t){return AO(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function wp(e,t){return Ge(e.kind,t.kind)||Ge(e.source,t.source)||SO(e.path,t.path)||Ge(e.id,t.id)}function _O(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(wp)}function Gb(e){return[...new Set(e.map((t,i)=>_r(t,`Git path ${i}`)))].sort(Ge)}function Lb(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 IO(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 Ub(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Gb(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Lb(e.baseCommit,"Native external drift base commit"),targetBranch:IO(e.targetBranch,"Native external drift target branch"),targetCommit:Lb(e.targetCommit,"Native external drift target commit"),paths:t}}function Kb(e){if(typeof e.contractHash!="string"||!yp.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:ms(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Gb(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:Ub(e.externalDrift)}}}function TO(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return Np(e,t,h=>{let v=i.some(m=>vs(m,h.path));if(d+=1,c.push(h.path),!v&&!n?.has(h.path)&&(f+=1),o?.has(h.path)&&s.push(h.path),!u&&a.length<bO){let m=Jb(h,i),p=ps(m);l+p<=Nn?(a.push(m),l+=p):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Yb(e,t){return Di({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 jO(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let i={changes:Ra(Number(t[1]),"Scope overflow change count"),unresolved:Ra(Number(t[2]),"Scope overflow unresolved count"),unattributed:Ra(Number(t[3]),"Scope overflow unattributed count")},r=yn(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Yb(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function $O(e){let t=Vb("sha256");t.update(`${yO}
|
|
204
|
+
`);let i=0;Np(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){Ar(t,"change",n);let a=0;for(let o of e.declaredArtifacts)vs(o,n.path)&&(a+=1,Ar(t,"change-attribution",o));Ar(t,"change-end",{attributionCount:a}),a===0&&Ar(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&Ar(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function Xb(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=TO(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),y=new Set(o.changePaths),w=i.externalDrift.paths.filter(P=>!y.has(P)||n.some(F=>vs(F,P)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=H(fs,e),c=H(fs,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,y]of[["baseline",e],["current",t]])for(let w of y.omitted){if(l.length>=kO)break;l.push(Di({kind:"snapshot-omission",source:R,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${R} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...Db("baseline",e),...Db("current",t),...o.totalChanges===0&&a===null?[Di({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(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(y=>R.has(y)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(y=>!R.has(y))}},v=R=>{let y=o.candidates.slice(0,R.detailedChangeCount),w=y.filter(qt=>qt.attributedTo.length===0&&!u.has(qt.path)),P=o.totalChanges-y.length,F=o.totalUnattributed-w.length,$=d-R.detailedOmissionCount,Be=F+$,ue=[...w.map(qt=>Di({kind:"unattributed-change",source:"implementation-scope",path:qt.path,evidence:{after:qt.after,before:qt.before,changeKind:qt.kind}},`Changed path is not covered by a declared artifact: ${qt.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...Be>0?[Yb(R.overflowHash,{changes:P,unattributed:F,unresolved:Be})]:[]],te=_O(ue),si=R.includeGitAdvisory?h():void 0;return{schema:mp,contractHash:r,baselineProjectionRef:vp(s),baselineProjectionHash:s,currentProjectionRef:vp(c),currentProjectionHash:c,complete:te.length===0,declaredArtifacts:n,changes:y,unattributed:w,unresolvedScopes:te,noCodeReason:a,...si?{gitAdvisory:si}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},m=o.candidates.length,p=l.length,b=i.gitChangedPaths!==void 0,g="0".repeat(64);for(;;){let R=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:g});if(ps({...R,scopeHash:g})<=Nn)break;if(b){b=!1;continue}if(p>0){p-=Math.max(1,Math.ceil(p/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 N=o.totalChanges>m||d>p?$O({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:m,detailedOmissionCount:p}):g,k=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:N}),E={...k,scopeHash:H(Wb,k)};if(ps(E)>Nn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return E}function kp(e){let t=gp(e.baseline),i=gp(e.current),r=Kb(e);return{authority:r,baseline:t,current:i,scope:Xb(t,i,r)}}var OO=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function wi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function yi(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function yn(e,t){if(typeof e!="string"||!yp.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Mb(e,t,i){let r=vp(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function Ca(e,t){let i=wi(e,"Native snapshot projection");if(yi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==qb)throw new Error("Native snapshot projection schema is invalid");let r=$i({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=gp(r);if(H(fs,i)!==H(fs,n))throw new Error("Native snapshot projection is not canonical");let a=H(fs,n);if(t!==void 0&&yn(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Sp(e,t){let i=wi(e,`Declared artifact ${t}`);if(yi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:_r(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Fb(e,t){if(e===null)return null;let i=wi(e,t);return yi(i,["hash","size"],[],t),{hash:yn(i.hash,`${t} hash`),size:Ra(i.size,`${t} size`)}}function Bb(e,t){let i=wi(e,`Implementation change ${t}`);if(yi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Sp),n=ms(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Fb(i.before,`Implementation change ${t} before`),o=Fb(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:_r(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function HO(e,t){let i=wi(e,`Unresolved scope ${t}`);yi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?zb(i.path,`Unresolved scope ${t} path`):_r(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function hs(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>_r(n,`${t} ${a}`)),r=[...new Set(i)].sort(Ge);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function Qb(e){let t=wi(e,"Native implementation external drift");if(yi(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=hs(t.paths,"Native external drift paths");return Ub({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function xa(e){let t=wi(e,"Native implementation scope"),i=[...OO].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(yi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==mp)throw new Error("Native implementation scope schema is invalid");let r=yn(t.contractHash,"Implementation scope contractHash"),n=yn(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Mb(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=yn(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Mb(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(Sp);if(JSON.stringify(c)!==JSON.stringify(ms(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Bb),u=[...l].sort((w,P)=>Ge(w.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(P=>vs(P,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Bb),h=t.externalDrift===void 0?void 0:Qb(t.externalDrift),v=new Set(h?.paths??[]),m=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(m))throw new Error("Implementation scope unattributed changes are inconsistent");let p=t.unresolvedScopes.map(HO),b=p.filter(w=>w.kind==="scope-detail-overflow");if(b.length>1)throw new Error("Implementation scope has multiple detail overflow records");let g=b[0]===void 0?null:jO(b[0]);if(g&&(g.changes+g.unresolved===0||g.unattributed>g.changes||g.unattributed>g.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,N=[...m.map(w=>Di({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(g?.changes??0)===0&&S===null?[Di({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")]:[]],k=p.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(p)!==JSON.stringify([...p].sort(wp))||new Set(p.map(w=>w.id)).size!==p.length||JSON.stringify(k)!==JSON.stringify(N.sort(wp))||t.complete!==(p.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 E;if(t.gitAdvisory!==void 0){let w=wi(t.gitAdvisory,"Implementation scope Git advisory");if(yi(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=hs(w.changedPaths,"Git changed paths"),F=hs(w.pathsPresentInSnapshotChanges,"Git present paths"),$=hs(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),Be=[...F,...$].sort(Ge);if(JSON.stringify(Be)!==JSON.stringify(P)||$.some(ue=>l.some(te=>te.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");E={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:F,pathsAbsentFromSnapshotChanges:$}}let R={schema:mp,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:p,noCodeReason:S,...E?{gitAdvisory:E}:{},...h?{externalDrift:h}:{}},y=yn(t.scopeHash,"Implementation scope scopeHash");if(H(Wb,R)!==y)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:y}}function DO(e){let t=wi(e,"Native implementation scope authority");if(yi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Sp);if(JSON.stringify(i)!==JSON.stringify(ms(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=hs(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:Qb(t.externalDrift),a=Kb({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function gs(e){let t=wi(e,"Native implementation scope bundle");yi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=DO(t.authority),r=Ca(t.baseline),n=Ca(t.current),a=xa(t.scope),o=Xb(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function Zb(e){let t=xa(e.scope);return gs({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})}import ek from"node:path";var LO=/\b(Bearer|Basic)\s+[^\s"']+/giu,MO=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,FO=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,BO=/\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,VO=/("(?:[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,qO=/(["'])((?:[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,WO=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function $t(e){return e.replace(LO,"$1 [REDACTED]").replace(MO,"[REDACTED PRIVATE KEY]").replace(FO,"$1[REDACTED]@").replace(BO,"[REDACTED TOKEN]").replace(VO,'$1"[REDACTED]"').replace(qO,"$1$2$1$3$4[REDACTED]$4").replace(WO,"$1$2[REDACTED]")}var ik=/^[a-f0-9]{64}$/u;var zO="comet.native.acceptance-trace.v2",JO="comet.native.partial-allowance.v1",GO="comet.native.verification-evidence.v2";function Li(e,t){if(!ik.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function rk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function nk(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 Ep(e,t,i=2e3){let r=$t(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function ws(e,t){let i=ek.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||ek.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function UO(e,t,i){let r=ws(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ui(r),a=r.toLowerCase(),o=i?ws(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function Pp(e){let t=ws(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 Aa(e,t){return e<t?-1:e>t?1:0}function uu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function du(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function ak(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function tk(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function KO(e){let t=uu(e,"Native acceptance trace");if(du(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"||!ik.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=ws(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=uu(o,`Native acceptance trace entry ${s}`);if(du(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=>Pp(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Aa))||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:ws(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Ep(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>Aa(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Li(t.traceHash,"Native acceptance trace hash");if(H(zO,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function fu(e){let t=uu(e,"Native partial allowance");if(du(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(Aa))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:nk(t.change),scopeHash:Li(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Ep(t.reason,"Partial allowance reason"),confirmedSummary:Ep(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:rk(t.sourceRevision),confirmedAt:ak(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Li(t.allowanceHash,"Native partial allowance hash");if(H(JO,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function ys(e){let t=uu(e,"Native verification evidence");if(du(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Li(t.implementationScopeHash,"Native verification implementation scope hash"),r=KO(t.acceptanceTrace),n=Li(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Li(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Pp(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Aa)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(Aa);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Pp(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Aa)))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:nk(t.change),sourceRevision:rk(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Li(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:tk(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:UO(t.reportRef,"Native verification report ref"),reportHash:Li(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:tk(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:ak(t.createdAt,"Native verification timestamp")},d=Li(t.envelopeHash,"Native verification envelope hash");if(H(GO,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import ok from"node:path";var sk="comet.native.check-receipt.v1",YO="comet.native.check-receipt.v1",_a="scoped-text-safety",Rp=1,dt=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),XO=/^[a-f0-9]{64}$/u,QO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ZO="comet.native.checker-policy.v1",e0="comet.native.check-input.v1",t0=2048,ck=H(ZO,{policy:_a,version:Rp,limits:dt,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),i0=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),lk=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],dk=["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"],r0=new Set(dk);function Ir(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Tr(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Mi(e,t){if(typeof e!="string"||!XO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function St(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function fk(e,t){let i=St(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function uk(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function n0(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>t0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=ok.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||ok.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function a0(e){let t=Ir(e,"Native check receipt checker");Tr(t,["policy","version","hash","limits"],"Native check receipt checker");let i=Ir(t.limits,"Native check receipt limits");if(Tr(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==_a||t.version!==Rp||t.hash!==ck||i.maxFiles!==dt.maxFiles||i.maxFileBytes!==dt.maxFileBytes||i.maxTotalBytes!==dt.maxTotalBytes||i.maxIssues!==dt.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:_a,version:Rp,hash:ck,limits:{...dt}}}function o0(e){let t=Ir(e,"Native check receipt contract");return Tr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Mi(t.expectedHash,"Native check expected contract hash"),beforeHash:Mi(t.beforeHash,"Native check before contract hash"),afterHash:Mi(t.afterHash,"Native check after contract hash")}}function s0(e){let t=Ir(e,"Native check receipt implementation");return Tr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Mi(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Mi(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Mi(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Mi(t.afterSnapshotHash,"Native check after snapshot hash")}}function c0(e,t){let i=Ir(e,`Native check batch ${t}`);Tr(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:St(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:St(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:St(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:St(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:St(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:St(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>dt.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>dt.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function l0(e){let t=Ir(e,"Native check receipt counts");Tr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:St(t.filesSelected,"Native check filesSelected"),filesScanned:St(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:St(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:St(t.bytesScanned,"Native check bytesScanned"),issueCount:St(t.issueCount,"Native check issueCount"),recordedIssueCount:St(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(c0):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>dt.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>dt.maxFiles||i.bytesScanned>dt.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function u0(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||lk.indexOf(e.kind)-lk.indexOf(t.kind)}function d0(e){if(!Array.isArray(e)||e.length>dt.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=Ir(r,`Native check issue ${n}`);if(Tr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!i0.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:n0(a.path,`Native check issue ${n} path`),line:fk(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(u0);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function f0(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!r0.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=dk.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function h0(e){return H(e0,e)}function hu(e){let t=Ir(e,"Native check receipt");if(Tr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==sk)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!QO.test(t.change))throw new Error("Native check receipt change name is invalid");let i=fk(t.sourceRevision,"Native check source revision"),r=a0(t.checker),n=o0(t.contract),a=s0(t.implementation),o=h0({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Mi(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=uk(t.startedAt,"Native check receipt startedAt"),c=uk(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=l0(t.counts),u=d0(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=f0(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>dt.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>dt.maxFiles&&!u.some(m=>m.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:sk,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Mi(t.receiptHash,"Native check receipt content hash");if(H(YO,h)!==v)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:v}}var xp="comet.native.verification-receipt.v3",p0=xp,m0="comet.native.declared-artifacts.v1",v0=/^[a-f0-9]{64}$/u,g0=/^acceptance-[a-f0-9]{64}$/u,w0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,y0=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,N0=4096,b0=256,k0=1024;function Ia(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function jr(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Fi(e,t){if(typeof e!="string"||!v0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ni(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=$t(e).trim();if(!i||i.length>N0||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Cp(e,t){let i=ni(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function Ns(e,t,i=ni,r=!1,n=b0){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function S0(e,t){if(typeof e!="string"||!g0.test(e))throw new Error(`${t} is invalid`);return e}function E0(e){let t=Ia(e,"Native verification receipt bindings");if(jr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!w0.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:Fi(t.contractHash,"Native verification receipt contract hash"),scopeHash:Fi(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Fi(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Fi(t.artifactHash,"Native verification receipt artifact hash")}}function P0(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=y0.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function R0(e,t,i,r){let n=Ia(t,`Native ${e} evidence`);if(e==="automated-check"){if(jr(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=Cp(n.startedAt,"Native automated-check start time"),o=Cp(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Ia(n.worktree,"Native automated-check worktree");if(jr(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=Ia(n.afterFence,"Native automated-check after fence");if(jr(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:ni(n.executable,"Native automated-check executable"),args:Ns(n.args,"Native automated-check arguments",ni,!0),cwd:ni(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:ni(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Fi(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Fi(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Fi(n.outputHash,"Native automated-check output hash"),outputSummary:ni(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){jr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=P0(n.checkReceiptRef);if(Fi(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Ns(n.subjects,"Native static inspection subjects",ni,r==="required-check"),rule:ni(n.rule,"Native static inspection rule"),resultSummary:ni(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return jr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Ns(n.steps,"Native manual evidence steps"),observations:Ns(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function C0(e){let t=Ia(e,"Native verification receipt");if(jr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=ni(t.actor,"Native verification receipt actor"),o=Ns(t.acceptanceIds,"Native receipt acceptance IDs",S0,r==="required-check",k0).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:xp,kind:i,role:r,status:n,bindings:E0(t.bindings),acceptanceIds:o,actor:a,issuedAt:Cp(t.issuedAt,"Native verification receipt issue time"),evidence:R0(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==_a||s.actor!==`native-runtime:${_a}`))throw new Error("Native required check policy identity is invalid");return s}function pu(e){let t=Ia(e,"Native verification receipt");if(jr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==xp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=C0(r),a=Fi(t.receiptHash,"Native verification receipt hash");if(H(p0,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Ap(e){return H(m0,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var vk=/^[a-f0-9]{64}$/u,$r=Nn,nJ=3*$r;function _p(e,t){let i=Ni.relative(e,t);return i===""||!Ni.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ni.sep}`)}function A0(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function mu(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function hk(e){let t=await ai.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ai.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function _0(e,t){let i=Ni.resolve(e),r=Ni.resolve(t);if(!_p(i,r))throw new Error("Native evidence path is outside its change");let n=[await hk(i)],a=i;for(let o of Ni.relative(i,r).split(Ni.sep).filter(Boolean)){a=Ni.join(a,o);let s=await hk(a);if(!_p(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function pk(e){for(let t of e){let i=await ai.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!A0(t,i)||await ai.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function I0(e,t,i={}){let r=await _0(t,Ni.dirname(e));await i.afterParentChainCaptured?.();let n=await ai.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ai.realpath(e);if(!_p(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ai.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ai.lstat(e),ai.realpath(e)]);if(await pk(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!mu(s,n)||!mu(s,c))throw new Error("Native evidence document changed while opening");if(s.size>$r)throw new Error(`Native evidence document exceeds ${$r} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let p=$r+1-d,b=await o.read(f,0,Math.min(f.length,p),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>$r)throw new Error(`Native evidence document exceeds ${$r} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[h,v,m]=await Promise.all([o.stat(),ai.lstat(e),ai.realpath(e)]);if(await pk(r),!v.isFile()||v.isSymbolicLink()||m!==a||!mu(s,h)||!mu(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function ja(e,t){if(!vk.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function gk(e){return ja("reports",e)}async function T0(e,t,i,r,n){if(!vk.test(i))throw new Error("Native report evidence hash is invalid");let a=await bn({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||x0("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function Ta(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function j0(e,t,i,r,n){let a=ja(i,r);return n?Ni.join(n,...a.split("/")):pr(D(e,t),a)}async function bn(e){let t=j0(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await I(i,t),I0(t,i,e.hooks)}function mk(e,t){return Ca(e,t)}function $0(e,t){let i=xa(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function O0(e,t,i){let r=fu(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function H0(e,t,i){let r=ys(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function D0(e,t,i,r=!1,n){let a=await vu(e,t,i.implementationScopeRef,void 0,n);if(r&&await T0(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await wk(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function bs(e,t,i,r,n){let a=Ta(i,"scopes"),o=$0(await bn({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Ta(o.baselineProjectionRef,"snapshots"),c=Ta(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([bn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>mk(d,s)),bn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>mk(d,c))]);return Zb({baseline:l,current:u,scope:o})}async function vu(e,t,i,r,n){return(await bs(e,t,i,r,n)).scope}async function wk(e,t,i,r,n){let a=Ta(i,"allowances");return O0(await bn({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function ks(e,t,i,r,n){let a=Ta(i,"receipts"),o=pu(await bn({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function $a(e,t,i,r,n){let a=Ta(i,"verifications"),o=H0(await bn({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await D0(e,t,o,!1,n),o}var L0=4096;async function M0(e,t=ut.maxChanges){try{let i=await wt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function yk(e,t){let i=await De(e,t),[r,n]=await Promise.all([i.implementation_scope?vu(e,t,i.implementation_scope):null,kt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function gu(e,t,i={}){let n=(await M0(e,L0)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await yk(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await yk(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=$b([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as iH}from"fs";import rH from"path";import{isDeepStrictEqual as yu}from"util";var Oa={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var F0=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function B0(e,t){return e<t?-1:e>t?1:0}function V0(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!F0.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(B0)}function Ip(e=[]){return V0(e,"Native repair failed check IDs",Oa.maxFailedCheckIds,!0)}function Nk(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function q0(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Nk(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Nk(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Tp(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(q0(r,a))break;i+=1,r=a}return i}function jp(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var bk="repairStagnation",Et={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},z0=/^[a-f0-9]{64}$/u;var J0=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),G0=["data","runId","sequence","timestamp","type"],kk=["disposition","overrideSummaryHash","signatureHash"],U0=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Sk=12;function Op(e,t){return e<t?-1:e>t?1:0}function Ek(e,t,i){let r=Object.keys(e).sort(Op);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function wu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Ss(e,t){if(typeof e!="string"||!z0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function K0(e){if(!Array.isArray(e)||e.length>Oa.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Op)}function Pk(e){if(typeof e!="string"||e.length===0||e.length>Et.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function $p(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Et.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Et.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Et.maxTextCharacters&&(!n||e.length>Et.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Et.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Et.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>$p(s,t+1,i,`${r}[${c}]`));return}let a=wu(e,r),o=Object.keys(a);if(o.length>Et.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Et.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Et.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");$p(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function Y0(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function X0(e,t,i){let r=wu(e,`Native repair trajectory event ${t+1}`);if(Ek(r,G0,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(Y0(r.timestamp),typeof r.type!="string"||!J0.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(Pk(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return $p(r.data,0,n,"Native trajectory event data"),wu(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Hp(e){let t=wu(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Op),r=i.length===kk.length&&i.every((l,u)=>l===kk[u]);r||Ek(t,U0,"Native repair trajectory projection");let n=Ss(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Ss(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Ss(t.contractHash,"Native repair trajectory contract hash"),s=K0(t.failedAcceptanceIds),c=Ip(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function Q0(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function Z0(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??Sk;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Tp({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<Oa.warningAtConsecutiveFailures?"continue":a<Oa.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function eH(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??Sk;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Rk(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Et.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Pk(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=X0(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Et.maxTotalDataNodes||c>Et.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?Ss(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Ss(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,bk)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Hp(f[bk]);if(Q0(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),Z0(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");eH(v,i,r);let m=i.at(-1);if(!m||m.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:m.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>Oa.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function Ck(e){return Rk(e).history}function xk(e){let t=Rk(e).latestProjection;return t?{...t}:null}var bi={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:[]},Es=L("comet-native-runtime:v3:scope-reopen"),tH=[{skillVersion:"3",skillHash:L("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:L("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:L("comet-native-runtime:v1")}];function Ak(e){return e.skillVersion===bi.definition.metadata.version&&e.skillHash===Es||tH.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var Dp={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function Or(e){let i={sequence:(await it(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await KN(e.changeDir,e.run.trajectoryRef,i),i}async function kn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:L(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await YN(e.changeDir,e.run.checkpointRef,t),t}function _k(e){return L(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var Lk=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],nH=new Set(Lk),Mk=new Set([...Lk,"minimum_runtime_version","revision"]),aH=new Set([...Mk,"operation"]),oH=512*1024,Lp=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),sH=new Set([...Lp,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Ps=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Ue(e,t){return rH.join(D(e,t),"transition.json")}function cH(e){return`transition-${e}`}async function lH(e,t,i){let r=cH(t);return vr(e,r,i)}async function Sn(e,t,i,r){let n=await lH(e,t,i);try{return await r()}finally{await gr(n)}}function bu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Fp(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Nu(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ki(e,t){return yu(e,t)}function Mp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!sH.has(u)),a=[...Lp].find(u=>!Object.hasOwn(i,u)),o=Lp.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(jp(i.summary,"Native transition journal event summary"),$t(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(jp(i.noCodeReason,"Native transition journal event no-code reason"),$t(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Hp(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function uH(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return Mp({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Mp(e,t)}function Bp(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?uH(e.eventData,e.evidenceHash):Mp(e.eventData,e.evidenceHash),n=xr(e.nextRun),a=e.previousRun===null?null:xr(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Ik(e,t,i=!1){if(e.skill!==bi.definition.metadata.name||(i?!Ak(e):e.skillVersion!==bi.definition.metadata.version||e.skillHash!==Es)||e.orchestration!==bi.definition.orchestration.mode||e.pendingRef!==Nt.pendingRef||e.trajectoryRef!==Nt.trajectoryRef||e.contextRef!==Nt.contextRef||e.artifactsRef!==Nt.artifactsRef||e.checkpointRef!==Nt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Tk(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function jk(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function Vp(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Ik(o,"next Run",r||a!==null),jk(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Ik(a,"previous Run",!0),jk(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!yu(Tk(a),Tk(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function dH(e,t,i){return L(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Fk(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function $k(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function qp(e,t,i,r,n=!1){let a=i.eventData,o=$k(e),s=$k(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&yu(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&yu(e.spec_changes,t.spec_changes),l=_k({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=dH(e.name,a.summary,t.spec_changes),l=L(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function Wp(e,t){let i=bu(e);if(Fp(i,aH),i.schema!==wr)throw new Error(`Expected Native transition schema ${wr}`);let r=Nu(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${wr} minimum_runtime_version must be ${3}`);let n=Nu(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Bp(i,t),o=lt(i.previousState),s=lt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(qp(o,s,a,i.operation),Vp(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:wr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function fH(e,t){let i=bu(e);if(Fp(i,nH),i.schema!==dn)throw new Error(`Expected Native transition schema ${dn}`);let r=Bp(i,t,!0),n=fn(i.previousState),a=fn(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return qp(n,a,r,Fk(n,a,r.eventData),!0),Vp(n,a,r,!0),{schema:dn,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function zp(e,t){let i=bu(e);if(Fp(i,Mk),i.schema!==ji)throw new Error(`Expected Native transition schema ${ji}`);if(Nu(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${ji} minimum_runtime_version must be 2`);let n=Nu(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Bp(i,t,!0),o=fi(i.previousState),s=fi(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(qp(o,s,a,Fk(o,s,a.eventData),!0),Vp(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:ji,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function hH(e,t){let i=bu(e);if(i.schema===wr)return{status:"current",journal:Wp(i,t)};if(i.schema===dn)return{status:"migration-required",journal:fH(i,t)};if(i.schema===ji)return{status:"migration-required",journal:zp(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function Jp(e,t){let i=Ue(e,t),r=j(e,i);await I(r,i);try{let n=await re({root:r,file:i,maxBytes:oH,label:`Native transition journal ${t}`});return hH(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Bi(e,t){let i=await Jp(e,t);if(!i)return null;if(i.status==="migration-required")throw new Ps(t);return i.journal}function Ok(e,t){if(ki(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(ki(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function Hk(e,t){if(ki(e,t.nextState))return"next";if(ki(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function pH(e){let{journal:t}=e;return Bk({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function Bk(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Dk(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=pH({sequence:a.index+1,journal:t,type:a.event.type});if(!ki(Bk(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function ku(e,t,i){if(await Sa(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Zl(e,t);let r=await Bi(e,t);if(!r)return null;let n=D(e,t),a=Dk(await it(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([Oe(n),De(e,t)]),c=Ok(o,r),l=Hk(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await vn(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!ki(await Oe(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let p=await su(e,r.nextState,r.previousState.revision);if(!ki(p,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!ki(await De(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Bi(e,t);if(!u||!ki(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=Dk(await it(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await Or({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await Or({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await kn({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[h,v]=await Promise.all([Oe(n),De(e,t)]);Ok(h,{...r,previousRun:r.nextRun}),Hk(v,{...r,previousState:r.nextState});let m=await Bi(e,t);if(!m||!ki(m,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await iH.rm(Ue(e,t),{force:!0}),r.nextState}async function Vk(e,t,i){return se(e,`continue transition ${t}`,()=>Sn(e,t,`continue transition ${t}`,()=>ku(e,t,i)))}import qk from"node:path";var mH="comet.native.contract.v1",vH="comet.native.acceptance-set.v1",Wk=/^[a-f0-9]{64}$/u,Rs={maxAcceptanceCriteria:Wo.maxCriteria};function zk(e,t){let i=qk.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||qk.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Jk(e){return H("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
205
|
+
`))}function gH(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(Wk))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(Wk))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=zk(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Jk(e.markdown)},markdown:e.markdown}}function wH(e,t){return Gk(e.id,t.id)}function Gk(e,t){return e<t?-1:e>t?1:0}function Uk(e){let t=zk(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(gH).sort((d,f)=>Gk(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=bl(e.briefMarkdown,t,Rs.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...kl(f,d.source,Rs.maxAcceptanceCriteria-a.length)),a.push(...Dy(f,d.source,Rs.maxAcceptanceCriteria-a.length)));if(a.sort(wH),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Rs.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Rs.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Jk(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=H(vH,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:H(mH,u)}}var Su={maxSpecs:64,maxFileBytes:Io,maxTotalBytes:4*1024*1024};async function Ha(e){if(e.specChanges.length>Su.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await Z({root:e.changeDir,ref:e.briefRef,maxBytes:Su.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await Z({root:e.changeDir,ref:n.source,maxBytes:Su.maxFileBytes});if(i+=a.size,i>Su.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:Uk({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as DH}from"node:child_process";import{promisify as LH}from"node:util";var oG=["$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{promises as PH}from"fs";import Da from"path";var Dr={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},La=/^[a-f0-9]{64}$/u;function Eu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Pu(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Hr(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Kk(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Gp(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function yH(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Da.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Da.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Up(e,t){return Da.join(D(e,t),"checkpoints","progress.json")}function Lr(e,t){return Da.join(D(e,t),"checkpoint-journal.json")}function Kp(e,t,i){if(!La.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Da.join(D(e,t),"checkpoints","manifests",`${i}.json`)}function NH(e){if(!La.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Yp(e,t,i){let r=await re({root:e,file:t,maxBytes:Dr.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function bH(e,t){let i=Eu(e,`checkpoint manifest artifact ${t}`);Pu(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=yH(Hr(i.path,`checkpoint artifact ${t} path`,4096)),n=ui(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!La.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:Gp(i.size,`checkpoint artifact ${t} size`)}}function Ru(e,t){let i=Eu(e,"Native checkpoint manifest");if(Pu(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>Dr.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(bH),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Gp(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Dr.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Xp(e){return L(JSON.stringify(Ru(e,e.change)))}function Qp(e,t){let i=Eu(e,"Native progress checkpoint");if(Pu(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Kk(i.previousRevision,"Native checkpoint previousRevision"),a=Kk(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Hr(i.manifestHash,"Native checkpoint manifestHash",64);if(!La.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=NH(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Hr(i.inputHash,"Native checkpoint inputHash",64);if(!La.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Hr(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Gp(i.artifactCount,"Native checkpoint artifactCount");if(u>Dr.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Hr(i.summary,"Native checkpoint summary"),f=Hr(i.nextAction,"Native checkpoint nextAction");if($t(d)!==d||$t(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Hr(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function kH(e,t){let i=Eu(e,"Native checkpoint journal");if(Pu(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=lt(i.previousState),n=lt(i.nextState),a=Qp(i.checkpoint,t),o=Ru(i.manifest,t),s=Hr(i.inputHash,"Native checkpoint journal inputHash",64),c=L(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!La.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Xp(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function SH(e,t,i){let r=Da.resolve(e.projectRoot,...t.split("/"));if(!O(e.projectRoot,r)||O(e.nativeRoot,r)||O(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=oh(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await re({root:e.projectRoot,file:r,maxBytes:Dr.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function EH(e,t){let i=Up(e,t),r=j(e,i);await I(r,i);try{return Qp(await Yp(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Zp(e,t,i){let r=Kp(e,t,i),n=j(e,r);await I(n,r);let a=await Yp(n,r,"Native checkpoint manifest"),o=Ru(a,t);if(em(e,o),Xp(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Mr(e,t){let i=Lr(e,t),r=j(e,i);await I(r,i);try{let n=kH(await Yp(r,i,"Native checkpoint journal"),t);return em(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Yk(e,t,i,r){let n=Ru(i,t);em(e,n);let a=Xp(n),o=Kp(e,t,a),s=j(e,o);await I(s,o);try{let c=await Zp(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await ee(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function em(e,t){for(let i of t.artifacts){let r=oh(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Xk(e,t){let i=Qp(t,t.change),r=await Zp(e,i.change,i.manifestHash),n=L(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=Up(e,t.change),o=j(e,a);await I(o,a),await ee(a,i,{containedRoot:o})}async function Qk(e){let t;try{t=await EH(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Up(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await Zp(e.paths,e.name,t.manifestHash);let a=L(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await SH(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Kp(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function Zk(e,t,i){let r=await Mr(e,t);if(!r)return null;if(await Yk(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await su(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await Xk(e,r.checkpoint),await i?.afterProgressWritten?.(r),await PH.rm(Lr(e,t),{force:!0}),r}async function eS(e,t,i){return se(e,`continue checkpoint ${t}`,()=>Sn(e,t,`continue checkpoint ${t}`,async()=>(await ku(e,t),Zk(e,t,i))))}import{constants as tm,promises as Ot}from"node:fs";import Ma from"node:path";var RH=/^[a-f0-9]{64}$/u,CH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Cs=512*1024;function xH(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Cu(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function AH(e,t){let i=Ma.resolve(e),r=Ma.resolve(t);if(!O(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...Ma.relative(i,r).split(Ma.sep).filter(Boolean)]){o&&(a=Ma.join(a,o));let s=await Ot.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ot.realpath(a);if(n.length>0&&!O(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function tS(e){for(let t of e){let i=await Ot.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!xH(t,i)||await Ot.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function _H(e){if(!RH.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function IH(e){let t=CH.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function TH(e,t,i){return pr(D(e,t),_H(i))}async function jH(e,t,i){let r=await AH(i,Ma.dirname(e)),n=await Ot.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Cs)throw new Error(`Native check receipt exceeds ${Cs} bytes`);let[a,o]=await Promise.all([Ot.realpath(t),Ot.realpath(e)]);if(!O(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":tm.O_RDONLY|tm.O_NOFOLLOW|tm.O_NONBLOCK,c=await Ot.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await tS(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Cu(n,l)||!Cu(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,v=Buffer.allocUnsafe(16*1024);for(;;){let g=Cs+1-h,S=await c.read(v,0,Math.min(v.length,g),null);if(S.bytesRead===0)break;if(h+=S.bytesRead,h>Cs)throw new Error(`Native check receipt exceeds ${Cs} bytes`);f.push(Buffer.from(v.subarray(0,S.bytesRead)))}let[m,p,b]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await tS(r),!p.isFile()||p.isSymbolicLink()||b!==o||!O(a,b)||!Cu(l,m)||!Cu(l,p))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function iS(e,t,i){let r=IH(i),n=D(e,t),a=TH(e,t,r),o=j(e,a);await I(o,a);let s=hu(await jH(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var xs=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var tU=64*1024;var iU=3600*1e3;var rU=LH(DH);var MH=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function rS(e,t){let i=[];for(let r of MH){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function nS(e){if(e.receipt.kind!=="static-inspection")return null;let t=await iS(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var Fr=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function FH(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function BH(e){let t=FH(e.bundle.baseline),i=await Xh(e.paths,t,{origin:"explicit",now:e.now});return kp({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function oS(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await bs(e.paths,e.state.name,e.state.implementation_scope),i=await Ha({changeDir:ne(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await BH({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function sS(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await oS(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function VH(e){let t=await Z({root:ne(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:My(t.text)}}function qH(e){let{receipt:t,implementationScope:i}=e,r=[],n=bp({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function WH(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Ap(e.implementationScope.scope.declaredArtifacts)}}async function aS(e){let t=await ks(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=rS(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new Fr([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await nS({paths:e.paths,state:e.state,receipt:t});if(n){let a=qH({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function zH(e){let t=WH({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await aS({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Fr)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await aS({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Fr)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new Fr(i)}function im(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function xu(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:im(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([oS(e),$a(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:im(e.state.verification_result,"stale"),envelope:null};let r=await VH({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await zH({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:im(e.state.verification_result,"invalid"),envelope:null}}}function GH(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function lS(e){try{return await JH.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function UH(e,t){try{return(await Z({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function KH(e,t,i){let r=cu(e,i.capability);if(!O(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=cS.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await UH(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await Z({root:ne(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function YH(e,t){return lS(Ue(e,t))}async function Au(e){let t=e.now??new Date,i=await De(e.paths,e.name),r=await kt(e.paths,e.name),n=await ye(e.paths.projectRoot),a=GH(i.name,t),o=cS.resolve(e.paths.nativeRoot,...a.split("/"));if(!O(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(v=>KH(e.paths,i.name,v))),xu({paths:e.paths,state:i,now:t}),gu(e.paths,i.name),Sa(e.paths,i.name),Ea(e.paths,i.name),YH(e.paths,i.name),lS(o)]);return xb({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as rm}from"node:fs";import Vi from"node:path";var XH="comet.native.archive-tree.v1",QH={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function fS(e){let t={...QH,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function uS(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function dS(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function hS(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await wt({root:e,directory:t,label:`Native Archive content directory ${Vi.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=uS(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Vi.join(t,u.name),f=Vi.relative(e,d).replaceAll("\\","/"),h=await rm.lstat(d);if(u.isSymbolicLink()||h.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&h.isDirectory()){dS(i,{ref:f,kind:"directory"},r,n),await hS(e,d,i,r,n,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let v=await re({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=v.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);dS(i,{ref:f,kind:"file",hash:v.hash,size:v.size},r,n),await o.verify()}await o.verify();let l=await wt({root:e,directory:t,label:`Native Archive content directory ${Vi.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(uS(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Vi.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function pS(e,t={}){let i=fS(t);e=Vi.resolve(e);let r=await rm.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await hS(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return L(`${XH}\0${o}`)}async function oi(e,t={}){let i=fS(t);e=Vi.resolve(e);let r;try{r=await rm.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await re({root:Vi.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Vi.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await pS(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as rt}from"node:fs";import Ae from"node:path";var am=16*1024*1024,ZH=256*1024,eD=16*1024,As="comet.native.archive-cas.v1";function tD(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=Ae.resolve(n,...a.split("/"));if(!O(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function Le(e,t){let i=tD(e,t);return I(j(e,i),i)}function Br(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function Fa(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function ft(e){let t=await oi(e.target);if(!Br(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Fa(t)}`);return t}async function om(e,t){let i=await pi(e,t),r=await re({root:e.runtimeDir,file:i.journal,maxBytes:ZH,label:`Native Archive transaction journal ${t}`}),n=Dl(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function _u(e,t,i){let r=Dl({...t,status:i}),n=await pi(e,r.id);return await ee(n.journal,r,{containedRoot:e.runtimeDir}),r}function Iu(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function mS(e){return{...Iu(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Vr(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function iD(e,t){return Vr(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ie(e){try{return await rt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Si(e){let t=await rt.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=mS(t),r=await re({root:j(e.paths,e.file),file:e.file,maxBytes:am,label:e.label}),n=await rt.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!iD(i,mS(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Iu(n),size:r.size}}function rD(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==As||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:As,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Ei(e,t,i,r){let n=await pi(e,t.id),a=Ae.join(n.backups,".cas"),o=`.${Ae.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:Ae.join(a,`${i.id}.original.json`),postRecord:Ae.join(a,`${i.id}.post.json`),candidate:Ae.join(a,`${i.id}.candidate`),originalQuarantine:Ae.join(Ae.dirname(r),`${o}.original`),rollbackQuarantine:Ae.join(Ae.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>I(j(e,c),c))),s}async function Ht(e){if(!await ie(e.file))return null;let t=await re({root:e.paths.runtimeDir,file:e.file,maxBytes:eD,label:`Archive CAS ${e.operation.id} ${e.role} record`});return rD(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Tu(e){let t=await Ht(e);if(t){if(!Vr(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await hi({root:e.paths.runtimeDir,directory:Ae.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:As,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await ee(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await Ht(e);if(!r||!Vr(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Re(e){let t=await Si({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Vr(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function nD(e){let t=await Si({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Tu({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Re({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function aD(e){if(!await ie(e.quarantine)||await ie(e.target))return;let t=await ei({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await rt.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([rt.lstat(e.quarantine),rt.lstat(e.target)]);if(!Vr(Iu(i),Iu(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await rt.unlink(e.quarantine),await t.verify()}async function yS(e){if(await ie(e.quarantine)){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await ei({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await rt.rename(e.target,e.quarantine),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await aD(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function En(e){if(!await ie(e.file))return;await Re(e);let t=await ei({root:j(e.paths,e.file),directory:Ae.dirname(e.file),label:e.label});await t.verify(),await Re(e),await rt.unlink(e.file),await t.verify()}async function vS(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await Le(e,t.target),n=await Le(e,t.backup),a=await oi(n);if(a!==null){if(!Br(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await ft({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await kr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:am,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await ft({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function NS(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await Ei(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ie(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Re({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await vS(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await ie(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await nD({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await vS(e.paths,e.operation,e.hooks),await yS({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function gS(e){let t=await Ei(e.paths,e.journal,e.operation,e.target);return await ie(t.candidate)?(await Si({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await hi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await kr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:am,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function oD(e){let t=e.operation.stagedHash,i=await Ei(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await ie(e.target))return await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await ie(i.candidate)&&await En({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await ie(e.target)){let c=await gS(e),l=await Si({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Si({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Vr(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await Tu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await En({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await gS(e),a=await Si({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await hi({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await ei({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Re({paths:e.paths,file:n,operation:e.operation,record:{schema:As,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await rt.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await Si({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Vr(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await Tu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await En({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function sD(e,t,i,r){let n=await Le(e,i.target),a=await Le(e,i.staged);if(await ft({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Ei(e,t,i,n);(!await Ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ie(n))&&await NS({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await oi(n);if(o!==null&&!Br(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${Fa(o)}`)}await oD({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await ft({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function cD(e,t,i,r){let n=await Le(e,i.target);await NS({paths:e,journal:t,operation:i,target:n,hooks:r}),await ft({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function lD(e,t){let i=await Le(e,t.source),r=await Le(e,t.target),[n,a]=await Promise.all([oi(i),oi(r)]);if(!(n===null&&Br(a,t.expectedSourceHash,"directory"))){if(!Br(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Fa(n)}, target=${Fa(a)}`);await rt.mkdir(Ae.dirname(r),{recursive:!0}),await rt.rename(i,r),await ft({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function uD(e,t,i,r){return i.type==="write"?sD(e,t,i,r):i.type==="remove"?cD(e,t,i,r):lD(e,i)}function dD(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function fD(e,t,i,r){let n=await Le(e,i.target);if(i.type==="write"){let a=await Le(e,i.staged);await ft({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Ei(e,t,i,n),s=await Ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Re({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await ft({target:await Le(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Ht({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await ie(o.originalQuarantine))await Re({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await ft({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await ft({target:await Le(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Ei(e,t,i,n),o=await Ht({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await ie(a.originalQuarantine))await Re({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await ft({target:await Le(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await ft({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function bS(e,t,i){let r=t.status==="prepared"?await _u(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await Er(e,r.id),a=dD({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await fD(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await It(e,r.id,"operation-started",l.id),await uD(e,r,l,i),await It(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await om(e,r.id),r}async function hD(e){try{return await Re(e),!0}catch{return!1}}async function pD(e){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await ei({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await rt.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function nm(e){if(e.operation.type!=="write")return;let t=await Ei(e.paths,e.journal,e.operation,e.target);if(!await ie(t.candidate))return;let i=await Si({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await En({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:As,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function mD(e,t,i,r){let n=await Le(e,i.target),a=await Ei(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await Ht({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Ht({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ie(a.candidate)&&await ie(n)){let l=await Si({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await Si({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Vr(l.identity,u.identity)&&(c=await Tu({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ie(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Re({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ie(n)&&!(s!==null&&await hD({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await oi(n);if(Br(u,o)){await nm({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await yS({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await ie(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ie(n)){if(!s||!await ie(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await pD({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await ie(a.originalQuarantine)&&await En({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ie(a.rollbackQuarantine)&&await En({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await nm({paths:e,journal:t,operation:i,target:n}),await ft({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function vD(e,t){let i=await Le(e,t.source),r=await Le(e,t.target),[n,a]=await Promise.all([oi(i),oi(r)]);if(!(Br(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Br(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${Fa(n)}, target=${Fa(a)}`);await rt.mkdir(Ae.dirname(i),{recursive:!0}),await rt.rename(r,i)}}async function kS(e,t,i){let r=await Er(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await _u(e,t,"rolling-back");await It(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await vD(e,o):await mD(e,n,o,i));return await It(e,n.id,"rollback-completed"),n=await _u(e,n,"rolled-back"),n}async function wS(e,t,i){let r=await Le(e,i.target);if(i.type==="write"){let n=await Ei(e,t,i,r),a=await Ht({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Re({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await ft({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function gD(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await Le(e,i.target),n=await Ei(e,t,i,r);if(await ie(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await wS(e,t,i),i.expectedTargetHash!==null){let a=await Ht({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await ie(n.originalQuarantine)&&await En({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await nm({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await wS(e,t,i)}async function ju(e,t,i){return i==="commit"&&await gD(e,t),await It(e,t.id,i),i==="commit"?_u(e,t,"committed"):t}var XU=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});import{promises as wD}from"fs";import yD from"path";var sm="comet.selection.v2",ND=16*1024;function $u(e){return yD.join(e,".comet","current-change.json")}function bD(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function SS(e){return e===null||typeof e=="string"}function kD(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!bD(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!SS(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:sm,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==sm)throw new Error(`current change selection schema must be ${sm}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!SS(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function cm(e){let t;try{let r=$u(e),{bytes:n}=await on(r,ND,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...kD(t)}}async function ES(e){await wD.rm($u(e),{force:!0})}async function PS(e,t,i){let r=await cm(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await ES(e),!0)}import{promises as Rn}from"node:fs";import zr from"node:path";var mm=$n(nn(),1);import{promises as WS}from"node:fs";import Lt from"node:path";import{execFileSync as SD}from"node:child_process";var ED=3e4,PD=8*1024*1024,lm=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function RD(e,t){try{return SD("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:ED,maxBuffer:PD,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new lm(e,t,r)}}function Ce(e,t){return RD(e,t).trim()}function _s(e){return Ce(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}import Me from"node:path";import{promises as Du}from"node:fs";import Ou from"node:path";function RS(...e){if(e.length===0)return Ou.resolve();if(Ou.win32.isAbsolute(e[0])){let t=Ou.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Ou.resolve(...e)}var Hu=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var dm="comet.native.supervisor.v2",CD=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function xD(e,t){let i=Me.relative(Me.resolve(e),Me.resolve(t));return i===""||!Me.isAbsolute(i)&&!i.startsWith(`..${Me.sep}`)}function AD(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function _D(e,t,i){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(i))throw new Error("Native Supervisor parent and child names are invalid");return RS(e,".worktrees",`${t}-${i}`)}function _S(e,t){return Me.join(We(e,t),"supervisor")}function Lu(e,t){return Me.join(_S(e,t),"state.json")}function IS(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!==dm)throw new Error(`Native Supervisor state schema must be ${dm}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Ba(t.integration.targetCommit,"Native Supervisor target commit"),Ba(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Ba(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(Ba(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Dt(e,t){try{let i=await Du.readFile(Lu(e,t),"utf8"),r=JSON.parse(i);return IS(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Pn(e,t){IS(t),await Du.mkdir(e.changesRuntimeDir,{recursive:!0}),await ee(Lu(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Ba(e,t){if(!CD.test(e))throw new Error(`${t} must be a Git commit`)}function Is(e){return structuredClone(e)}function fm(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function TS(e){Ba(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:dm,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function hm(e){let t=AD(e.parent),i=Ai(e.paths.projectRoot,t);if(!i)return null;let r=Ai(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Gt(e.paths.projectRoot).map(o=>Me.resolve(o)).find(o=>fe(o).currentBranch===t);if(!n)return null;let a=TS({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return fm(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Mu(e){if(!_s(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=Ce(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Me.resolve(t)!==Me.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let i=Ce(e.integration.worktree,["branch","--show-current"]);if(i!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${i||"(detached)"}`);return Ce(e.integration.worktree,["rev-parse","HEAD"])}async function ID(e){let t=Ai(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let i=e.state;if(Mu(i)!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{Ce(i.integration.worktree,["merge","--no-edit",i.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${i.integration.worktree}`,{cause:o})}let n=Ce(i.integration.worktree,["rev-parse","HEAD"]),a=Is(i);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},fm(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${i.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await Pn(e.paths,a),a}function TD(e,t){if(Ba(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 i=Is(e);if(t.headCommit!==i.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(i.children.some(({status:r})=>r!=="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 i.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]}},i.stateVersion+=1,i}function jS(e){let t=Mu(e);if(t===e.integration.headCommit)return e;try{Ce(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 i=Is(e);return i.integration.headCommit=t,fm(i,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),i.stateVersion+=1,i}function $S(e,t){let i=t.verification;if(i===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let r=Mu(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=i.checks.length>0&&i.checks.every(({status:o})=>o==="passed");return TD(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:i.summary.text,headCommit:r,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:i.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:i.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}async function Ts(e){let i=await Dt(e.paths,e.state.parent)??e.state;if(i.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(i.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!i.children.every(({status:v})=>v==="integrated"||v==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=Gt(e.paths.projectRoot).map(v=>Me.resolve(v)).find(v=>fe(v).currentBranch===i.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${i.integration.targetBranch}`);if(!_s(n))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let a=Ce(n,["rev-parse","HEAD"]);if((()=>{try{return Ce(n,["merge-base","--is-ancestor",i.integration.headCommit,a]),!0}catch{return!1}})()){let v=await xS({paths:e.paths,state:i,targetCommit:a});if(await AS({paths:e.paths,plan:v,targetRoot:n}),i.children.every(({status:p})=>p==="archived"))return await um(e.paths,i.parent),{state:i,targetRoot:n,targetCommit:a};let m=Is(i);for(let p of m.children)p.status="archived";return m.stateVersion+=1,await Pn(e.paths,m),await um(e.paths,i.parent),{state:m,targetRoot:n,targetCommit:a}}let c=Mu(i);if(c!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let l=Ai(e.paths.projectRoot,i.integration.targetBranch),u=(()=>{if(!l)return!1;try{return Ce(i.integration.worktree,["merge-base","--is-ancestor",l,c]),!0}catch{return!1}})();if(l!==c&&!u&&l!==i.integration.targetCommit&&await ID({paths:e.paths,state:i}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let d=await xS({paths:e.paths,state:i,targetCommit:c});l!==c&&Ce(n,["merge","--ff-only",i.integration.branch]);let f=Ce(n,["rev-parse","HEAD"]);if(f!==c)throw new Error("Native Supervisor target did not receive the verified integration head");let h=Is(i);for(let v of h.children)v.status="archived";return await AS({paths:e.paths,plan:d,targetRoot:n}),h.stateVersion+=1,await Pn(e.paths,h),await um(e.paths,i.parent),{state:h,targetRoot:n,targetCommit:f}}function OS(e,t){return Me.join(_S(e,t),"cleanup.json")}function CS(e){let t=Gt(e.paths.projectRoot).map(s=>Me.resolve(s)),i=Me.resolve(process.cwd()),r=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s})=>({root:_D(e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:Me.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=r.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(xD(s.root,i))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!_s(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=fe(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{Ce(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(_o(e.paths.projectRoot,s))try{Ce(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function xS(e){let t=OS(e.paths,e.state.parent);try{let r=JSON.parse(await Du.readFile(t,"utf8"));if(r.parent===e.state.parent&&r.targetCommit===e.targetCommit&&Array.isArray(r.worktrees)&&r.expectedBranches&&typeof r.expectedBranches=="object"&&Array.isArray(r.branches)){let n=CS(e);return{parent:r.parent,targetCommit:r.targetCommit,worktrees:[...new Set([...r.worktrees,...n.worktrees])],expectedBranches:{...r.expectedBranches,...n.expectedBranches},branches:[...new Set([...r.branches,...n.branches])]}}}catch(r){if(r.code!=="ENOENT")throw r}let i=CS(e);return await ee(t,i,{containedRoot:e.paths.changesRuntimeDir}),i}async function AS(e){for(let t of e.plan.worktrees){if(!Gt(e.paths.projectRoot).map(a=>Me.resolve(a)).includes(Me.resolve(t)))continue;let r=e.plan.expectedBranches[t];if(!r)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=fe(t).currentBranch;if(n!==r)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${r}`);Ce(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)_o(e.paths.projectRoot,t)&&Ce(e.targetRoot,["branch","-d",t])}async function um(e,t){await Du.rm(OS(e,t),{force:!0})}function HS(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var DS="children.yaml",js="comet.native.children.v1",Va="comet.native.children.v2",zS=Va,jD=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LS=new Set(["schema","children"]),$D=new Set(["schema","acceptance_index","children"]),OD=new Set(["name","depends_on","covers"]),HD=new Set(["name","summary","depends_on"]),DD=new Set(["name","depends_on","covers"]);function Bu(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function Fu(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function MS(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function pm(e,t){let i=Lt.normalize(Lt.resolve(e)),r=Lt.normalize(Lt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function LD(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function FS(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function MD(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===zS&&e.acceptance_index){let n=i.requiredAcceptanceIds??t??[],a=i.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);r.missing=n.filter(l=>!(l in e.acceptance_index)),r.extra=o.filter(l=>!a.includes(l));let s=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&r.mismatched.push(l)}let c=new Set(o);for(let l of e.children)r.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return r.uncovered=o.filter(l=>!BS(e.children,l)),VS(r)?r:null}if(e.schema===js&&t){let n=new Set(t);for(let a of e.children)r.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return r.uncovered=t.filter(a=>!BS(e.children,a)),VS(r)?r:null}return null}function BS(e,t){return e.some(i=>i.covers.includes(t))}function VS(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function vm(e){let t=new Set(e.acceptance.map(({id:n})=>n)),i=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),r=new Set(i);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&r.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])i.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...i],allowedAcceptanceIds:[...r]}}function FD(e){let t=Bu(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=Bu(n,`Native children acceptance_index.${r}`);if(Fu(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function BD(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=i.allowedAcceptanceIds??r,a=Object.keys(e),o=r.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(h=>d[h]!==u[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function VD(e,t,i={}){let r=(0,mm.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=Bu(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==js&&a!==Va)throw Fu(n,LS,"Native children contract"),new Error(`Native children schema must be ${js} or ${Va}`);let o=a===js?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Fu(n,o==="indexed-v2"?$D:LS,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,h)=>{let v=Bu(f,`Native child ${h}`);if(Fu(v,o==="indexed-v2"?DD:o==="summary-v2"?HD:OD,`Native ${s} child fields (child ${h})`),typeof v.name!="string"||!jD.test(v.name))throw new Error(`Native child ${h} name is invalid`);let m=o==="summary-v2";if(m){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:m?v.summary:null,depends_on:MS(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?MS(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let h=f.depends_on.filter(v=>!u.has(v));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}LD(c);let d=i.policy==="advisory";if(a===zS){if(o==="indexed-v2"){let f=FD(n.acceptance_index);d||BD(f,t,i);let h=Object.keys(f);return d||FS(c,h,h),{schema:Va,acceptance_index:f,children:c}}return{schema:Va,children:c}}return t&&!d&&FS(c,t),{schema:js,children:c}}async function $s(e){let t=Lt.join(e.changeDir,DS);try{await WS.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await Z({root:e.changeDir,ref:DS}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=VD(i.text,e.acceptanceIds,n);return{contract:a,hash:i.hash,size:i.size,drift:r?MD(a,e.acceptanceIds,e.validation??{}):null}}function qD(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function WD(e){let t=qD(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function JS(e){try{let t=await Z({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return WD(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function gm(e){return H("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function zD(e){let t=Gt(e.projectRoot);t.some(r=>pm(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Lt.resolve(n)))]){let n=await ye(r);n&&i.push({projectRoot:r,paths:await qe(r,n.native.artifact_root),parent:pm(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function JD(e,t){let i=Lt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ze(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function GD(e,t){let i;try{i=await WS.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Lt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ze(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function UD(e,t,i){let r=Lt.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Lt.sep}`))return null;let n=r.split(Lt.sep).join("/");try{let a=(0,mm.parseDocument)(Ce(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ct(a.toJS({mapAsMap:!1}))}catch{return null}}function KD(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function qS(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Os(e){let t=Lt.join(e.paths.changesDir,e.state.name),i=await JS(t),r=await $s({changeDir:t,validation:vm(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{},policy:"advisory"});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=gm({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!r.drift;if(r.contract.schema===Va){let p=await Dt(e.paths,e.state.name);if(!p){let S=e.state.workspace.target_branch??e.state.workspace.change_branch;if(S){let N=await hm({paths:e.paths,parent:e.state.name,targetBranch:S,contract:r.contract});N&&(p=N,await Pn(e.paths,N))}}if(p){let S=HS(p);return e.state.children_contract_hash!==n||r.drift?{...S,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:S.children.map(N=>({...N,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...S,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let b=new Map(r.contract.children.map(S=>[S.name,S])),g=r.contract.children.map(S=>({name:S.name,summary:S.summary,dependsOn:[...S.depends_on],covers:[],status:o&&S.depends_on.every(N=>r.contract.children.filter(({name:k})=>k!==S.name).every(({name:k})=>k!==N))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let S of g){if(S.status!=="ready")continue;b.get(S.name).depends_on.length>0&&(S.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:S})=>S==="ready").map(({name:S})=>S),allDone:!1}}let s=await zD(e.paths),c=new Set(r.contract.children.map(({name:p})=>p)),l=new Map,u=new Map;for(let p of s){let b=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await GD(p,c)){let S={...g,source:p,committedState:UD(p,g.file,b)};l.set(g.state.name,[...l.get(g.state.name)??[],S])}for(let g of c){let S=await JD(p,g);S&&u.set(g,[...u.get(g)??[],{source:p,state:S}])}}let d=new Map;for(let p of r.contract.children){let b=(l.get(p.name)??[]).find(({source:N,committedState:k})=>N.parent&&k?.name===p.name&&qS(k,a));if(b){d.set(p.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let g=l.get(p.name)?.[0];if(g){d.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let S=u.get(p.name)??[];S.length>1?d.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):S[0]&&d.set(p.name,KD(S[0].state,S[0].source,a))}let f=new Map(r.contract.children.map(p=>[p.name,p])),h=new Map,v=p=>{let b=h.get(p);if(b)return b;let g=f.get(p),N=g.depends_on.map(v).every(({status:P})=>P==="done"),k=d.get(p),E=k?.kind==="active"&&N?g.depends_on.filter(P=>!(l.get(P)??[]).some(({source:F,committedState:$})=>pm(F.projectRoot,k.projectRoot)&&$?.name===P&&qS($,a))):[],R,y=k?.message??null;k?.kind==="done"?(R=N?"done":"blocked",N||(y=`Native child ${p} was merged before its dependencies`)):k?.kind==="active"?(R=N&&E.length===0?"active":"blocked",N?E.length>0&&(y=`Native child ${p} does not include merged dependencies: ${E.join(", ")}`):y=`Native child ${p} started before its dependencies merged`):k?.kind==="blocked"?R="blocked":(R=o&&N?"ready":"pending",o||(y="Parent Shape confirmation is required"));let w={name:p,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:R,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:y};return h.set(p,w),w},m=r.contract.children.map(({name:p})=>v(p));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:m,readyChildren:m.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:m.every(({status:p})=>p==="done")}}var Hs="skill-coordinated";function XD(e){return e.state_version+1}function QD(e){return e.map(t=>({...t,result:"pending",reason:null}))}function ZD(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:Ti(e.summary),completed_at:e.completedAt}}function wm(e){let t=ct(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=ln(t,ZD({state:t,outcome:"recovery",summary:e.reason,completedAt:i})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?QD(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return ct({...r,phase:"build",status:"active",state_version:XD(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}import{promises as US}from"node:fs";import Ds from"node:path";function Vu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function qu(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Pi(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function GS(e,t){return e===null?null:Pi(e,t)}function zu(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function eL(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 tL(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Wu(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ym(e,t){if(e===null)return null;let i=Pi(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Nm(e,t){let i=Pi(e,t);if(!Ds.isAbsolute(i))throw new Error(`${t} must be absolute`);return Ds.resolve(i)}function iL(e,t){let i=`Native local checks[${t}]`,r=Vu(e,i);if(qu(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>Pi(l,`${i}.argv[${u}]`,!0)),a=Wu(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=ym(r.startedAt,`${i}.startedAt`),s=ym(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=zu(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Pi(r.id,`${i}.id`),name:Pi(r.name,`${i}.name`),operationId:Pi(r.operationId,`${i}.operationId`),status:a,repeatable:tL(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:zu(r.executionCount,`${i}.executionCount`),argv:n,cwd:Nm(r.cwd,`${i}.cwd`),exitCode:eL(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Pi(r.log,`${i}.log`)}}function bm(e){let t="Native local execution state",i=Vu(e,t);if(qu(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==zo)throw new Error(`Native local execution schema must be ${zo}`);let r=Vu(i.workspace,"Native local workspace");qu(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Vu(i.execution,"Native local execution");qu(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=ym(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Pi(o.operationId,"Native local execution.operationId"),stage:Wu(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Wu(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:GS(o.executionId,"Native local execution.executionId"),status:Wu(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:zu(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(iL);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:zo,change:Pi(i.change,"Native local change"),basedOnStateVersion:zu(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Nm(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Nm(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:GS(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function qr(e){return bm({schema:zo,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Ds.resolve(e.projectRoot),worktreeRoot:Ds.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Ju(e){let t;try{t=await US.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return bm(i)}async function qi(e,t,i={}){let r=bm(t);await US.mkdir(Ds.dirname(e),{recursive:!0}),await ee(e,r,i)}import{promises as rL}from"node:fs";function Wr(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
206
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Wi(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function nL(e){return e.archived?Wt(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Wt(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Wt(e.language,"Verification passed; ready to archive","验收通过,可归档"):Wt(e.language,"Verification passed","验收通过")}function aL(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Wt(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?nL(e):e.verification_result==="blocked"?Wt(t,"Blocked","已阻塞"):e.verification_result==="fail"?Wt(t,"Failed","未通过"):Wt(t,"Pending","待处理")}function oL(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Hs?Hs:"host-attested"),i=t===Hs&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":i?"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":i?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function sL(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let i=e.language,r=d=>Sd(i,d),n=(d,f)=>Wt(i,d,f),a=e.acceptance.map(d=>`| ${Wi(d.id)} | ${Wi(d.result)} | ${Wi(d.source)} | ${Wi(d.text)} | ${Wi(Wr(d.reason))} |`).join(`
|
|
207
|
+
`),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(Wr).join(" ");return`| ${Wi(Wr(d.name))} | ${Wi(f||"—")} | ${Wi(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
|
|
208
|
+
`),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${Wr(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
|
|
209
|
+
`),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${Wr(d)}`).join(`
|
|
210
|
+
`),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${Wi(Wr(d.summary))} | ${d.completed_at} |`)].join(`
|
|
211
211
|
`),u=t?.finalVerification.layers?`
|
|
212
212
|
## ${n("Supervisor evidence layers","Supervisor 分层证据")}
|
|
213
213
|
|
|
@@ -224,13 +224,13 @@ generated_from_state_version: ${e.state_version}
|
|
|
224
224
|
|
|
225
225
|
## ${r("currentResult")}
|
|
226
226
|
|
|
227
|
-
- ${n("Result","结果")}: **${
|
|
228
|
-
- ${n("Verification status","验证情况")}: **${
|
|
227
|
+
- ${n("Result","结果")}: **${aL(e)}**
|
|
228
|
+
- ${n("Verification status","验证情况")}: **${oL(e)}**
|
|
229
229
|
- ${n("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
|
|
230
230
|
- ${n("Iteration","迭代")}: ${e.verification.iteration}
|
|
231
231
|
- ${n("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
|
|
232
232
|
- ${n("Completed","完成时间")}: ${e.verification.completed_at}
|
|
233
|
-
- ${n("Summary","摘要")}: ${
|
|
233
|
+
- ${n("Summary","摘要")}: ${Wr(e.verification.summary)}
|
|
234
234
|
|
|
235
235
|
## ${r("acceptance")}
|
|
236
236
|
|
|
@@ -260,27 +260,28 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
|
|
|
260
260
|
|
|
261
261
|
`:""}## ${r("conclusion")}
|
|
262
262
|
|
|
263
|
-
${
|
|
264
|
-
`}function ZD(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function Vu(e){let t;try{t=await UD.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=ZD(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function qu(e){await he(e.file,QD(e.state,e.supervisor))}var VS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eL="comet-state.yaml",tL="state.json",jY=Xs("en");function Lt(e,t){if(!VS.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=qr.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}function Pt(e,t){return qr.join(Lt(e,t),eL)}function Wr(e,t){return qr.join(We(e,t),tL)}async function zr(e,t){try{let i=await Sn.readFile(Pt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function qS(e){return fe(e).currentBranch}async function En(e,t){return Ze(Pt(e,t))}async function WS(e){let t=await sn({file:Pt(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 i=qr.join(Lt(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await Sn.rm(i,{force:!0})}return t}async function iL(e){let t=Lt(e.paths,e.state.name),i=qr.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Sn.readdir(i,{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(!VS.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=qr.join(t,...s.split("/")),l=await Sn.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=qr.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await Sn.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function rL(e){let t=Lt(e.paths,e.state.name),i=await Z({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return yl({briefMarkdown:i.text,specs:r})}async function zS(e){let t=await iL(e),i=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let u=e.state.spec_changes[l];return u!==void 0&&c.capability===u.capability&&c.source===u.source&&(c.operation===u.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await rL({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Hy(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await um({changeDir:Lt(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:lm({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?dm({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function JS(e){let t=await En(e.paths,e.name),i=await Ei(e.paths,e.name),r=await ia(e.paths,{kind:"archive",change:e.name}),n=r?.kind==="archive"?r:null;if(n&&i?.finalVerification.status==="pending"){if(n.journal.status!=="prepared"||n.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await Sn.rm(n.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||i?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=RS(i);if(n||a.stateVersion!==i.stateVersion){let o=await nL({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return n&&await Sn.rm(n.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await kn(e.paths,CS(i,t)),{state:t,action:"recorded-final-verification"}}async function GS(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...on(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ii(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await WS({paths:e.paths,previous:t,next:r});return await qi(Wr(e.paths,t.name),Br({portableState:n,projectRoot:e.paths.projectRoot,branch:qS(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function nL(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 r={...on(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ii(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 WS({paths:e.paths,previous:t,next:r});return await qi(Wr(e.paths,t.name),Br({portableState:n,projectRoot:e.paths.projectRoot,branch:qS(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Wu(e){if(e.state.verification===null)return"not-applicable";let t=qr.join(Lt(e.paths,e.state.name),"verification.md");return await Vu({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await qu({file:t,state:e.state}),"rebuilt")}async function US(e){let t=await En(e.paths,e.name),i=Wr(e.paths,e.name);try{let r=await Bu(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var BY=16*1024;async function zu(e){let t=await tm(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Zl(t.selection.change),t.selection)}function KS(e){return _u(e.projectRoot)}async function $s(e,t){return await Yn(e.projectRoot),gS(e.projectRoot,"native",t)}var v4=16*1024*1024,Ju=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Os=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function XS(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Fa.resolve(e.nativeRoot,...i.target.split("/"))}async function QS(e,t,i){let r=await kr(e,t.id);if(r.some(p=>p.type==="archive-finalized"))return;let n=r.some(p=>p.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let p=t.operations.find(g=>g.id==="archive-change");if(!p||p.type!=="move"||!p.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let b=await ai(XS(e,t));if(b?.kind!=="directory"||b.hash!==p.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=XS(e,t),o=Fa.join(a,Ie),s=await fb(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=H(e,s.name),l=await Oe(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let p=Km(Ni,l,new Set,_p,void 0);if(!p.action)throw new Error(p.reason??"Native archive produced no action");u=Ym(Ni,p.state,{actionId:p.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},_p,void 0)}let d=L(`archive:${t.id}:${s.name}`),f=await it(c,u.trajectoryRef),h=f.filter(p=>p.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(p=>p.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=h.find(p=>p.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!aL(v.data,m)||v.runId!==u.runId||v.timestamp!==t.createdAt||v!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||h.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await Au(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await sa(e,t,"archive-finalization-started")),!s.archived){let p={...s,archived:!0};await db(o,p)}v||(v=await jr({changeDir:c,run:u,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await yn({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await hn(c,u),await $s(e,s.name),t.schema==="comet.native.transaction.v2"?await Au(e,t,"archive-finalized"):await sa(e,t,"archive-finalized")}async function vm(e,t){let i=We(e,t);try{let r=await YS.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await YS.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function oL(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await kr(e,t.id)).some(c=>c.type==="operation-started")){let c=await Pu({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new Os(c,"Native Archive facts changed before the first transaction operation")}let o=await hS(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await De(e,t.change),u=await Eu({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await QS(e,o,i);let s=await Au(e,o,"commit");return{journal:s,runtimeCleanupWarning:await vm(e,s.change)}}let r=await sN(e,t);await QS(e,r,i);let n=await sa(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await vm(e,n.change):null}}function sL(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Fa.resolve(t.projectRoot)!==Fa.resolve(e.projectRoot)||Fa.resolve(t.nativeRoot)!==Fa.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function ZS(e){return se(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await pr(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await yt(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await Zp(e.paths,e.transactionId):i;return sL(e.paths,r),r.status==="committed"?(r.change&&await vm(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await oL(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?pS(e.paths,r):Ol(e.paths,r)}finally{await mr(t)}},{allowedTransactionId:e.transactionId})}import{promises as kL}from"fs";async function eE(e,t){let i=[],r=H(e,t.name),n=fr(r,Nt.stateRef),a;try{a=await Oe(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=fr(r,a.trajectoryRef),s=await ma(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await it(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=fr(r,a.checkpointRef);try{let u=await pa(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var cL=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function lL(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function uL(e){return e?e.map(lL).join(" "):null}function dL(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function Mt(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function fL(e){return e.map(t=>Mt(t,[],null))}function hL(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[Mt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(Mt("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(Mt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Mt("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(Mt("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(Mt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Mt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Ke(e,t){let i=t.commandArgs===void 0?dL(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?uL(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??fL(t.requiredInputs??[])}}function Gu(e){let i=(e.findings??[]).filter(d=>!va(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||cL.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return Ke(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Mt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Ke(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Mt("summary",["--summary"],"<summary>")]});if(n)return Ke(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Mt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Ke(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Mt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Ke(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Ke(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=hL(e.state);return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Hs from"path";var tE=8,pL={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function mL(e){let t=pL[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:va(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function vL(e,t,i){if(!i.path)return null;let r;if(Hs.isAbsolute(i.path)?r=Hs.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Hs.resolve(ne(e,t.name),...i.path.split(/[\\/]/u)):r=Hs.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!O(e.projectRoot,r))return null;let n=Hs.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function gL(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function gm(e){return e.findings.map(t=>{let i=mL(t.code);return{code:t.code,message:t.message,severity:i.severity,path:vL(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:gL(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function wm(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,tE),truncated:t.length>tE}}var iE=240,rE=8,Uu=50;function nE(e){let t=Array.from(e);return t.length<=iE?e:`${t.slice(0,iE-1).join("")}…`}function wL(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function yL(e){let t=[...new Set(e.map(wL))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,rE),reasonCount:e.length,codesTruncated:t.length>rE};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Uu),reasonsTruncated:e.length>Uu}}}async function aE(e){let t=null;try{let s=await Dr(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Hr(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Hr(e.paths,e.state.name)}}let i=await Wk({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=yL(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Or.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:nE(i.checkpoint.summary),nextAction:nE(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Or.maxArtifacts}}async function NL(e,t){let i=H(e,t.name),r=await Oe(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await pa(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await it(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function bL(e,t){let i=await NL(e,t);return{committed:i,latest:Nk(i),history:yk(i)}}async function oE(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await bL(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var SL=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Ba=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function ym(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function EL(e){return(await zu(e))?.change??null}function PL(e,t,i=!1,r){return Gu({state:e,archiveReady:t,evidenceRetreat:i}).command}async function RL(e,t){let i=ne(e,t.name),r=[...(await rp(i,t.brief)).findings,...(await gb(e,t)).findings,...await eE(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await ha(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Vl(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await ja({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Bi(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await np(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function Nm(e,t,i){let r=await EL(e)===t,n=await Do(e,t),a=await ZN(e,t),o;try{let w=await vi(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=gm({paths:e,state:o,findings:[w]}),F=Gu({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:F.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:wm(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:F,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await aE({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await oE(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await ja({changeDir:ne(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Be=await Ta(e,o.name,o.verification_evidence);for(let ue of Be.acceptanceTrace.entries)P.set(ue.acceptanceId,ue.status==="failed"?"failed":ue.status==="missing"?"missing":"satisfied")}let F=Ay({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),$=F.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",F.nextCursor,"--project-root",e.projectRoot]:null;u={...F,...$?{nextPageCommand:ym($),nextPageArgs:$}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await hu(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await kt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let P=await wa({paths:e,identity:w});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await is({paths:e,identity:w});f.push(...P.findingCodes.map(F=>({code:F,message:`Native workspace advisory changed: ${F} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],v=!1;if(o.phase==="verify"){let w=await Zk({paths:e,state:o});v=w.freshness!=="fresh",h.push(...w.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let m=null,p=[];if(o.phase==="archive")try{m=await Pu({paths:e,name:o.name}),p.push(...m.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{p.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let b=[...await RL(e,o),...s.findings,...d,...f,...h,...l,...p].filter((w,P,F)=>F.findIndex($=>$.code===w.code&&$.path===w.path)===P),g=gm({paths:e,state:o,findings:b}),y=g.filter(w=>!va(w.code)),E=o.phase==="archive"&&m?.ready===!0&&y.length===0,k=v||o.phase==="archive"&&(m?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),S=g.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",N=g.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:S||R?null:PL(o,E,k,i?.clarificationMode),archiveReady:E,inspection:s.inspection,findingSummary:wm(g),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Gu({state:o,findings:g,archiveReady:E,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:g.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Uu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:g.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...N?{error:N.message}:{}}}async function CL(e){let t;try{t=await Zt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await kL.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Ba.maxChanges))throw new Error(`Native status exceeds ${Ba.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function Ku(e,t){let i=t.toString(36),r=D("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function xL(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=SL.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=D("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function AL(e,t){let i=await CL(e),r=D("comet.native.status-names.v1",i),n=xL({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Ba.maxItems).map(u=>Nm(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,h={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:f<i.length?Ku(r,f):null,nextPageCommand:f<i.length?ym(["comet","native","status","--cursor",Ku(r,f)]):null,nextPageArgs:f<i.length?["comet","native","status","--cursor",Ku(r,f)]:null,limits:{...Ba}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>Ba.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s<i.length?Ku(r,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:i.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?ym(l):null,nextPageArgs:l,limits:{...Ba}}}async function bm(e,t){return(await AL(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as UL,randomUUID as KL}from"node:crypto";import{constants as Rm,promises as Q}from"node:fs";import le from"node:path";var Qu=Tn(en(),1);import{randomUUID as _L}from"crypto";import{promises as dE}from"fs";import Sm from"path";import{isDeepStrictEqual as Em}from"util";var Pn=/^[a-f0-9]{64}$/u,TL=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),IL=new Set(["sourceHash","targetHash","nextJournal"]),jL=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),sE=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),$L=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Yu(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function cE(e){return JSON.stringify(e,null,2)+`
|
|
265
|
-
`}function
|
|
266
|
-
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===be?Va(a,u.previousState)||Va(a,u.nextState):a.schema===Ne&&(uE(a,u.previousState)||uE(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==Ne)throw new Error("Schema migration transition supersede target schema is invalid");s=DL(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Yu(i.runRetreat,$L,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=Rr(l.previousRun),d=Rr(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!Pn.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==Ne||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Ls(e,t){let i=Ds(e,t),r=j(e,i);await T(r,i);try{let n=await xl({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return LL(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ML(e,t,i){let r=await ha(e,t),n=r?await Vl(e,r):await ql(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=qh(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new ya(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await Jh(e,t,n)}async function fE(e){try{return await ei(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function FL(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function hE(e,t){let i=t.transitionSupersede,r=H(e,t.change),n=await it(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!Em(o.event,FL(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function BL(e,t,i){if(!t.transitionSupersede)return;let r=Ue(e,t.change),n=await fE(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=H(e,t.change),o=await Oe(a),s=await hE(e,t),c=await pa(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!zi(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==L(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function VL(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=H(e,t.change),a=await Oe(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!zi(a,r.nextRun)){if(!zi(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await hn(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!zi(await Oe(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await hE(e,t);if(o.sequence===null){let l=await jr({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await yn({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=Ue(e,t.change),c=await fE(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await dE.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function qL(e,t,i){if(!t.runRetreat)return;let r=H(e,t.change),n=await Oe(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!zi(n,t.runRetreat.nextRun)){if(!zi(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await hn(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await it(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await jr({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await yn({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function WL(e,t,i){let r=await Ls(e,t);if(!r)return null;if(await ba(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=Sm.join(ne(e,t),Ie),a=await ei(n);if(await BL(e,r,a===r.targetHash),await ML(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await he(n,(0,Qu.stringify)(Pm(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=Ue(e,t),s=await ei(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await ee(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await VL(e,r,i),await qL(e,r,i),await dE.rm(Ds(e,t),{force:!0}),r.nextState}async function zL(e){let t=H(e.paths,e.state.name),i=await Oe(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=L(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:be,toSchema:Ne,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function JL(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=Va(i,t.previousState),a=Va(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=H(e.paths,i.name),s=await Oe(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&zi(s,t.previousRun),l=zi(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await it(o,t.nextRun.trajectoryRef)).map((b,g)=>({event:b,index:g})).filter(({event:b})=>b.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let b={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!Em(f.event,b)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...Xu(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},v=s,m=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,p=L(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await ei(Ue(e.paths,i.name)),transitionId:t.id,previousRun:v,nextRun:m,evidenceHash:p,eventData:{fromSchema:be,toSchema:Ne,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function GL(e){let t,i,r,n;if(e.state.schema===et){if(t=km(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==cn)throw new Error("Native v1 change has a transition from another schema generation");let s=OL(e.pendingTransition.journal);if(lE(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(lE(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=Ue(e.paths,e.name);i={sourceHash:await ei(c),targetHash:L(cE(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==ji)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await JL({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=HL(s);if(Va(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Va(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=Ue(e.paths,e.name);i={sourceHash:await ei(u),targetHash:L(cE(l)),nextJournal:l}}}else t=Xu(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await zL({paths:e.paths,state:e.state,migrationId:e.id}));let a=Sm.join(ne(e.paths,e.name),Ie),o=(0,Qu.stringify)(Pm(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===et?be:Ne,sourceHash:await ei(a),targetHash:L(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function pE(e){return se(e.paths,`migrate schema for ${e.name}`,()=>Nn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await WL(e.paths,e.name,e.hooks);if(i?.schema===Ne)return i;let r=await vi(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await ba(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==et&&n.schema!==be)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Mp(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await GL({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??_L()}),s=Ds(e.paths,e.name),c=j(e.paths,s);await T(c,s),await ee(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Ji=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),YL=512*1024,Rn=/^([a-f0-9]{64})\.json$/u,XL=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,QL=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Zu=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function xm(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ri(e,t){return xm(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function yE(e,t){return xm(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function qa(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function nt(e,t){return e<t?-1:e>t?1:0}function ZL(e,t){let i=le.relative(e.projectRoot,t);if(i.length===0||le.isAbsolute(i)||i===".."||i.startsWith(`..${le.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(le.sep).join("/")}function NE(e,t){return le.join(H(e,t),"evidence")}function ed(e,t){return ZL(e,NE(e,t))}async function td(e,t){let i=le.resolve(e),r=le.resolve(t);if(!O(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=le.relative(i,r).split(le.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=le.join(o,s));let c=await Q.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await Q.realpath(o);if(a.length>0&&!O(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...qa(c)})}return a}async function Ft(e){for(let t of e){let i=await Q.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!xm(t,i)||await Q.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function bE(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:_a(e,t)}function mE(e){return e!==null&&QL.test(e)?[e]:[]}function eM(e,t,i,r){if(e==="snapshots")return{canonical:Ea(i,t),dependencies:[]};if(e==="scopes"){let a=Pa(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=cu(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[_a("scopes",a.scopeHash)]}}if(e==="verifications"){let a=vs(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(mE));return{canonical:a,dependencies:[a.implementationScopeRef,lk(a.reportHash),...mE(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||UL("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=uu(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=lu(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Jr(e){let t=await Q.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?YL:Ir;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await Q.realpath(e.file);if(!O(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Rm.O_RDONLY|Rm.O_NOFOLLOW|Rm.O_NONBLOCK,a=await Q.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Ft(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!Ri(qa(t),o)||!Ri(qa(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let g=i+1-d,y=await a.read(u,0,Math.min(u.length,g),null);if(y.bytesRead===0)break;if(d+=y.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,y.bytesRead)))}let[f,h,v]=await Promise.all([a.stat(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Ft(e.directoryChain),!h.isFile()||h.isSymbolicLink()||v!==r||!Ri(qa(o),f)||!Ri(qa(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let m=Buffer.concat(l,d).toString("utf8"),p;try{p=JSON.parse(m)}catch(g){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:g})}let b=eM(e.kind,e.hash,p,e.name);if(m!==JSON.stringify(b.canonical,null,2)+`
|
|
267
|
-
`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:qa(f),directoryChain:e.directoryChain,dependencies:[...new Set(b.dependencies)].sort(nt)}}finally{await a.close()}}async function vE(e){try{return await Q.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function tM(e){let t=H(e.paths,e.name),i=t,r=NE(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await td(t,r);n=await Q.readdir(r,{withFileTypes:!0}),await Ft(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of Zu){if(!n.some(f=>f.name===s))continue;let c=le.join(r,s),l=await td(t,c),u=(await Q.readdir(c,{withFileTypes:!0})).sort((f,h)=>nt(f.name,h.name)),d=new Map;for(let f of u){let h=XL.exec(f.name);if(!h)continue;let v=d.get(h[1])??[];v.push(f),d.set(h[1],v)}for(let[f,h]of[...d.entries()].sort(([v],[m])=>nt(v,m))){if(h.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let v=h[0];if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${v.name}`);let m=le.join(c,f),p=Rn.exec(f)?.[1];if(!p)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let b=bE(s,p),g=le.join(c,v.name),y=await Jr({changeRoot:i,file:g,ref:b,kind:s,hash:p,name:e.name,directoryChain:l}),E=await vE(m),k=E?null:await Jr({changeRoot:i,file:m,ref:b,kind:s,hash:p,name:e.name,directoryChain:l});a.push({ref:b,original:m,quarantine:g,document:y,action:E?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(nt);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Wa(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${id(o)}`),path:ed(e.paths,e.name)}]};for(let s of a.sort((c,l)=>nt(c.ref,l.ref))){if(await Ft(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Jr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:Rn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Jr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:Rn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!Ri(s.originalDocument.identity,d.identity)||!Ri(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await Q.rm(s.quarantine),await Ft(s.document.directoryChain);continue}if(!await vE(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await Q.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!Ri(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await Q.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Jr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:Rn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Jr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:Rn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!yE(s.document.identity,l.identity)||!Ri(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await Q.rm(s.quarantine),await Ft(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Wa(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${id(o)}`),path:ed(e.paths,e.name)}]}}async function iM(e,t){let i=H(e,t),r=i,n=le.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await td(i,n);a=await Q.readdir(n,{withFileTypes:!0}),await Ft(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!Zu.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(nt);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${id(o)}`);let s=[],c=0;for(let l of Zu){if(!a.some(h=>h.name===l))continue;let u=le.join(n,l),d=await td(r,u),f=(await Q.readdir(u,{withFileTypes:!0})).sort((h,v)=>nt(h.name,v.name));await Ft(d);for(let h of f){if(s.length>=Ji.maxDocuments)throw new Error(`Native evidence store exceeds ${Ji.maxDocuments} documents`);let v=Rn.exec(h.name);if(!v||!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${h.name}`);let m=bE(l,v[1]),p=le.join(u,h.name);await T(j(e,p),p);let b=await Jr({changeRoot:r,file:p,ref:m,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=b.size,c>Ji.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Ji.maxScannedBytes} scanned bytes`);s.push(b)}await Ft(d)}return s}function gE(e,t){let i=new Set,r=[...e].sort(nt).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(nt).reverse())i.has(o)||r.push(o)}return i}function rM(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(nt),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(nt))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function nM(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=gE(t,r),a=new Set(n);for(let c of e)i-c.mtimeMs<Ji.minimumAgeMs&&a.add(c.ref);for(let c of Zu){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||nt(u.ref,d.ref)).slice(0,Ji.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=gE(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Ji.minimumAgeMs).sort((c,l)=>nt(c.ref,l.ref));return{candidates:rM(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function id(e){let t=e.slice(0,Ji.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Wa(e){let t=Ji.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Cm(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(nt);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Wa(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${id(n)}`),path:r}}async function wE(e,t){try{await Q.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await Q.rename(e,t)}catch{}}async function aM(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Ft(e.directoryChain);let i=await Jr({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:Rn.exec(le.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await Q.lstat(e.file),n=await Q.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!Ri(e.identity,r)||!Ri(e.identity,i.identity)||!O(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=le.join(le.dirname(e.file),`.${le.basename(e.file)}.${KL()}.gc`);await Q.rename(e.file,a);try{let[o,s]=await Promise.all([Q.lstat(a),Q.realpath(a)]);if(await Ft(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!yE(e.identity,o)||!O(e.directoryChain[0].realPath,s))throw await wE(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await Q.rm(a),await Ft(e.directoryChain)}catch(o){throw await wE(a,e.file),o}}async function oM(e){if((await ye(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await Q.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await yt(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function sM(e,t){if(t)return[t];let i;try{i=await Q.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(nt)}async function cM(e,t){let i=await vi(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Bi(e,t),Ls(e,t),Dr(e,t)]);return r!==null||n!==null||a!==null}async function lM(e){if(await cM(e.paths,e.name))return[];let t=await vi(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await tM({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await iM(e.paths,e.name),a=nM(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=ed(e.paths,e.name);if(!e.repair)return[...i.findings,Cm(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await aM(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Cm(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Wa(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Cm(e.name,a,!0,o)]}async function kE(e){if(e.deferAll||await oM(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await sM(e.paths,e.name))try{a.push(...await lM({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Wa(`Native evidence retention refused to clean ${o}: ${s.message}`),path:ed(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await se(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Wa(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as uM,randomUUID as K6}from"crypto";import{promises as Bs}from"fs";import ae from"path";var _m=64*1024*1024,dM=256*1024,RE=16*1024*1024;async function at(e){try{return await Bs.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function fM(e){let t;try{t=await Bs.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await kt(e,i.name);if(r){await Xl({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function Fs(e,t){let i=[];async function r(n){let a=await wt({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ae.join(n,s.name);if(t.excludedFiles?.has(ae.resolve(c))){await a.verify();continue}let l=await Bs.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await re({root:e,file:c,maxBytes:_m,label:`Native root file ${ae.relative(e,c)}`});i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function hM(e,t,i,r){await fi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await wt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ae.join(a,l.name);if(ae.resolve(u)===ae.resolve(i)){await s.verify();continue}let d=await Bs.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ae.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await fi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await Nr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:_m,label:`Native root move file ${ae.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function za(e,t,i,r){let n=await Fs(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ae.resolve(i)]):void 0}),a=await Fs(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ae.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function pM(e,t){return ae.join(e.artifactRoot,`.comet-native-move-${t}`)}function mM(e,t){return ae.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function vM(e){return`${e}.removing`}function SE(e,t){return ae.join(ae.dirname(e),`.${ae.basename(e)}.${t}.rollback-removing`)}function CE(e,t,i){return ae.join($l(e,t).directory,`root-move-cleanup-${i}.json`)}function gM(e){return JSON.stringify(e,null,2)+`
|
|
268
|
-
`}function wM(e){return uM("sha256").update(e).digest("hex")}function yM(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ae.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function NM(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(yM);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ae.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function bM(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=gM(t);if(Buffer.byteLength(i,"utf8")>RE)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await he(CE(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),wM(i)}async function kM(e){let t=await re({root:e.paths.runtimeDir,file:CE(e.paths,e.id,e.cleanup.kind),maxBytes:RE,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return NM(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Am(e){let t=await Fs(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function EE(e){return e.ref.split("/").length}async function SM(e){let i=[...await Am({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>EE(a)-EE(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ae.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await Al({root:e.projectRoot,file:a,maxBytes:_m,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await Ch({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Am({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Ch({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function xE(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function EM(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function PM(e,t,i,r){for(let a of[e,t])try{let o=await yt(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ae.join(i,"runtime","transactions",r,"transaction.json");try{let a=await re({root:i,file:n,maxBytes:dM,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function PE(e){let t=xE(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await hr(e.projectRoot,t),t}async function Ms(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=xE(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await hr(e.projectRoot,i),i}async function rd(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await at(e.target),a=await at(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await bM({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Fs(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await Ms({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await kM({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await at(e.target),a=await at(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await Ky({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Ms({projectRoot:e.projectRoot,config:t,id:e.id})}return await Am({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await Ms({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await Ms({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await SM({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Ms({projectRoot:e.projectRoot,config:t,id:e.id})}async function RM(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await at(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=vM(e.staging);t=await rd({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await Fs(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ae.resolve(e.lockFile)])}),await hM(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await za(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await PE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await at(e.destinationPaths.nativeRoot)){if(await at(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await za(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await at(e.staging))throw new Error("Native move staging tree is missing");await za(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Bs.rename(e.staging,e.destinationPaths.nativeRoot)}t=await PE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await at(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=mM(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await at(e.sourcePaths.nativeRoot)&&await za(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await rd({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await fM(e.destinationPaths);let n=await yt(e.destinationPaths,e.pending.id);await sa(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await hr(e.projectRoot,o),o}async function AE(e){let t=await ye(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await qe(e.projectRoot,i.fromArtifactRoot),n=await qe(e.projectRoot,i.toArtifactRoot),a=pM(n,i.id),o=await at(r.nativeRoot)?r:n,s=await pr(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await PM(r,n,a,i.id)}catch(v){if(i.stage!=="copying"||!await at(r.nativeRoot))throw v;let m=EM({id:i.id,paths:r,now:new Date});await aN(r,m),c={journal:m,paths:r}}if(e.strategy==="continue"){let v=await RM({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:v}}if(!await at(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=SE(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await at(n.nativeRoot)&&await za(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await rd({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=SE(a,i.id);!t.native.pending_root_move?.cleanup&&await at(a)&&await za(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await rd({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await yt(r,i.id);await Ol(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},h={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await hr(e.projectRoot,h),{activeNativeRoot:r.nativeRoot,config:h}}finally{await mr(s)}}var Ja=4096,CM=4096,xM=1024;async function Gr(e,t,i){try{let r=await wt({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function ad(e,t){let i=new Map(e.map(r=>[je.resolve(r.file),{...r,file:je.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await Lo(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await mh(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function AM(e,t){let i=KS(e),r;try{await T(e.projectRoot,i);let n=await zu(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await zr(e,r.change)?[]:(await De(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await nd.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function _M(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function TM(e,t){let i=[],r=[];for(let n of await Gr(e,e.transactionsDir,CM)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await yt(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:je.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await Xn([e],`doctor archive recovery ${a.id}`,async()=>await ad([{paths:e,file:je.join(e.locksDir,"root-move.lock")},{paths:e,file:je.join(e.locksDir,"archive.lock")}],i)?(await ZS({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function IM(e,t,i){let r=[];for(let n of await Gr(e,e.locksDir,xM)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=je.join(e.locksDir,n.name);try{let o=await Lo(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await mh(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function jM(e,t,i=5){let r=[],n=t?await bm(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await bm(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:je.join(e.changesDir,a.name,Ie)});continue}let o=await Nm(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:je.join(e.projectRoot,s.path)}:{}})}return r}async function $M(e,t){let i=[],r=t.name?[t.name]:(await Gr(e,e.changesDir,Ja)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await ma(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await WN(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:je.join(H(e,n),"trajectory.jsonl")})}return i}async function OM(e,t){let i=[],r=t.name?[t.name]:(await Gr(e,e.changesDir,Ja)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await Do(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=nn(e,n),s=We(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await Xn([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Zt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await nd.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Zt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await nd.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await nd.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function HM(e,t){let i=[],r=t.name?[t.name]:(await Gr(e,e.changesDir,Ja)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await Qh(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:ga(e,n),repair:"migrate"});continue}let a=await De(e,n);await tb({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:ga(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:ga(e,n)})}return i}async function DM(e,t){let i=[],r=t.name?[t.name]:(await Gr(e,e.changesDir,Ja)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Ds(e,n);try{let o=await Ls(e,n),s=await vi(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:je.join(e.changesDir,n,Ie)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:je.join(e.changesDir,n,Ie),repair:"migrate"});continue}await pE({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:je.join(e.changesDir,n,Ie)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function LM(e,t){let i=[],r=t.name?[t.name]:(await Gr(e,e.changesDir,Ja)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Bi(e,n)}catch(o){if(o instanceof ks)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Ue(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Xn([e],`doctor transition recovery ${n}`,async()=>await ad([{paths:e,file:je.join(e.locksDir,"root-move.lock")},{paths:e,file:je.join(e.locksDir,`transition-${n}.lock`)}],i)?(await $k(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:Ue(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Ue(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:Ue(e,n),repair:"continue"})}}return i}async function MM(e,t){let i=[],r=t.name?[t.name]:(await Gr(e,e.changesDir,Ja)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Hr(e,n),o;try{o=await Dr(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await Xn([e],`doctor checkpoint recovery ${n}`,async()=>await ad([{paths:e,file:je.join(e.locksDir,"root-move.lock")},{paths:e,file:je.join(e.locksDir,`transition-${n}.lock`)}],i)?(await Jk(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function Vs(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await ye(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([qe(r.projectRoot,c.fromArtifactRoot),qe(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await ad([{paths:l,file:je.join(l.locksDir,"root-move.lock")},{paths:u,file:je.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await AE({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await qe(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await _M(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await TM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await OM(r,{name:e.name,repair:t})),i.push(...await DM(r,{name:e.name,repair:t})),i.push(...await HM(r,{name:e.name,repair:t})),i.push(...await $M(r,{name:e.name,repair:t})),i.push(...await LM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await MM(r,{name:e.name,repair:t})),i.push(...await kE({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await IM(r,t,s.unfinished)),i.push(...await AM(r,t)),e.projectOnly||i.push(...await jM(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{randomUUID as FM}from"node:crypto";import{promises as Fe}from"node:fs";import ht from"node:path";var Tm=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function _E(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function TE(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=ht.join(e.archiveDir,t);if(!O(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function od(e){try{return await Fe.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function IE(e,t){let i=ht.normalize(ht.resolve(e)),r=ht.normalize(ht.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function BM(e,t){let i;try{i=await Fe.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=ht.join(e.archiveDir,n.name);try{let o=await Ze(ht.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function VM(e,t){let i=await ia(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function Cn(e,t){await Fe.mkdir(e.transactionsDir,{recursive:!0}),await ee(gr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function qM(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Jt(e.paths.projectRoot);i.some(a=>IE(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await ye(a);if(!o)continue;let s=await qe(a,o.native.artifact_root);r.some(c=>IE(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await Fe.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await Ze(ht.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await iu(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function WM(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function zM(e){let t=ht.join(e.paths.specsDir,e.change.capability),i=ht.join(t,"spec.md");if(!O(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await Fe.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await Fe.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([Fe.realpath(e.paths.specsDir),Fe.realpath(t)]);if(!O(o,s))throw new Error("Native canonical capability path escaped");try{let c=await Fe.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Fe.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await Fe.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=ht.join(Lt(e.paths,e.state.name),e.change.source);await he(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await Fe.mkdir(t,{recursive:!0}),await he(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function jE(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function JM(e,t){let i=Lt(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await Z({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function GM(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(jE(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Im(e){return se(e.paths,`archive portable change ${e.name}`,async()=>{let t=WM(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await VM(e.paths,e.name),r=Lt(e.paths,e.name),n=await od(r),a=n?null:await BM(e.paths,e.name),o;if(n)o=await En(e.paths,e.name);else if(i)o=await Ze(ht.join(TE(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await Ei(e.paths,e.name);if(n&&!o.archived&&i===null){let d=await zS({paths:e.paths,state:o});if(d.drifted){let f=d.reason??"Native confirmed requirements changed";throw await GS({paths:e.paths,state:o,reason:f}),new Error(`${f}; Native change returned to Shape and requires confirmation`)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let d=await JS({paths:e.paths,name:e.name});if(o=d.state,d.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");d.action==="recorded-final-verification"&&(s=await Ei(e.paths,e.name))}let c=TE(e.paths,i?.archive_ref??_E(o)),l=await od(c);if(i&&GM(i,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await $s(e.paths,o.name),await Fe.rm(We(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)jE(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let d=await qM({paths:e.paths,state:o});if(!o.archived&&d.length>0&&t!==o.name)throw new Tm(d);i={schema:Rl,id:FM(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:_E(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await JM(e.paths,o),created_at:new Date().toISOString()},await Cn(e.paths,i)}if(!n&&l&&i.status==="report-aligned")i={...i,status:"moved"},await Cn(e.paths,i);else if(!n&&l&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);let u=!1;if(i.status==="prepared"&&s&&!o.archived&&(s=(await As({paths:e.paths,state:s})).state,u=!0),i.status==="prepared"){for(let d=i.next_spec_index;d<i.spec_changes.length;d+=1)await zM({paths:e.paths,state:o,change:i.spec_changes[d]}),i={...i,next_spec_index:d+1},await Cn(e.paths,i),await e.hooks?.afterSpecApplied?.(d);i={...i,status:"specs-applied"},await Cn(e.paths,i)}if(i.status==="specs-applied"){if(s&&!o.archived&&!u&&(s=(await As({paths:e.paths,state:s})).state,u=!0),!o.archived){let d={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await sn({file:Pt(e.paths,o.name),expectedStateVersion:o.state_version,next:d,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await Cn(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let d=await od(r)?r:c;if(await qu({file:ht.join(d,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Vu({file:ht.join(d,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await Cn(e.paths,i),s&&!u&&(await As({paths:e.paths,state:s}),u=!0),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(s&&!u&&await As({paths:e.paths,state:s}),await Fe.mkdir(e.paths.archiveDir,{recursive:!0}),await od(c))throw new Error(`Native Archive target already exists: ${c}`);await Fe.rename(r,c),i={...i,status:"moved"},await Cn(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await $s(e.paths,o.name),await Fe.rm(We(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await Fe.rm(gr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function xn(e,t,i){return e.language==="zh-CN"?i:t}function UM(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:xn(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:xn(e,"Reply A or B","回复 A 或 B"),agentInstruction:xn(e,"Relay the two coordination choices and wait for the user decision. Do not treat a generic confirmation as a mode selection or run --confirmed without --coordination-mode.","转述这两个推进方式并等待用户选择。不要把普通“确认”视为已选择推进方式,也不要在没有 --coordination-mode 时运行 --confirmed。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i(xn(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(xn(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return i(xn(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 $E(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function qs(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function OE(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function KM(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function YM(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function XM(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--confirmed","--expected-state-version",String(e.stateVersion),"--expected-action","confirm-shape"]}function An(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:$E({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[qs("summary","--summary"),OE(e.name,e.flag)]}}function jm(e){return[An({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),An({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function sd(e,t){let i=YM(t)&&e.coordination_mode===void 0,r={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:UM(e,i)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...r,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...r,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[qs("summary","--summary")],commandAlternatives:[An({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...jm({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...r,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[qs("summary","--summary")],commandAlternatives:[An({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),An({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...r,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[qs("summary","--summary")],commandAlternatives:[An({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...jm({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...r,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[qs("summary","--summary")],commandAlternatives:jm({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...r,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:n("none")};if(e.status==="blocked"){let a=e.blockers.some(({resolution_action:o})=>o==="retry-verifier");return{...r,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?$E({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:a?["summary"]:["repair-runtime"],inputOptions:a?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:n(a?"retry-verifier":"none")}}if(e.phase==="shape")return{...r,disposition:i?"await-user":"continue",action:"confirm-shape",commandArgs:XM({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[KM("coordination-mode","--coordination-mode",Dy)]:[],OE("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...r,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:n("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...r,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...r,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")};let a=t.children.some(({status:s})=>s==="blocked"||s==="needs-reverify"),o=t.children.some(({status:s})=>s==="ready"||s==="active");return{...r,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...r,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")}}if(e.phase==="verify"){let a=e.loop.next_action==="await-verifier-result",o=!!e.children_contract_hash,s={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...r,userCommunication:!a&&o?{...r.userCommunication,agentInstruction:`${r.userCommunication.agentInstruction} ${xn(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:r.userCommunication,disposition:"continue",action:a?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[a?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:a?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[s]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:o?[s]:[]}}],runnerAction:n(a?"await-verifier":"dispatch-verifier")}}return e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived?{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[An({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}import{randomUUID as QM}from"node:crypto";import{promises as Ga}from"node:fs";import VE from"node:path";var $m=["evidence.md","repair.md","archive.md","checkpoint.md"],ZM="verification.md";async function eF(e){try{return await Ga.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Om(e,t){let i=ne(e,t),r=[gr(e,{kind:"migration",change:t}),nn(e,t),...$m.map(n=>VE.join(i,n))];return(await Promise.all(r.map(eF))).some(Boolean)}async function tF(e,t){let i=await ia(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function HE(e,t){await Ga.mkdir(e.transactionsDir,{recursive:!0}),await ee(gr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function DE(e,t,i={}){let r=i.removeVerificationReport===!1?$m:[...$m,ZM];await Promise.all([Ga.rm(We(e,t),{recursive:!0,force:!0}),Ga.rm(nn(e,t),{recursive:!0,force:!0}),...r.map(n=>Ga.rm(VE.join(ne(e,t),n),{force:!0}))])}async function LE(e,t){await qi(Wr(e,t.name),Br({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function ME(e,t){try{let i=await kt(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function FE(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=fe(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function iF(e){let t=ne(e.paths,e.state.name),i=await Z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];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});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return yl({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function BE(e,t){let i=await iu(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Ws(e){return se(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await tF(e.paths,e.name),i=await zr(e.paths,e.name)?await Ze(Pt(e.paths,e.name)):null;if(!t&&i)return await DE(e.paths,e.name,{removeVerificationReport:!1}),await LE(e.paths,i),i;let r=null,n=null;for(t||(r=await BE(e.paths,e.name),n=await ME(e.paths,e.name),FE(e.paths,n),t={schema:Pl,id:QM(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await HE(e.paths,t));;){let a=Fy(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await BE(e.paths,e.name),n??=await ME(e.paths,e.name),FE(e.paths,n),i=My({state:r,acceptance:await iF({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await El(Pt(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await DE(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ze(Pt(e.paths,e.name)),await LE(e.paths,i)),t={...t,status:a.nextStatus},await HE(e.paths,t)}return await Ga.rm(gr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ze(Pt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as qE}from"node:fs";import WE from"node:path";function rF(e,t){let i=fe(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function nF(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function aF(e,t,i){let r=new Date().toISOString(),n=e.verification===null?e:on(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ii(t),completed_at:r});return ct({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:i?nF(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 oF(e){try{let t=await Bu(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 zE(e){return se(e.paths,`recover portable change ${e.name}`,async()=>{let t=await En(e.paths,e.name);if(t.status==="done")return await Wu({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 i=rF(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=Wr(e.paths,e.name),n=await oF(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await qi(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await Wu({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=fm({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await sn({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await qE.rm(WE.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=Br({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await qi(r,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=c||l;if(u){let f=aF(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",l);t=await sn({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=Br({portableState:t,projectRoot:e.paths.projectRoot,branch:fe(e.paths.projectRoot).currentBranch});return await qE.mkdir(WE.dirname(Wr(e.paths,t.name)),{recursive:!0}),await qi(r,d,{containedRoot:e.paths.runtimeDir}),await Wu({paths:e.paths,state:t}),{state:t,local:d,action:u?"reverify":"resume-stable-boundary",reason:a,message:u?"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{promises as GE}from"node:fs";import cF from"node:path";function sF(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function JE(e){let t=e.acceptance.reduce((i,r)=>({...i,[r.result]:i[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:sF(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}function lF(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function uF(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function dF(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:pF(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:mF(r,i)}))]:[]]}function fF(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function UE(e,t){let i=fe(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:cF.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}function hF(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function cd(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function pF(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:cd(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function mF(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:cd(e.summary,t)??""}}async function Ua(e){let t=await US(e),i=JE(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Ts({paths:e.paths,state:t.state}),a=await Ei(e.paths,e.name),o=a?{...UE(e.paths,t.state),projectRoot:"."}:UE(e.paths,t.state),s=sd(t.state,n),c=o.bindingState==="mismatch"?{...s,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...s.runnerAction,kind:"none"}}:s,l=a?hF(e.paths,a):[],u=a?(()=>{let h=a.children.filter(({status:y})=>y==="pending"||y==="ready").length,v=a.children.filter(({status:y})=>y==="active"||y==="verified").length,m=a.children.filter(({status:y})=>y==="integrated"||y==="archived").length,p=a.children.filter(({status:y})=>y==="blocked"||y==="needs-reverify").length,b=a.children.filter(({status:y})=>y==="active"||y==="blocked"||y==="needs-reverify").slice(0,16).map(y=>({name:y.name,summary:y.summary,projectRoot:y.task?.projectRoot??y.projectRoot?"<worktree>":null,reason:cd(y.blocker,l)})),g=a.children.flatMap(({blocker:y})=>{let E=cd(y,l);return E?[E]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:a.children.length,waiting:h,working:v,integrated:m,blocked:p,active:b,agents:{working:a.children.filter(({task:y})=>y!==null).length,completed:m},risks:g,nextAction:a.finalVerification.status==="passed"?"final-delivery":a.finalVerification.status==="pending"&&m===a.children.length?"parent-verification":h>0?"dispatch-ready-child":p>0?"resolve-blocker":"continue-supervisor"}})():null,d=e.details?(()=>{let h=a?.stateVersion??0,v=dF(t.state,a,l),m=uF(e.cursor,t.state.state_version,h),p=v.slice(m,m+32),b=m+p.length<v.length?lF(t.state.state_version,h,m+p.length):null;return{items:p,nextCursor:b,supervisorStateVersion:h}})():null,f=a?{schema:a.schema,parent:a.parent,integration:{branch:a.integration.branch,targetBranch:a.integration.targetBranch},finalVerification:{status:a.finalVerification.status,summary:a.finalVerification.summary},summary:u}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:fF(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:a?[]:i.blockers,workspace:o,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((h,v)=>({...h,[v.status]:(h[v.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},continuation:c,...e.details?{details:{stateVersion:t.state.state_version,...a?{supervisorStateVersion:d.supervisorStateVersion}:{},items:d.items,nextCursor:d.nextCursor,nextPageArgs:d.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",d.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}async function KE(e){let t;try{t=await GE.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await GE.readFile(`${Lt(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}import zs from"path";import{realpathSync as _F}from"fs";var Gi={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function YE(e){return e?e.command?`${Gi.next} ${e.command}`:e.ask_user?`${Gi.next} ${e.ask_user}`:null:null}function XE(e,t){let i=[e.summary],r=YE(e.next);return r&&i.push(r),e.user_message&&i.push("",Gi.relay,e.user_message),t!==void 0&&i.push("",Gi.details,JSON.stringify(t,null,2)),`${i.join(`
|
|
263
|
+
${Wr(e.verification.summary)}
|
|
264
|
+
`}function cL(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function Gu(e){let t;try{t=await rL.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=cL(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function Uu(e){await he(e.file,sL(e.state,e.supervisor))}var KS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lL="comet-state.yaml",uL="state.json",i4=tc("en");function Mt(e,t){if(!KS.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=zr.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}function Pt(e,t){return zr.join(Mt(e,t),lL)}function Jr(e,t){return zr.join(We(e,t),uL)}async function Gr(e,t){try{let i=await Rn.readFile(Pt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function YS(e){return fe(e).currentBranch}async function zi(e,t){return Ze(Pt(e,t))}async function XS(e){let t=await un({file:Pt(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 i=zr.join(Mt(e.paths,t.name),"verification.md");await I(e.paths.nativeRoot,i),await Rn.rm(i,{force:!0})}return t}async function dL(e){let t=Mt(e.paths,e.state.name),i=zr.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Rn.readdir(i,{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(!KS.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=zr.join(t,...s.split("/")),l=await Rn.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=zr.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await Rn.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function fL(e){let t=Mt(e.paths,e.state.name),i=await Z({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(lp(i.text))throw new Error("Brief has a blocking open question");let r=[],n=[];for(let a of e.specChanges){if(a.source===null){n.push({...a,contentHash:null});continue}let o=await Z({root:t,ref:a.source,maxBytes:null,includeHash:!1});r.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:H("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:Sl({briefMarkdown:i.text,specs:r}),formalHash:H("comet.native.shape-formal-artifacts.v1",{brief:{source:i.ref,contentHash:H("comet.native.shape-artifact-content.v1",i.text)},specs:n})}}function hL(e){return H("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function QS(e){let t=await dL(e),i=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.operation===d.operation||i?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await fL({...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(!qy(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await $s({changeDir:Mt(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:vm({...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&&hL({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?gm({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 ZS(e){let t=await zi(e.paths,e.name),i=await Dt(e.paths,e.name),r=await aa(e.paths,{kind:"archive",change:e.name}),n=r?.kind==="archive"?r:null;if(n&&i?.finalVerification.status==="pending"){if(n.journal.status!=="prepared"||n.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await Rn.rm(n.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||i?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=jS(i);if(n||a.stateVersion!==i.stateVersion){let o=await pL({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return n&&await Rn.rm(n.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await Pn(e.paths,$S(i,t)),{state:t,action:"recorded-final-verification"}}async function eE(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...ln(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ti(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete r.shape_confirmation_hash,delete r.children_contract_hash;let n=await XS({paths:e.paths,previous:t,next:r});return await qi(Jr(e.paths,t.name),qr({portableState:n,projectRoot:e.paths.projectRoot,branch:YS(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function pL(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 r={...ln(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ti(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 XS({paths:e.paths,previous:t,next:r});return await qi(Jr(e.paths,t.name),qr({portableState:n,projectRoot:e.paths.projectRoot,branch:YS(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Ku(e){if(e.state.verification===null)return"not-applicable";let t=zr.join(Mt(e.paths,e.state.name),"verification.md");return await Gu({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Uu({file:t,state:e.state}),"rebuilt")}async function tE(e){let t=await zi(e.paths,e.name),i=Jr(e.paths,e.name);try{let r=await Ju(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var u4=16*1024;async function Yu(e){let t=await cm(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(ru(t.selection.change),t.selection)}function iE(e){return $u(e.projectRoot)}async function Ls(e,t){return await Zn(e.projectRoot),PS(e.projectRoot,"native",t)}var M4=16*1024*1024,Xu=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Ms=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function nE(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return qa.resolve(e.nativeRoot,...i.target.split("/"))}async function aE(e,t,i){let r=await Er(e,t.id);if(r.some(p=>p.type==="archive-finalized"))return;let n=r.some(p=>p.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let p=t.operations.find(g=>g.id==="archive-change");if(!p||p.type!=="move"||!p.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let b=await oi(nE(e,t));if(b?.kind!=="directory"||b.hash!==p.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=nE(e,t),o=qa.join(a,Te),s=await Nb(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=D(e,s.name),l=await Oe(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let p=iv(bi,l,new Set,Dp,void 0);if(!p.action)throw new Error(p.reason??"Native archive produced no action");u=rv(bi,p.state,{actionId:p.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},Dp,void 0)}let d=L(`archive:${t.id}:${s.name}`),f=await it(c,u.trajectoryRef),h=f.filter(p=>p.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(p=>p.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=h.find(p=>p.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!mL(v.data,m)||v.runId!==u.runId||v.timestamp!==t.createdAt||v!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||h.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await ju(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await ua(e,t,"archive-finalization-started")),!s.archived){let p={...s,archived:!0};await yb(o,p)}v||(v=await Or({changeDir:c,run:u,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await kn({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await vn(c,u),await Ls(e,s.name),t.schema==="comet.native.transaction.v2"?await ju(e,t,"archive-finalized"):await ua(e,t,"archive-finalized")}async function km(e,t){let i=We(e,t);try{let r=await rE.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await I(e.runtimeDir,i),await rE.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function vL(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Er(e,t.id)).some(c=>c.type==="operation-started")){let c=await Au({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new Ms(c,"Native Archive facts changed before the first transaction operation")}let o=await bS(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await De(e,t.change),u=await xu({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await aE(e,o,i);let s=await ju(e,o,"commit");return{journal:s,runtimeCleanupWarning:await km(e,s.change)}}let r=await mN(e,t);await aE(e,r,i);let n=await ua(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await km(e,n.change):null}}function gL(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(qa.resolve(t.projectRoot)!==qa.resolve(e.projectRoot)||qa.resolve(t.nativeRoot)!==qa.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function oE(e){return se(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await vr(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await yt(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await om(e.paths,e.transactionId):i;return gL(e.paths,r),r.status==="committed"?(r.change&&await km(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await vL(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?kS(e.paths,r):Ml(e.paths,r)}finally{await gr(t)}},{allowedTransactionId:e.transactionId})}import{promises as TL}from"fs";async function sE(e,t){let i=[],r=D(e,t.name),n=pr(r,Nt.stateRef),a;try{a=await Oe(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=pr(r,a.trajectoryRef),s=await wa(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await it(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=pr(r,a.checkpointRef);try{let u=await ga(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var wL=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function yL(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function NL(e){return e?e.map(yL).join(" "):null}function bL(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function Ft(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function kL(e){return e.map(t=>Ft(t,[],null))}function SL(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[Ft("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(Ft("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(Ft("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Ft("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(Ft("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(Ft("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Ft("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Ke(e,t){let i=t.commandArgs===void 0?bL(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?NL(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??kL(t.requiredInputs??[])}}function Qu(e){let i=(e.findings??[]).filter(d=>!ya(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||wL.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return Ke(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Ft("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Ke(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Ft("summary",["--summary"],"<summary>")]});if(n)return Ke(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Ft("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Ke(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Ft("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Ke(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Ke(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=SL(e.state);return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Fs from"path";var cE=8,EL={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function PL(e){let t=EL[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:ya(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function RL(e,t,i){if(!i.path)return null;let r;if(Fs.isAbsolute(i.path)?r=Fs.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Fs.resolve(ne(e,t.name),...i.path.split(/[\\/]/u)):r=Fs.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!O(e.projectRoot,r))return null;let n=Fs.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function CL(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Sm(e){return e.findings.map(t=>{let i=PL(t.code);return{code:t.code,message:t.message,severity:i.severity,path:RL(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:CL(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Em(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,cE),truncated:t.length>cE}}var lE=240,uE=8,Zu=50;function dE(e){let t=Array.from(e);return t.length<=lE?e:`${t.slice(0,lE-1).join("")}…`}function xL(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function AL(e){let t=[...new Set(e.map(xL))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,uE),reasonCount:e.length,codesTruncated:t.length>uE};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Zu),reasonsTruncated:e.length>Zu}}}async function fE(e){let t=null;try{let s=await Mr(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Lr(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Lr(e.paths,e.state.name)}}let i=await Qk({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=AL(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Dr.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:dE(i.checkpoint.summary),nextAction:dE(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Dr.maxArtifacts}}async function _L(e,t){let i=D(e,t.name),r=await Oe(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await ga(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await it(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function IL(e,t){let i=await _L(e,t);return{committed:i,latest:xk(i),history:Ck(i)}}async function hE(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await IL(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var jL=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Wa=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function Pm(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function $L(e){return(await Yu(e))?.change??null}function OL(e,t,i=!1,r){return Qu({state:e,archiveReady:t,evidenceRetreat:i}).command}async function HL(e,t){let i=ne(e,t.name),r=[...(await up(i,t.brief)).findings,...(await Pb(e,t)).findings,...await sE(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await va(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Jl(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await Ha({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Bi(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await dp(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function Rm(e,t,i){let r=await $L(e)===t,n=await Fo(e,t),a=await sb(e,t),o;try{let w=await gi(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=Sm({paths:e,state:o,findings:[w]}),F=Qu({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:F.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:Em(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:F,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await fE({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await hE(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await Ha({changeDir:ne(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Be=await $a(e,o.name,o.verification_evidence);for(let ue of Be.acceptanceTrace.entries)P.set(ue.acceptanceId,ue.status==="failed"?"failed":ue.status==="missing"?"missing":"satisfied")}let F=Hy({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),$=F.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",F.nextCursor,"--project-root",e.projectRoot]:null;u={...F,...$?{nextPageCommand:Pm($),nextPageArgs:$}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await gu(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await kt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let P=await ba({paths:e,identity:w});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await as({paths:e,identity:w});f.push(...P.findingCodes.map(F=>({code:F,message:`Native workspace advisory changed: ${F} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],v=!1;if(o.phase==="verify"){let w=await sS({paths:e,state:o});v=w.freshness!=="fresh",h.push(...w.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let m=null,p=[];if(o.phase==="archive")try{m=await Au({paths:e,name:o.name}),p.push(...m.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{p.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let b=[...await HL(e,o),...s.findings,...d,...f,...h,...l,...p].filter((w,P,F)=>F.findIndex($=>$.code===w.code&&$.path===w.path)===P),g=Sm({paths:e,state:o,findings:b}),S=g.filter(w=>!ya(w.code)),N=o.phase==="archive"&&m?.ready===!0&&S.length===0,k=v||o.phase==="archive"&&(m?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),E=g.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",y=g.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:E||R?null:OL(o,N,k,i?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:Em(g),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Qu({state:o,findings:g,archiveReady:N,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:g.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Zu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:g.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...y?{error:y.message}:{}}}async function DL(e){let t;try{t=await ei({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await TL.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Wa.maxChanges))throw new Error(`Native status exceeds ${Wa.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function ed(e,t){let i=t.toString(36),r=H("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function LL(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=jL.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=H("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function ML(e,t){let i=await DL(e),r=H("comet.native.status-names.v1",i),n=LL({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Wa.maxItems).map(u=>Rm(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,h={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:f<i.length?ed(r,f):null,nextPageCommand:f<i.length?Pm(["comet","native","status","--cursor",ed(r,f)]):null,nextPageArgs:f<i.length?["comet","native","status","--cursor",ed(r,f)]:null,limits:{...Wa}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>Wa.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s<i.length?ed(r,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:i.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?Pm(l):null,nextPageArgs:l,limits:{...Wa}}}async function Cm(e,t){return(await ML(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as nM,randomUUID as aM}from"node:crypto";import{constants as Tm,promises as Q}from"node:fs";import le from"node:path";var rd=$n(nn(),1);import{randomUUID as FL}from"crypto";import{promises as wE}from"fs";import Am from"path";import{isDeepStrictEqual as _m}from"util";var Cn=/^[a-f0-9]{64}$/u,BL=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),VL=new Set(["sourceHash","targetHash","nextJournal"]),qL=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),pE=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),WL=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function td(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function mE(e){return JSON.stringify(e,null,2)+`
|
|
265
|
+
`}function Im(e){return e.schema===be?nu(e):gn(e)}function xm(e,t){return{...e,schema:be,minimum_runtime_version:2,revision:t}}function zL(e){return{...e,schema:ji,minimum_runtime_version:2,revision:1,previousState:xm(e.previousState,1),nextState:xm(e.nextState,2)}}function id(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:Ne,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function JL(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?L(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:wr,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:id(e.previousState),nextState:{...id(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:bi.definition.metadata.version,skillHash:Es}:e.nextRun}}function vE(e,t){return JSON.stringify(e)===JSON.stringify(t)}function za(e,t){return JSON.stringify(nu(e))===JSON.stringify(nu(t))}function gE(e,t){return JSON.stringify(gn(e))===JSON.stringify(gn(t))}function Ji(e,t){return _m(e,t)}function GL(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(td(n,qL,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!Cn.test(n.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof n.transitionId!="string"||n.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof n.evidenceHash!="string"||!Cn.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=xr(n.previousRun),o=xr(n.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!Ji(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!n.eventData||typeof n.eventData!="object"||Array.isArray(n.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=n.eventData,u=Object.keys(l);if(u.length!==pE.size||u.some(f=>!pE.has(f))||l.fromSchema!==be||l.toSchema!==Ne||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=L(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:r,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(n.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:n.sourceHash,transitionId:n.transitionId,previousRun:a,nextRun:o,evidenceHash:n.evidenceHash,eventData:l}}function Bs(e,t){return Am.join(D(e,t),"schema-migration.json")}function UL(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");td(e,BL,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let r=i.fromSchema===et&&i.toSchema===be,n=i.fromSchema===be&&i.toSchema===Ne;if(!r&&!n)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!Cn.test(i.sourceHash)||typeof i.targetHash!="string"||!Cn.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=r?fi(i.nextState):lt(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(L((0,rd.stringify)(Im(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");td(i.transition,VL,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!Cn.test(l.sourceHash)||typeof l.targetHash!="string"||!Cn.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=r?zp(l.nextJournal,t):Wp(l.nextJournal,t);if(L(JSON.stringify(l.nextJournal,null,2)+`
|
|
266
|
+
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===be?za(a,u.previousState)||za(a,u.nextState):a.schema===Ne&&(gE(a,u.previousState)||gE(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==Ne)throw new Error("Schema migration transition supersede target schema is invalid");s=GL(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");td(i.runRetreat,WL,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=xr(l.previousRun),d=xr(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!Cn.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==Ne||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Vs(e,t){let i=Bs(e,t),r=j(e,i);await I(r,i);try{let n=await Tl({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return UL(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function KL(e,t,i){let r=await va(e,t),n=r?await Jl(e,r):await Gl(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=Kh(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new ka(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await Qh(e,t,n)}async function yE(e){try{return await ti(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function YL(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function NE(e,t){let i=t.transitionSupersede,r=D(e,t.change),n=await it(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!_m(o.event,YL(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function XL(e,t,i){if(!t.transitionSupersede)return;let r=Ue(e,t.change),n=await yE(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=D(e,t.change),o=await Oe(a),s=await NE(e,t),c=await ga(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!Ji(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==L(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function QL(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=D(e,t.change),a=await Oe(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Ji(a,r.nextRun)){if(!Ji(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await vn(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!Ji(await Oe(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await NE(e,t);if(o.sequence===null){let l=await Or({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await kn({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=Ue(e,t.change),c=await yE(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await wE.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function ZL(e,t,i){if(!t.runRetreat)return;let r=D(e,t.change),n=await Oe(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Ji(n,t.runRetreat.nextRun)){if(!Ji(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await vn(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await it(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Or({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await kn({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function eM(e,t,i){let r=await Vs(e,t);if(!r)return null;if(await Ea(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=Am.join(ne(e,t),Te),a=await ti(n);if(await XL(e,r,a===r.targetHash),await KL(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await he(n,(0,rd.stringify)(Im(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=Ue(e,t),s=await ti(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await ee(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await QL(e,r,i),await ZL(e,r,i),await wE.rm(Bs(e,t),{force:!0}),r.nextState}async function tM(e){let t=D(e.paths,e.state.name),i=await Oe(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=L(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:be,toSchema:Ne,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function iM(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=za(i,t.previousState),a=za(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=D(e.paths,i.name),s=await Oe(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Ji(s,t.previousRun),l=Ji(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await it(o,t.nextRun.trajectoryRef)).map((b,g)=>({event:b,index:g})).filter(({event:b})=>b.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let b={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!_m(f.event,b)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...id(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},v=s,m=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,p=L(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await ti(Ue(e.paths,i.name)),transitionId:t.id,previousRun:v,nextRun:m,evidenceHash:p,eventData:{fromSchema:be,toSchema:Ne,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function rM(e){let t,i,r,n;if(e.state.schema===et){if(t=xm(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==dn)throw new Error("Native v1 change has a transition from another schema generation");let s=zL(e.pendingTransition.journal);if(vE(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(vE(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=Ue(e.paths,e.name);i={sourceHash:await ti(c),targetHash:L(mE(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==ji)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await iM({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=JL(s);if(za(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(za(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=Ue(e.paths,e.name);i={sourceHash:await ti(u),targetHash:L(mE(l)),nextJournal:l}}}else t=id(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await tM({paths:e.paths,state:e.state,migrationId:e.id}));let a=Am.join(ne(e.paths,e.name),Te),o=(0,rd.stringify)(Im(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===et?be:Ne,sourceHash:await ti(a),targetHash:L(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function bE(e){return se(e.paths,`migrate schema for ${e.name}`,()=>Sn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await eM(e.paths,e.name,e.hooks);if(i?.schema===Ne)return i;let r=await gi(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await Ea(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==et&&n.schema!==be)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Jp(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await rM({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??FL()}),s=Bs(e.paths,e.name),c=j(e.paths,s);await I(c,s),await ee(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Gi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),oM=512*1024,xn=/^([a-f0-9]{64})\.json$/u,sM=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,cM=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,nd=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function $m(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ri(e,t){return $m(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function RE(e,t){return $m(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Ja(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function nt(e,t){return e<t?-1:e>t?1:0}function lM(e,t){let i=le.relative(e.projectRoot,t);if(i.length===0||le.isAbsolute(i)||i===".."||i.startsWith(`..${le.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(le.sep).join("/")}function CE(e,t){return le.join(D(e,t),"evidence")}function ad(e,t){return lM(e,CE(e,t))}async function od(e,t){let i=le.resolve(e),r=le.resolve(t);if(!O(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=le.relative(i,r).split(le.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=le.join(o,s));let c=await Q.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await Q.realpath(o);if(a.length>0&&!O(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...Ja(c)})}return a}async function Bt(e){for(let t of e){let i=await Q.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!$m(t,i)||await Q.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function xE(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:ja(e,t)}function kE(e){return e!==null&&cM.test(e)?[e]:[]}function uM(e,t,i,r){if(e==="snapshots")return{canonical:Ca(i,t),dependencies:[]};if(e==="scopes"){let a=xa(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=fu(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[ja("scopes",a.scopeHash)]}}if(e==="verifications"){let a=ys(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(kE));return{canonical:a,dependencies:[a.implementationScopeRef,gk(a.reportHash),...kE(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||nM("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=pu(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=hu(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Ur(e){let t=await Q.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?oM:$r;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await Q.realpath(e.file);if(!O(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Tm.O_RDONLY|Tm.O_NOFOLLOW|Tm.O_NONBLOCK,a=await Q.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Bt(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!Ri(Ja(t),o)||!Ri(Ja(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let g=i+1-d,S=await a.read(u,0,Math.min(u.length,g),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,S.bytesRead)))}let[f,h,v]=await Promise.all([a.stat(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Bt(e.directoryChain),!h.isFile()||h.isSymbolicLink()||v!==r||!Ri(Ja(o),f)||!Ri(Ja(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let m=Buffer.concat(l,d).toString("utf8"),p;try{p=JSON.parse(m)}catch(g){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:g})}let b=uM(e.kind,e.hash,p,e.name);if(m!==JSON.stringify(b.canonical,null,2)+`
|
|
267
|
+
`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:Ja(f),directoryChain:e.directoryChain,dependencies:[...new Set(b.dependencies)].sort(nt)}}finally{await a.close()}}async function SE(e){try{return await Q.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function dM(e){let t=D(e.paths,e.name),i=t,r=CE(e.paths,e.name);await I(j(e.paths,r),r);let n;try{let s=await od(t,r);n=await Q.readdir(r,{withFileTypes:!0}),await Bt(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of nd){if(!n.some(f=>f.name===s))continue;let c=le.join(r,s),l=await od(t,c),u=(await Q.readdir(c,{withFileTypes:!0})).sort((f,h)=>nt(f.name,h.name)),d=new Map;for(let f of u){let h=sM.exec(f.name);if(!h)continue;let v=d.get(h[1])??[];v.push(f),d.set(h[1],v)}for(let[f,h]of[...d.entries()].sort(([v],[m])=>nt(v,m))){if(h.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let v=h[0];if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${v.name}`);let m=le.join(c,f),p=xn.exec(f)?.[1];if(!p)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let b=xE(s,p),g=le.join(c,v.name),S=await Ur({changeRoot:i,file:g,ref:b,kind:s,hash:p,name:e.name,directoryChain:l}),N=await SE(m),k=N?null:await Ur({changeRoot:i,file:m,ref:b,kind:s,hash:p,name:e.name,directoryChain:l});a.push({ref:b,original:m,quarantine:g,document:S,action:N?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(nt);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Ga(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${sd(o)}`),path:ad(e.paths,e.name)}]};for(let s of a.sort((c,l)=>nt(c.ref,l.ref))){if(await Bt(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Ur({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:xn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Ur({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:xn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!Ri(s.originalDocument.identity,d.identity)||!Ri(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await Q.rm(s.quarantine),await Bt(s.document.directoryChain);continue}if(!await SE(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await Q.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!Ri(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await Q.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Ur({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:xn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Ur({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:xn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!RE(s.document.identity,l.identity)||!Ri(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await Q.rm(s.quarantine),await Bt(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Ga(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${sd(o)}`),path:ad(e.paths,e.name)}]}}async function fM(e,t){let i=D(e,t),r=i,n=le.join(i,"evidence");await I(j(e,n),n);let a;try{let l=await od(i,n);a=await Q.readdir(n,{withFileTypes:!0}),await Bt(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!nd.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(nt);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${sd(o)}`);let s=[],c=0;for(let l of nd){if(!a.some(h=>h.name===l))continue;let u=le.join(n,l),d=await od(r,u),f=(await Q.readdir(u,{withFileTypes:!0})).sort((h,v)=>nt(h.name,v.name));await Bt(d);for(let h of f){if(s.length>=Gi.maxDocuments)throw new Error(`Native evidence store exceeds ${Gi.maxDocuments} documents`);let v=xn.exec(h.name);if(!v||!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${h.name}`);let m=xE(l,v[1]),p=le.join(u,h.name);await I(j(e,p),p);let b=await Ur({changeRoot:r,file:p,ref:m,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=b.size,c>Gi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Gi.maxScannedBytes} scanned bytes`);s.push(b)}await Bt(d)}return s}function EE(e,t){let i=new Set,r=[...e].sort(nt).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(nt).reverse())i.has(o)||r.push(o)}return i}function hM(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(nt),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(nt))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function pM(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=EE(t,r),a=new Set(n);for(let c of e)i-c.mtimeMs<Gi.minimumAgeMs&&a.add(c.ref);for(let c of nd){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||nt(u.ref,d.ref)).slice(0,Gi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=EE(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Gi.minimumAgeMs).sort((c,l)=>nt(c.ref,l.ref));return{candidates:hM(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function sd(e){let t=e.slice(0,Gi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Ga(e){let t=Gi.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function jm(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(nt);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Ga(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${sd(n)}`),path:r}}async function PE(e,t){try{await Q.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await Q.rename(e,t)}catch{}}async function mM(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Bt(e.directoryChain);let i=await Ur({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:xn.exec(le.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await Q.lstat(e.file),n=await Q.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!Ri(e.identity,r)||!Ri(e.identity,i.identity)||!O(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=le.join(le.dirname(e.file),`.${le.basename(e.file)}.${aM()}.gc`);await Q.rename(e.file,a);try{let[o,s]=await Promise.all([Q.lstat(a),Q.realpath(a)]);if(await Bt(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!RE(e.identity,o)||!O(e.directoryChain[0].realPath,s))throw await PE(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await Q.rm(a),await Bt(e.directoryChain)}catch(o){throw await PE(a,e.file),o}}async function vM(e){if((await ye(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await Q.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await yt(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function gM(e,t){if(t)return[t];let i;try{i=await Q.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(nt)}async function wM(e,t){let i=await gi(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Bi(e,t),Vs(e,t),Mr(e,t)]);return r!==null||n!==null||a!==null}async function yM(e){if(await wM(e.paths,e.name))return[];let t=await gi(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await dM({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await fM(e.paths,e.name),a=pM(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=ad(e.paths,e.name);if(!e.repair)return[...i.findings,jm(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await mM(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[jm(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Ga(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,jm(e.name,a,!0,o)]}async function AE(e){if(e.deferAll||await vM(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await gM(e.paths,e.name))try{a.push(...await yM({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Ga(`Native evidence retention refused to clean ${o}: ${s.message}`),path:ad(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await se(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Ga(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as NM,randomUUID as w9}from"crypto";import{promises as zs}from"fs";import ae from"path";var Hm=64*1024*1024,bM=256*1024,jE=16*1024*1024;async function at(e){try{return await zs.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function kM(e){let t;try{t=await zs.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await kt(e,i.name);if(r){await tu({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function Ws(e,t){let i=[];async function r(n){let a=await wt({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ae.join(n,s.name);if(t.excludedFiles?.has(ae.resolve(c))){await a.verify();continue}let l=await zs.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await re({root:e,file:c,maxBytes:Hm,label:`Native root file ${ae.relative(e,c)}`});i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function SM(e,t,i,r){await hi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await wt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ae.join(a,l.name);if(ae.resolve(u)===ae.resolve(i)){await s.verify();continue}let d=await zs.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ae.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await hi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await kr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:Hm,label:`Native root move file ${ae.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function Ua(e,t,i,r){let n=await Ws(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ae.resolve(i)]):void 0}),a=await Ws(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ae.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function EM(e,t){return ae.join(e.artifactRoot,`.comet-native-move-${t}`)}function PM(e,t){return ae.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function RM(e){return`${e}.removing`}function _E(e,t){return ae.join(ae.dirname(e),`.${ae.basename(e)}.${t}.rollback-removing`)}function $E(e,t,i){return ae.join(Ll(e,t).directory,`root-move-cleanup-${i}.json`)}function CM(e){return JSON.stringify(e,null,2)+`
|
|
268
|
+
`}function xM(e){return NM("sha256").update(e).digest("hex")}function AM(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ae.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function _M(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(AM);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ae.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function IM(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=CM(t);if(Buffer.byteLength(i,"utf8")>jE)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await he($E(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),xM(i)}async function TM(e){let t=await re({root:e.paths.runtimeDir,file:$E(e.paths,e.id,e.cleanup.kind),maxBytes:jE,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return _M(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Om(e){let t=await Ws(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function IE(e){return e.ref.split("/").length}async function jM(e){let i=[...await Om({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>IE(a)-IE(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ae.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await jl({root:e.projectRoot,file:a,maxBytes:Hm,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await jh({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Om({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await jh({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function OE(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function $M(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function OM(e,t,i,r){for(let a of[e,t])try{let o=await yt(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ae.join(i,"runtime","transactions",r,"transaction.json");try{let a=await re({root:i,file:n,maxBytes:bM,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function TE(e){let t=OE(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await mr(e.projectRoot,t),t}async function qs(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=OE(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await mr(e.projectRoot,i),i}async function cd(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await at(e.target),a=await at(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await IM({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Ws(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await qs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await TM({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await at(e.target),a=await at(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await rN({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return qs({projectRoot:e.projectRoot,config:t,id:e.id})}return await Om({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await qs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await qs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await jM({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),qs({projectRoot:e.projectRoot,config:t,id:e.id})}async function HM(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await at(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=RM(e.staging);t=await cd({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await Ws(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ae.resolve(e.lockFile)])}),await SM(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Ua(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await TE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await at(e.destinationPaths.nativeRoot)){if(await at(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Ua(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await at(e.staging))throw new Error("Native move staging tree is missing");await Ua(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await zs.rename(e.staging,e.destinationPaths.nativeRoot)}t=await TE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await at(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=PM(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await at(e.sourcePaths.nativeRoot)&&await Ua(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await cd({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await kM(e.destinationPaths);let n=await yt(e.destinationPaths,e.pending.id);await ua(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await mr(e.projectRoot,o),o}async function HE(e){let t=await ye(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await qe(e.projectRoot,i.fromArtifactRoot),n=await qe(e.projectRoot,i.toArtifactRoot),a=EM(n,i.id),o=await at(r.nativeRoot)?r:n,s=await vr(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await OM(r,n,a,i.id)}catch(v){if(i.stage!=="copying"||!await at(r.nativeRoot))throw v;let m=$M({id:i.id,paths:r,now:new Date});await hN(r,m),c={journal:m,paths:r}}if(e.strategy==="continue"){let v=await HM({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:v}}if(!await at(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=_E(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await at(n.nativeRoot)&&await Ua(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await cd({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=_E(a,i.id);!t.native.pending_root_move?.cleanup&&await at(a)&&await Ua(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await cd({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await yt(r,i.id);await Ml(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},h={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await mr(e.projectRoot,h),{activeNativeRoot:r.nativeRoot,config:h}}finally{await gr(s)}}var Ka=4096,DM=4096,LM=1024;async function Kr(e,t,i){try{let r=await wt({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function ud(e,t){let i=new Map(e.map(r=>[je.resolve(r.file),{...r,file:je.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await Bo(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await bh(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function MM(e,t){let i=iE(e),r;try{await I(e.projectRoot,i);let n=await Yu(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await Gr(e,r.change)?[]:(await De(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await ld.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function FM(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await I(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function BM(e,t){let i=[],r=[];for(let n of await Kr(e,e.transactionsDir,DM)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await yt(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:je.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await ea([e],`doctor archive recovery ${a.id}`,async()=>await ud([{paths:e,file:je.join(e.locksDir,"root-move.lock")},{paths:e,file:je.join(e.locksDir,"archive.lock")}],i)?(await oE({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function VM(e,t,i){let r=[];for(let n of await Kr(e,e.locksDir,LM)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=je.join(e.locksDir,n.name);try{let o=await Bo(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await bh(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function qM(e,t,i=5){let r=[],n=t?await Cm(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await Cm(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:je.join(e.changesDir,a.name,Te)});continue}let o=await Rm(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:je.join(e.projectRoot,s.path)}:{}})}return r}async function WM(e,t){let i=[],r=t.name?[t.name]:(await Kr(e,e.changesDir,Ka)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await wa(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await QN(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:je.join(D(e,n),"trajectory.jsonl")})}return i}async function zM(e,t){let i=[],r=t.name?[t.name]:(await Kr(e,e.changesDir,Ka)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await Fo(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=sn(e,n),s=We(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await ea([e],`migrate Runtime layout for ${n}`,async()=>{let c=await ei({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await I(e.runtimeDir,s),await ld.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await ei({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await ld.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await ld.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function JM(e,t){let i=[],r=t.name?[t.name]:(await Kr(e,e.changesDir,Ka)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await np(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:Na(e,n),repair:"migrate"});continue}let a=await De(e,n);await lb({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:Na(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:Na(e,n)})}return i}async function GM(e,t){let i=[],r=t.name?[t.name]:(await Kr(e,e.changesDir,Ka)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Bs(e,n);try{let o=await Vs(e,n),s=await gi(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:je.join(e.changesDir,n,Te)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:je.join(e.changesDir,n,Te),repair:"migrate"});continue}await bE({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:je.join(e.changesDir,n,Te)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function UM(e,t){let i=[],r=t.name?[t.name]:(await Kr(e,e.changesDir,Ka)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Bi(e,n)}catch(o){if(o instanceof Ps)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Ue(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await ea([e],`doctor transition recovery ${n}`,async()=>await ud([{paths:e,file:je.join(e.locksDir,"root-move.lock")},{paths:e,file:je.join(e.locksDir,`transition-${n}.lock`)}],i)?(await Vk(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:Ue(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Ue(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:Ue(e,n),repair:"continue"})}}return i}async function KM(e,t){let i=[],r=t.name?[t.name]:(await Kr(e,e.changesDir,Ka)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Lr(e,n),o;try{o=await Mr(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await ea([e],`doctor checkpoint recovery ${n}`,async()=>await ud([{paths:e,file:je.join(e.locksDir,"root-move.lock")},{paths:e,file:je.join(e.locksDir,`transition-${n}.lock`)}],i)?(await eS(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function Js(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await ye(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([qe(r.projectRoot,c.fromArtifactRoot),qe(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await ud([{paths:l,file:je.join(l.locksDir,"root-move.lock")},{paths:u,file:je.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await HE({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await qe(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await FM(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await BM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await zM(r,{name:e.name,repair:t})),i.push(...await GM(r,{name:e.name,repair:t})),i.push(...await JM(r,{name:e.name,repair:t})),i.push(...await WM(r,{name:e.name,repair:t})),i.push(...await UM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await KM(r,{name:e.name,repair:t})),i.push(...await AE({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await VM(r,t,s.unfinished)),i.push(...await MM(r,t)),e.projectOnly||i.push(...await qM(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{randomUUID as YM}from"node:crypto";import{promises as Fe}from"node:fs";import ht from"node:path";var Dm=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function DE(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function LE(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=ht.join(e.archiveDir,t);if(!O(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function dd(e){try{return await Fe.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ME(e,t){let i=ht.normalize(ht.resolve(e)),r=ht.normalize(ht.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function XM(e,t){let i;try{i=await Fe.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=ht.join(e.archiveDir,n.name);try{let o=await Ze(ht.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function QM(e,t){let i=await aa(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function An(e,t){await Fe.mkdir(e.transactionsDir,{recursive:!0}),await ee(yr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function ZM(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Gt(e.paths.projectRoot);i.some(a=>ME(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await ye(a);if(!o)continue;let s=await qe(a,o.native.artifact_root);r.some(c=>ME(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await Fe.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await Ze(ht.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await ou(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function eF(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function tF(e){let t=ht.join(e.paths.specsDir,e.change.capability),i=ht.join(t,"spec.md");if(!O(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await Fe.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await Fe.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([Fe.realpath(e.paths.specsDir),Fe.realpath(t)]);if(!O(o,s))throw new Error("Native canonical capability path escaped");try{let c=await Fe.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Fe.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await Fe.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=ht.join(Mt(e.paths,e.state.name),e.change.source);await he(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await Fe.mkdir(t,{recursive:!0}),await he(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function FE(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function iF(e,t){let i=Mt(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await Z({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function rF(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(FE(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Lm(e){return se(e.paths,`archive portable change ${e.name}`,async()=>{let t=eF(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await QM(e.paths,e.name),r=Mt(e.paths,e.name),n=await dd(r),a=n?null:await XM(e.paths,e.name),o;if(n)o=await zi(e.paths,e.name);else if(i)o=await Ze(ht.join(LE(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await Dt(e.paths,e.name);if(n&&!o.archived&&i===null){let d=await QS({paths:e.paths,state:o});if(d.drifted){let f=d.reason??"Native confirmed requirements changed";throw await eE({paths:e.paths,state:o,reason:f}),new Error(`${f}; Native change returned to Shape and requires confirmation`)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let d=await ZS({paths:e.paths,name:e.name});if(o=d.state,d.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");d.action==="recorded-final-verification"&&(s=await Dt(e.paths,e.name))}let c=LE(e.paths,i?.archive_ref??DE(o)),l=await dd(c);if(i&&rF(i,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await Ls(e.paths,o.name),await Fe.rm(We(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)FE(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let d=await ZM({paths:e.paths,state:o});if(!o.archived&&d.length>0&&t!==o.name)throw new Dm(d);i={schema:_l,id:YM(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:DE(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await iF(e.paths,o),created_at:new Date().toISOString()},await An(e.paths,i)}if(!n&&l&&i.status==="report-aligned")i={...i,status:"moved"},await An(e.paths,i);else if(!n&&l&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);let u=!1;if(i.status==="prepared"&&s&&!o.archived&&(s=(await Ts({paths:e.paths,state:s})).state,u=!0),i.status==="prepared"){for(let d=i.next_spec_index;d<i.spec_changes.length;d+=1)await tF({paths:e.paths,state:o,change:i.spec_changes[d]}),i={...i,next_spec_index:d+1},await An(e.paths,i),await e.hooks?.afterSpecApplied?.(d);i={...i,status:"specs-applied"},await An(e.paths,i)}if(i.status==="specs-applied"){if(s&&!o.archived&&!u&&(s=(await Ts({paths:e.paths,state:s})).state,u=!0),!o.archived){let d={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await un({file:Pt(e.paths,o.name),expectedStateVersion:o.state_version,next:d,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await An(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let d=await dd(r)?r:c;if(await Uu({file:ht.join(d,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Gu({file:ht.join(d,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await An(e.paths,i),s&&!u&&(await Ts({paths:e.paths,state:s}),u=!0),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(s&&!u&&await Ts({paths:e.paths,state:s}),await Fe.mkdir(e.paths.archiveDir,{recursive:!0}),await dd(c))throw new Error(`Native Archive target already exists: ${c}`);await Fe.rename(r,c),i={...i,status:"moved"},await An(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await Ls(e.paths,o.name),await Fe.rm(We(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await Fe.rm(yr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function Ui(e,t,i){return e.language==="zh-CN"?i:t}function nF(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:Ui(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Ui(e,"Reply A or B","回复 A 或 B"),agentInstruction:Ui(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i(Ui(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(Ui(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return i(Ui(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 aF(e){let t=e.workspace.change_branch??"<change-branch>",i=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${i}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${i}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function oF(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:r,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",r],requiredInputs:[],inputOptions:[],description:Ui(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Ui(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function VE(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ya(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function sF(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function BE(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function cF(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function lF(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Yr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:VE({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ya("summary","--summary"),sF(e.name,e.flag)]}}function Mm(e){return[Yr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Yr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function fd(e,t,i={}){let r=cF(t)&&e.coordination_mode===void 0,n=nF(e,r),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[Ya("summary","--summary")],commandAlternatives:[Yr({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:[Ya("summary","--summary")],commandAlternatives:[Yr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Mm({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:[Ya("summary","--summary")],commandAlternatives:[Yr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Yr({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:[Ya("summary","--summary")],commandAlternatives:[Yr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Mm({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:[Ya("summary","--summary")],commandAlternatives:Mm({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?VE({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:r?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:lF({change:e.name,stateVersion:e.state_version,coordinationRequired:r}),requiredInputs:["summary",...r?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...r?[BE("coordination-mode","--coordination-mode",Wy)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.some(({status:l})=>l==="blocked"||l==="needs-reverify"),c=t.children.some(({status:l})=>l==="ready"||l==="active");return{...a,disposition:s&&!c?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:s&&!c?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Ui(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=i.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?i.archiveBlockers&&i.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[BE("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...oF(e)],userCommunication:aF(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Yr({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import{randomUUID as uF}from"node:crypto";import{promises as Xa}from"node:fs";import KE from"node:path";var Fm=["evidence.md","repair.md","archive.md","checkpoint.md"],dF="verification.md";async function fF(e){try{return await Xa.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Bm(e,t){let i=ne(e,t),r=[yr(e,{kind:"migration",change:t}),sn(e,t),...Fm.map(n=>KE.join(i,n))];return(await Promise.all(r.map(fF))).some(Boolean)}async function hF(e,t){let i=await aa(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function qE(e,t){await Xa.mkdir(e.transactionsDir,{recursive:!0}),await ee(yr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function WE(e,t,i={}){let r=i.removeVerificationReport===!1?Fm:[...Fm,dF];await Promise.all([Xa.rm(We(e,t),{recursive:!0,force:!0}),Xa.rm(sn(e,t),{recursive:!0,force:!0}),...r.map(n=>Xa.rm(KE.join(ne(e,t),n),{force:!0}))])}async function zE(e,t){await qi(Jr(e,t.name),qr({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function JE(e,t){try{let i=await kt(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function GE(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=fe(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function pF(e){let t=ne(e.paths,e.state.name),i=await Z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];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});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Sl({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function UE(e,t){let i=await ou(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Gs(e){return se(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await hF(e.paths,e.name),i=await Gr(e.paths,e.name)?await Ze(Pt(e.paths,e.name)):null;if(!t&&i)return await WE(e.paths,e.name,{removeVerificationReport:!1}),await zE(e.paths,i),i;let r=null,n=null;for(t||(r=await UE(e.paths,e.name),n=await JE(e.paths,e.name),GE(e.paths,n),t={schema:Al,id:uF(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await qE(e.paths,t));;){let a=Uy(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await UE(e.paths,e.name),n??=await JE(e.paths,e.name),GE(e.paths,n),i=Gy({state:r,acceptance:await pF({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await xl(Pt(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await WE(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ze(Pt(e.paths,e.name)),await zE(e.paths,i)),t={...t,status:a.nextStatus},await qE(e.paths,t)}return await Xa.rm(yr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ze(Pt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as XE}from"node:fs";import QE from"node:path";import{promises as Vm}from"node:fs";import mF from"node:path";var vF=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),gF=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),wF=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),yF=new Set(["status","summary"]);function hd(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function pd(e,t,i){let r=new Set(Object.keys(e)),n=[...t].filter(o=>!r.has(o)),a=[...r].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${i} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function NF(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((i,r)=>i===t[r])}function _n(e,t,i){return{status:"incompatible",file:e,snapshot:t,message:i}}function bF(e,t,i,r){let n=hd(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=pd(n,vF,"Native Supervisor overlay");if(a)return a;if(r.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(r.parent!==t.name)return`Native Supervisor overlay parent ${r.parent} does not match ${t.name}`;let o=hd(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=pd(o,gF,"Native Supervisor integration");if(s)return s;if(r.integration.headCommit!==r.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=hd(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=pd(c,yF,"Native Supervisor finalVerification");if(l)return l;if(r.finalVerification.status!=="pending"||r.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!==i.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let f=hd(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let h=pd(f,wF,`Native Supervisor child ${u}`);if(h)return h;let v=i.children[u];if(f.name!==v.name||f.summary!==v.summary||!NF(f.dependsOn,v.depends_on))return`Native Supervisor child ${v.name} does not match the legacy children contract`;let m=v.depends_on.length===0?"ready":"pending";if(f.status!==m)return`Native Supervisor child ${v.name} has progressed beyond its initial ${m} status`;if(f.baseCommit!==null||f.candidateCommit!==null||f.verifiedCommit!==null||f.integrationCommit!==null||f.verification!==null||f.blocker!==null||f.projectRoot!==null||f.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function In(e){let t=Lu(e.paths,e.state.name),i;try{let c=await Vm.lstat(t);if(!c.isFile()||c.isSymbolicLink())return _n(t,"","Native Supervisor overlay is not a regular file");i=await Vm.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:_n(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let r;try{r=JSON.parse(i)}catch(c){return _n(t,i,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=mF.join(e.paths.changesDir,e.state.name),a;try{a=await $s({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return _n(t,i,`Native children contract cannot be validated: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:i};let o;try{o=await Dt(e.paths,e.state.name)}catch(c){return _n(t,i,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return _n(t,i,"Native Supervisor overlay disappeared during inspection");let s=bF(r,e.state,a.contract,o);return s?_n(t,i,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:i}}async function YE(e){let t=await In({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 Vm.rm(t.file,{force:!1})}function kF(e,t){let i=fe(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function SF(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function EF(e,t,i){let r=new Date().toISOString(),n=e.verification===null?e:ln(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ti(t),completed_at:r});return ct({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:i?SF(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 PF(e){try{let t=await Ju(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 ZE(e){return se(e.paths,`recover portable change ${e.name}`,async()=>{let t=await zi(e.paths,e.name);if(t.status==="done")return await Ku({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 i=kF(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=await In({paths:e.paths,state:t});if(r.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:r.message};let n=!1;r.status==="repairable-legacy-overlay"&&(await YE({paths:e.paths,state:t,expected:r}),n=!0);let a=Jr(e.paths,e.name),o=await PF(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason;if(s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed"&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(v=>v.status==="planned"||v.status==="running"?{...v,status:"interrupted"}:v)},await qi(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Ku({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(v=>v.status==="interrupted"&&!v.repeatable):void 0;if(l){let v=wm({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await un({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot}),await XE.rm(QE.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let m=qr({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await qi(a,m,{containedRoot:e.paths.runtimeDir}),{state:t,local:m,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",f=u||d;if(f){let v=EF(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 un({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot})}let h=qr({portableState:t,projectRoot:e.paths.projectRoot,branch:fe(e.paths.projectRoot).currentBranch});return await XE.mkdir(QE.dirname(Jr(e.paths,t.name)),{recursive:!0}),await qi(a,h,{containedRoot:e.paths.runtimeDir}),await Ku({paths:e.paths,state:t}),{state:t,local:h,action:f?"reverify":"resume-stable-boundary",reason:s,message:f?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{promises as rP}from"node:fs";import RF from"node:path";import eP from"node:path";function tP(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function iP(e,t){let i=e.acceptance.reduce((r,n)=>({...r,[n.result]:r[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:i,unresolved_acceptance_ids:e.acceptance.filter(({result:r})=>r==="failed"||r==="blocked").map(({id:r})=>r),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(r=>({owner:r.owner,reason:tP(r.reason.text),acceptance_ids:r.acceptance_ids,resolution_action:r.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(r=>r.outcome==="fail"&&r.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:tP(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(r=>r.source).filter(r=>r!==null)].slice(0,16).map(r=>eP.relative(t.projectRoot,eP.join(t.changesDir,e.name,r)).replaceAll("\\","/")):[]},archived:e.archived}}function CF(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function xF(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function AF(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:TF(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:jF(r,i)}))]:[]]}function _F(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function nP(e,t){let i=fe(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:RF.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}function IF(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function md(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function TF(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:md(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function jF(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:md(e.summary,t)??""}}async function Tn(e){let t=await tE(e),i=iP(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Os({paths:e.paths,state:t.state}),a=await In({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await Dt(e.paths,e.name),s=o?{...nP(e.paths,t.state),projectRoot:"."}:nP(e.paths,t.state),c=fd(t.state,n),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?IF(e.paths,o):[],d=o?(()=>{let v=o.children.filter(({status:N})=>N==="pending"||N==="ready").length,m=o.children.filter(({status:N})=>N==="active"||N==="verified").length,p=o.children.filter(({status:N})=>N==="integrated"||N==="archived").length,b=o.children.filter(({status:N})=>N==="blocked"||N==="needs-reverify").length,g=o.children.filter(({status:N})=>N==="active"||N==="blocked"||N==="needs-reverify").slice(0,16).map(N=>({name:N.name,summary:N.summary,projectRoot:N.task?.projectRoot??N.projectRoot?"<worktree>":null,reason:md(N.blocker,u)})),S=o.children.flatMap(({blocker:N})=>{let k=md(N,u);return k?[k]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:m,integrated:p,blocked:b,active:g,agents:{working:o.children.filter(({task:N})=>N!==null).length,completed:p},risks:S,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&p===o.children.length?"parent-verification":v>0?"dispatch-ready-child":b>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let v=o?.stateVersion??0,m=AF(t.state,o,u),p=xF(e.cursor,t.state.state_version,v),b=m.slice(p,p+32),g=p+b.length<m.length?CF(t.state.state_version,v,p+b.length):null;return{items:b,nextCursor:g,supervisorStateVersion:v}})():null,h=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:_F(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:i.blockers,workspace:s,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((v,m)=>({...v,[m.status]:(v[m.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...h?{supervisor:h}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:f.supervisorStateVersion}:{},items:f.items,nextCursor:f.nextCursor,nextPageArgs:f.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",f.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}async function aP(e){let t;try{t=await rP.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await rP.readFile(`${Mt(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}import Us from"path";import{realpathSync as UF}from"fs";var Ki={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function oP(e){return e?e.command?`${Ki.next} ${e.command}`:e.ask_user?`${Ki.next} ${e.ask_user}`:null:null}function sP(e,t){let i=[e.summary],r=oP(e.next);return r&&i.push(r),e.user_message&&i.push("",Ki.relay,e.user_message),t!==void 0&&i.push("",Ki.details,JSON.stringify(t,null,2)),`${i.join(`
|
|
269
269
|
`)}
|
|
270
|
-
`}function
|
|
271
|
-
`)}function J(e,t,i){return e==="zh-CN"?i:t}var
|
|
272
|
-
`)}}let i=t.continuation;if(
|
|
273
|
-
comet native next <change-name> --
|
|
274
|
-
comet native
|
|
270
|
+
`}function cP(e,t,i){let r=[e.summary],n=oP(e.next);return n&&r.push(n),e.user_message&&r.push("",Ki.relay,e.user_message),r.push("",`${Ki.detail} ${t}`),i!==void 0&&r.push("",Ki.details,JSON.stringify(i,null,2)),r.join(`
|
|
271
|
+
`)}function J(e,t,i){return e==="zh-CN"?i:t}var qm={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function lP(e,t){return typeof e=="string"&&qm[e]?J(t,qm[e].en,qm[e].zh):typeof e=="string"?e:""}function Wm(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 $F(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let i of e){if(!i||typeof i!="object")return null;let r=i.result;if(r!=="passed"&&r!=="failed"&&r!=="blocked"&&r!=="pending")return null;t[r]+=1}return t}function uP(e,t){let i=[];e.failed>0&&i.push(J(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&i.push(J(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&i.push(J(t,`${e.pending} pending`,`${e.pending} 项待验`));let r=J(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return i.length>0?`${r} (${i.join(", ")})`:r}function dP(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let i=t.userCommunication;return!!(i&&typeof i=="object"&&typeof i.required=="boolean"&&(i.message===null||typeof i.message=="string")&&typeof i.agentInstruction=="string")}function zm(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function OF(e,t,i){return e==="done"?J(i,"complete","已完成"):e==="await-user"?J(i,"waiting for a user decision","等待用户决定"):e==="blocked"?J(i,"paused: needs attention","已暂停,需要处理"):t?J(i,"waiting for a user decision","等待用户决定"):J(i,"ready to continue","可继续推进")}function HF(e,t,i){let r=zm(e),n=[];i&&n.push(i);let a=J(r,`Change ${e.change}`,`需求 ${e.change}`),o=lP(e.phase,r),s=OF(e.disposition,e.userCommunication.required,r);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(uP(t,r));let c=e.userCommunication,l=fP(e,r);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function fP(e,t){let i=e.userCommunication;if(e.disposition==="await-user"&&i.required)return{ask_user:J(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:J(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:J(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function DF(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function LF(e,t){let i=typeof e.name=="string"?e.name:"(unnamed)",r=lP(e.phase,t),n=e.status==="await-user"?J(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?J(t,"paused","已暂停"):e.status==="done"?J(t,"complete","已完成"):J(t,"in progress","进行中"),a=Wm(e.acceptance)?`${J(t,", ",",")}${uP(e.acceptance,t)}`:"";return` ${i} · ${r||String(e.phase??"?")} · ${n}${a}`}function MF(e){for(let t of e){let i=t.continuation;if(i?.userCommunication&&typeof i.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(i.userCommunication.agentInstruction))return"zh-CN"}return"en"}function FF(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 BF(e){if(e.healthy){let r=e.repaired?J("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):J("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=VF(e.continuation);return n?{summary:r,next:n}:{summary:r}}let i=Array.isArray(e.findings)?e.findings.length:0;return{summary:J("en",i>0?`Diagnostics found ${i} problem${i===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",i>0?`诊断发现 ${i} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:J("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function VF(e){return dP(e)?fP(e,zm(e)):void 0}function hP(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(FF(t))return BF(t);if(DF(t)){let r=MF(t.items);return{summary:[t.total===t.items.length?J(r,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):J(r,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>LF(a,r))].join(`
|
|
272
|
+
`)}}let i=t.continuation;if(dP(i))return HF(i,qF(t),WF(t,zm(i)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let r=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:J(r,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function qF(e){if(Wm(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t;if(Wm(i.acceptance))return i.acceptance;if(Array.isArray(i.acceptance))return $F(i.acceptance)}return null}function WF(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return J(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let i=e.migration;return i&&typeof i=="object"&&i.completed===!0?J(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function pP(e){let i=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:J("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof i.change=="string"?{next:{command:`comet native status ${i.change} --json`}}:{}};case"baseline-incomplete":return{summary:J("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:J("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:J("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:J("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:J("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:J("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:J("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:J("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var mP=["--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."],Gm=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:mP,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
|
|
273
|
+
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>]
|
|
274
|
+
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Select how a multi-child Supervisor proceeds while preparing its Shape confirmation; final Shape confirmation is a later, separate step.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
275
|
+
comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, and the exact next continuation, or the completed Archive transaction and workspace finish result. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Jm(e,t){return`${e}:
|
|
275
276
|
${t.map(i=>` ${i}`).join(`
|
|
276
|
-
`)}`}function
|
|
277
|
-
${i.output}`),i.examples&&r.push("",
|
|
277
|
+
`)}`}function zF(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Gm[i]||t.length>1&&Gm[t[0]]?.subcommands?i:t[0]}function JF(e=[]){let t=zF(e),i=Gm[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Jm("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...mP];return n&&n.length>0&&r.push("",Jm("Options",n)),r.push("",`Output:
|
|
278
|
+
${i.output}`),i.examples&&r.push("",Jm("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
|
|
278
279
|
`)}
|
|
279
|
-
`}}var
|
|
280
|
-
`}function
|
|
281
|
-
`}:e.error?{exitCode:e.exitCode,stderr:r?
|
|
282
|
-
${
|
|
280
|
+
`}}var GF=JF().usage;var R5=10*1024*1024,Vt=class extends Error{};function Ks(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new Vt(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function vd(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Vt(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new Vt(`${t} requires a value`);return e.splice(r,2),n}function gP(e){if(e.length>0)throw new Vt(`Unexpected argument: ${e[0]}`)}function Um(e,t){let i=Us.normalize(vP(e)),r=Us.normalize(vP(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function vP(e){let t=Us.resolve(e);try{return UF.native(t)}catch{return t}}function KF(e){let t=Us.resolve(e),i=fe(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=fe(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Um(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Um(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:Um(process.cwd(),i.currentWorktreeRoot)?Us.resolve(process.cwd()):i.currentWorktreeRoot}async function wP(e){return e?KF(e):gh(process.cwd())}async function yP(e){let t=await ye(e);return qe(e,t?.native.artifact_root??"docs")}function NP(e){return JSON.stringify(e,null,2)+`
|
|
281
|
+
`}function Yi(e,t,i){return{command:e,exitCode:0,data:t,text:i??NP(t)}}function YF(e,t){if(t instanceof Vt)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Xu)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 Ms)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof ss)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 cs)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 Hu)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof ka)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 Fr)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof xs)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function bP(e,t){let i=YF(e,t),r=i.error;if(!r)return i;let n=pP({code:r.code,message:r.message,data:i.data});return n?{...i,envelope:n}:i}function kP(e,t,i=!1){let r=e.envelope??hP(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...r===void 0?{}:{summary:r.summary,...r.next===void 0?{}:{next:r.next},...r.user_message===void 0?{}:{user_message:r.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
282
|
+
`}:e.error?{exitCode:e.exitCode,stderr:r?cP(r,e.error.message,i?e.data:void 0):e.error.message}:r?{exitCode:e.exitCode,stdout:sP(r,i?e.data:void 0)}:i&&e.text!==void 0&&e.data!==void 0&&e.text!==NP(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
283
|
+
${Ki.details}
|
|
283
284
|
${JSON.stringify(e.data,null,2)}
|
|
284
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}async function
|
|
285
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}async function Ys(e,t){let i=await Os({paths:e,state:t});return fd(t,i)}async function XF(e){let t;try{t=await PP.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort((i,r)=>i.localeCompare(r,"en"))}function QF(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function SP(e,t){let i;try{i=await PP.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let r=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${QF(t)}$`,"u"),n=i.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&r.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:gd.join(e.archiveDir,n.name)}:null}function ZF(e){let t=new Map;for(let i of e){let r=[i.severity,i.code,i.message,i.path??""].join("\0");t.set(r,i)}return[...t.values()]}function Xs(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function EP(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:gd.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}function eB(e,t){return t.status==="repairable-legacy-overlay"?{severity:"error",code:"portable-supervisor-overlay-stale",message:t.message,path:t.file,repair:"continue",repairCommand:`comet native doctor ${e} --repair`}:t.status==="incompatible"?{severity:"error",code:"portable-supervisor-overlay-incompatible",message:t.message,path:t.file}:null}async function tB(e,t){let i=[],r=[];for(let n of await Zy(e)){let a=hn(n);if(t&&a.change!==t)continue;let o=gd.join(e.transactionsDir,n);try{let s=await Jo(e,n);if(!s)continue;i.push(s),r.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){r.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:i,findings:r}}async function Km(e,t){let i=Ks(e,"--repair"),r=vd(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new Vt("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();gP(e);let a=await yP(t),o=await tB(a,n);if(n&&o.findings.length>0){if(r)throw new Vt("--strategy is only available to the legacy transaction doctor");let d=await Gr(a,n)?await Tn({paths:a,name:n,details:!0}):void 0;if(i&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let v=await Lm({paths:a,name:n});return Yi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:v.transactionId},state:v.state,continuation:await Ys(a,v.state)})}let h=await Gs({paths:a,name:n});return Yi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:await Ys(a,h)})}return Xs({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await Gr(a,n)){if(r)throw new Vt("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([SP(a,n),Bm(a,n)]);if(u){let p=await Tn({paths:a,name:n,details:!0});return Xs({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[u],continuation:p.continuation})}if(d&&!i){let p=await Tn({paths:a,name:n,details:!0});return Xs({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[EP(a,n)],continuation:p.continuation})}let f=await zi(a,n),h=await In({paths:a,state:f}),v=eB(n,h);if(v&&(h.status==="incompatible"||!i)){let p=await Tn({paths:a,name:n,details:!0});return Xs({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[v],continuation:p.continuation})}if(i){if(d){let b=await Gs({paths:a,name:n});return Yi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:b.schema,stateVersion:b.state_version},state:b,continuation:await Ys(a,b)})}let p=await ZE({paths:a,name:n});return Yi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:p,continuation:await Ys(a,p.state)})}let m=await Tn({paths:a,name:n,details:!0});return Yi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:m,continuation:m.continuation})}if(n){if(i){let u=await Gs({paths:a,name:n});return Yi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Ys(a,u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await aP(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new Vt("--strategy is only available to the legacy transaction doctor");if(i){let k=await Js({paths:a,repair:!0,projectOnly:!0}),E=[];for(let w of c.transactions)w.kind==="archive"?await Lm({paths:a,name:w.change}):await Gs({paths:a,name:w.change}),E.push({kind:w.kind,change:w.change,transactionId:w.journal.id});let R=await Km([],t),y=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...y,repaired:!0,repairedPortableTransactions:E,repairFindings:k.findings}}}let u=await XF(a),d=new Set(s),f=new Set(c.transactions.filter(k=>k.kind==="migration").map(({change:k})=>k)),h=u.filter(k=>!d.has(k)),[v,m,p,b,g]=await Promise.all([Promise.all(s.map(k=>Tn({paths:a,name:k}))),Promise.all(s.map(k=>SP(a,k))),Promise.all(s.map(k=>Bm(a,k))),Promise.all(h.map(k=>Js({paths:a,name:k}))),Js({paths:a,projectOnly:!0})]),S=ZF([...m.filter(k=>k!==null),...s.flatMap((k,E)=>p[E]&&!f.has(k)?[EP(a,k)]:[]),...c.findings,...h.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:gd.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...b.flatMap(({findings:k})=>k),...g.findings]),N={healthy:S.every(k=>k.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:v,legacyChanges:h,findings:S};return N.healthy?Yi("doctor",N):Xs(N)}let l=await Js({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?Yi("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}async function RP(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Ks(n,"--json"),Ks(n,"--verbose"),c=vd(n,"--project-root");let d=[...n,...a],f=await wP(c);l=await t(d,f)}catch(d){l=bP(e,d)}let u=kP(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
285
286
|
`)?"":`
|
|
286
|
-
`)),u.exitCode}process.exitCode=await
|
|
287
|
+
`)),u.exitCode}process.exitCode=await RP("doctor",Km);
|