@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
|
@@ -57,7 +57,7 @@ ${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comme
|
|
|
57
57
|
${a.comment}`:i.comment}i=n}e.items[r]=fi.isPair(i)?i:new Yn.Pair(i)}}else t("Expected a sequence for this tag");return e}function Us(e,t,r){let{replacer:i}=r,n=new yh.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Yn.createPair(s,c,r))}return n}var Nh={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Gs,createNode:Us};hi.createPairs=Us;hi.pairs=Nh;hi.resolvePairs=Gs});var Zn=g(Qn=>{"use strict";var Ks=P(),Xn=Re(),Wt=$e(),bh=Oe(),Ys=pi(),Ge=class e extends bh.YAMLSeq{constructor(){super(),this.add=Wt.YAMLMap.prototype.add.bind(this),this.delete=Wt.YAMLMap.prototype.delete.bind(this),this.get=Wt.YAMLMap.prototype.get.bind(this),this.has=Wt.YAMLMap.prototype.has.bind(this),this.set=Wt.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Ks.isPair(n)?(a=Xn.toJS(n.key,"",r),o=Xn.toJS(n.value,a,r)):a=Xn.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Ys.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Ge.tag="tag:yaml.org,2002:omap";var kh={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ge,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Ys.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Ks.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Ge,r)},createNode:(e,t,r)=>Ge.from(e,t,r)};Qn.YAMLOMap=Ge;Qn.omap=kh});var tc=g(ea=>{"use strict";var Xs=$();function Qs({value:e,source:t},r){return t&&(e?Zs:ec).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Zs={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 Xs.Scalar(!0),stringify:Qs},ec={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 Xs.Scalar(!1),stringify:Qs};ea.falseTag=ec;ea.trueTag=Zs});var rc=g(mi=>{"use strict";var Sh=$(),ta=ut(),Eh={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:ta.stringifyNumber},Ch={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():ta.stringifyNumber(e)}},Ph={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 Sh.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:ta.stringifyNumber};mi.float=Ph;mi.floatExp=Ch;mi.floatNaN=Eh});var nc=g(Jt=>{"use strict";var ic=ut(),zt=e=>typeof e=="bigint"||Number.isInteger(e);function vi(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function ra(e,t,r){let{value:i}=e;if(zt(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return ic.stringifyNumber(e)}var xh={identify:zt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>vi(e,2,2,r),stringify:e=>ra(e,2,"0b")},Rh={identify:zt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>vi(e,1,8,r),stringify:e=>ra(e,8,"0")},Ah={identify:zt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>vi(e,0,10,r),stringify:ic.stringifyNumber},_h={identify:zt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>vi(e,2,16,r),stringify:e=>ra(e,16,"0x")};Jt.int=Ah;Jt.intBin=xh;Jt.intHex=_h;Jt.intOct=Rh});var na=g(ia=>{"use strict";var yi=P(),gi=Ie(),wi=$e(),Ue=class e extends wi.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;yi.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new gi.Pair(t.key,null):r=new gi.Pair(t,null),wi.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=wi.findPair(this.items,t);return!r&&yi.isPair(i)?yi.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=wi.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new gi.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(gi.createPair(o,null,i));return a}};Ue.tag="tag:yaml.org,2002:set";var Th={collection:"map",identify:e=>e instanceof Set,nodeClass:Ue,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Ue.from(e,t,r),resolve(e,t){if(yi.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Ue,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ia.YAMLSet=Ue;ia.set=Th});var oa=g(Ni=>{"use strict";var Ih=ut();function aa(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function ac(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Ih.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var jh={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>aa(e,r),stringify:ac},$h={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=>aa(e,!1),stringify:ac},oc={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(oc.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=aa(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$/,"")??""};Ni.floatTime=$h;Ni.intTime=jh;Ni.timestamp=oc});var lc=g(cc=>{"use strict";var Oh=ct(),Hh=si(),Dh=lt(),Lh=Vt(),Bh=Kn(),sc=tc(),sa=rc(),bi=nc(),Mh=Zr(),Fh=Zn(),Vh=pi(),qh=na(),ca=oa(),Wh=[Oh.map,Dh.seq,Lh.string,Hh.nullTag,sc.trueTag,sc.falseTag,bi.intBin,bi.intOct,bi.int,bi.intHex,sa.floatNaN,sa.floatExp,sa.float,Bh.binary,Mh.merge,Fh.omap,Vh.pairs,qh.set,ca.intTime,ca.floatTime,ca.timestamp];cc.schema=Wh});var yc=g(da=>{"use strict";var hc=ct(),zh=si(),pc=lt(),Jh=Vt(),Gh=Fn(),la=qn(),ua=zn(),Uh=Vs(),Kh=zs(),mc=Kn(),Gt=Zr(),vc=Zn(),gc=pi(),uc=lc(),wc=na(),ki=oa(),dc=new Map([["core",Uh.schema],["failsafe",[hc.map,pc.seq,Jh.string]],["json",Kh.schema],["yaml11",uc.schema],["yaml-1.1",uc.schema]]),fc={binary:mc.binary,bool:Gh.boolTag,float:la.float,floatExp:la.floatExp,floatNaN:la.floatNaN,floatTime:ki.floatTime,int:ua.int,intHex:ua.intHex,intOct:ua.intOct,intTime:ki.intTime,map:hc.map,merge:Gt.merge,null:zh.nullTag,omap:vc.omap,pairs:gc.pairs,seq:pc.seq,set:wc.set,timestamp:ki.timestamp},Yh={"tag:yaml.org,2002:binary":mc.binary,"tag:yaml.org,2002:merge":Gt.merge,"tag:yaml.org,2002:omap":vc.omap,"tag:yaml.org,2002:pairs":gc.pairs,"tag:yaml.org,2002:set":wc.set,"tag:yaml.org,2002:timestamp":ki.timestamp};function Xh(e,t,r){let i=dc.get(t);if(i&&!e)return r&&!i.includes(Gt.merge)?i.concat(Gt.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(dc.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(Gt.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?fc[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(fc).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},[])}da.coreKnownTags=Yh;da.getTags=Xh});var pa=g(Nc=>{"use strict";var fa=P(),Qh=ct(),Zh=lt(),ep=Vt(),Si=yc(),tp=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ha=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Si.getTags(t,"compat"):t?Si.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Si.coreKnownTags:{},this.tags=Si.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,fa.MAP,{value:Qh.map}),Object.defineProperty(this,fa.SCALAR,{value:ep.string}),Object.defineProperty(this,fa.SEQ,{value:Zh.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?tp:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Nc.Schema=ha});var kc=g(bc=>{"use strict";var rp=P(),ma=Bt(),Ut=Ot();function ip(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=ma.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Ut.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(rp.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Ut.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=ma.stringify(e.contents,n,()=>s=null,c);s&&(l+=Ut.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(ma.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
58
|
`)?(r.push("..."),r.push(Ut.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(Ut.indentComment(a(c),"")))}return r.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}bc.stringifyDocument=ip});var Kt=g(Sc=>{"use strict";var np=jt(),dt=qr(),
|
|
60
|
+
`}bc.stringifyDocument=ip});var Kt=g(Sc=>{"use strict";var np=jt(),dt=qr(),Z=P(),ap=Ie(),op=Re(),sp=pa(),cp=kc(),va=Br(),lp=Nn(),up=$t(),ga=yn(),wa=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Z.NODE_TYPE,{value:Z.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new ga.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[Z.NODE_TYPE]:{value:Z.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=Z.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){ft(this.contents)&&this.contents.add(t)}addIn(t,r){ft(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=va.anchorNames(this);t.anchor=!r||i.has(r)?va.findNewAnchor(r||"a",i):r}return new np.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,w=r.filter(m).map(String);w.length>0&&(r=r.concat(w)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=i??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=va.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=up.createNode(t,u,v);return s&&Z.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new ap.Pair(n,a)}delete(t){return ft(this.contents)?this.contents.delete(t):!1}deleteIn(t){return dt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):ft(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Z.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return dt.isEmptyPath(t)?!r&&Z.isScalar(this.contents)?this.contents.value:this.contents:Z.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Z.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return dt.isEmptyPath(t)?this.contents!==void 0:Z.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=dt.collectionFromPath(this.schema,[t],r):ft(this.contents)&&this.contents.set(t,r)}setIn(t,r){dt.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=dt.collectionFromPath(this.schema,Array.from(t),r):ft(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new ga.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new ga.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new sp.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=op.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?lp.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return cp.stringifyDocument(this,t)}};function ft(e){if(Z.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Sc.Document=wa});var Qt=g(Xt=>{"use strict";var Yt=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},ya=class extends Yt{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Na=class extends Yt{constructor(t,r,i){super("YAMLWarning",t,r,i)}},dp=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
@@ -166,38 +166,39 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
|
|
|
166
166
|
# 可选值:true | false`}};function $l(e,t){return vt[t][e]}function sv(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in vt.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in vt.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in vt.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in vt.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in vt.en)return s}return null}function cr(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,or.stringify)(e).trimEnd().split(`
|
|
167
167
|
`)){let s=sv(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of $l(s,t).split(`
|
|
168
168
|
`))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
|
|
169
|
-
`)}function cv(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Le.posix.isAbsolute(r)||Le.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Xe(e){let t=cv(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Ol(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Oi(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Le.posix.isAbsolute(i)||Le.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function ke(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Hl(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Za(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>ji)throw new Error(`${t} exceeds ${ji} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>$i)throw new Error(`${t} contains more than ${$i} wildcard tokens`);return e}function jl(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>Za(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Ya(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function lv(e){if(e===void 0)return{...K,include:[...K.include],exclude:[...K.exclude]};let t=ke(e,"native.snapshot");return{include:jl(t.include,"native.snapshot.include",K.include),exclude:jl(t.exclude,"native.snapshot.exclude",K.exclude),max_files:Ya(t.max_files,K.max_files,"native.snapshot.max_files"),max_total_bytes:Ya(t.max_total_bytes,K.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Ya(t.max_duration_ms,K.max_duration_ms,"native.snapshot.max_duration_ms")}}function uv(e){if(e===void 0)return;let t=ke(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=ke(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:Xe(i),toArtifactRoot:Xe(n),stage:a,...o?{cleanup:o}:{}}}function dv(e){if(e===void 0)return;let t=ke(e,"native.finish");if(t.pull_request===void 0)return{};let r=ke(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Le.posix.isAbsolute(i[0])||Le.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??iv;if(!Number.isSafeInteger(n)||n<1||n>Il)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Il}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function fv(e,t={}){let r=ke(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??Xa;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=uv(r.pending_root_move),c=dv(r.finish);return{artifact_root:Xe(i),language:Hl(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:lv(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function hv(e){let t=ke(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Ol(t.artifact_layout),language:Hl(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function pv(e){let r=ke(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>Oi(i,`hook.allow_paths[${n}]`)))]}}function mv(e){if(e===void 0)return{...ar};let t=ke(e,"memory"),r=t.learning??ar.learning,i=t.retrieval??ar.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function eo(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function vv(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Le.posix.isAbsolute(r)||Le.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>_l)throw new Error(`${t} exceeds ${_l} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>Tl)throw new Error(`${t} contains more than ${Tl} wildcard tokens`);return r}function gv(e){let r=eo(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>vv(i,`knowledge.local.include[${n}]`)))]}}function wv(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function yv(e){let t=eo(e,"knowledge.remote"),r=wv(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function Nv(e){if(e===void 0)return{...Qa};let t=eo(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:gv(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:yv(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function bv(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function kv(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(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:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function gt(e,t={}){let r=(0,or.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=bv(n.ambient_resume),o=n.hook===void 0?void 0:pv(n.hook),s=mv(n.memory),c=Nv(n.knowledge),l=n.native===void 0?void 0:fv(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:hv(n.classic),d=kv(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 Dl(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 Ll(e){let t=e.knowledge??{...Qa};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...ar},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:Dl(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 U(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function lr(e,t){let r=Ll(t),i=gt((0,or.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...U(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=U(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=U(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...U(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...U(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=U(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=U(a.finish);o.finish={...s,pull_request:{...U(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...U(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=U(a.pending_root_move),c=Dl(i.native.pending_root_move),l=U(s.cleanup),u=U(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...U(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function Hi(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...ar},knowledge:{...Qa},native:{artifact_root:Xe(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Xa,snapshot:{...K,include:[...K.include],exclude:[...K.exclude]}}}}import{createHash as Ev}from"crypto";import{promises as Bi}from"fs";import Me from"path";import{constants as Di,promises as Qe}from"fs";function Be(e){return e!==0&&e!==0n&&e!=="0"}function he(e,t){return Be(e.dev)&&Be(t.dev)&&Be(e.ino)&&Be(t.ino)}function I(e,t){let r=Be(e.dev)&&Be(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Be(e.ino)&&Be(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var oe=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function to(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Bl(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ur(e){return{dev:e.dev,ino:e.ino,birthtime:to(e)}}function Li(e,t){let r=ur(e),i=ur(t);return he(r,i)?I(r,i):I(r,i)&&to(e)===to(t)&&Bl(e)===Bl(t)&&e.size===t.size}async function wt(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await Qe.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new oe("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new oe("too-large",`${i} exceeds ${t} bytes`);let o=await Qe.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ur(a)});let s=process.platform==="win32"?Di.O_RDONLY:Di.O_RDONLY|Di.O_NOFOLLOW|Di.O_NONBLOCK,c;try{c=await Qe.open(e,s)}catch(l){throw l.code==="ELOOP"?new oe("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Qe.lstat(e,{bigint:n}),Qe.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Li(a,l)||!Li(a,u))throw new oe("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ur(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:b}=await c.read(v,0,Math.min(v.length,y),null);if(b===0)break;if(p+=b,p>t)throw new oe("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,b)))}await r.hooks?.beforeFinalCheck?.();let[h,m,w]=await Promise.all([c.stat({bigint:n}),Qe.lstat(e,{bigint:n}),Qe.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||w!==o||!Li(a,h)||!Li(a,m))throw new oe("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:ur(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:w}}finally{await c.close()}}function Sv(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ro(e,t){let r=Me.relative(e,t);return r===""||!Me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Me.sep}`)}async function Ml(e,t){let r=Me.resolve(e),i=await Bi.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Bi.realpath(r)}async function Fl(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Me.join(n,r[a]);let o;try{o=await Bi.lstat(n)}catch(u){if(Sv(u))return{exists:!1,kind:"missing"};throw u}let s=Me.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await Bi.realpath(n);if(!ro(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function yt(e,t,r){let i=Oi(t,r.label),n=Me.resolve(e),a=await Ml(n,r.label),o=i.split("/"),s=Me.resolve(n,...o);if(!ro(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Fl(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Fe(e,t,r,i){let n=await yt(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Ml(n.projectRoot,i.label);return wt(n.target,r,{...i,verify:async(o,s)=>{if(!ro(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Fl(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var dr=".comet/config.yaml";function io(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function Cv(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Mi(e,t={}){return(await fr(e,t)).document}async function Vl(e){try{return(await Fe(e,dr,sr,{label:dr})).bytes}catch(t){if(Cv(t))return null;throw t}}function ql(e){return e?{exists:!0,sha256:Ev("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Fi(e){return ql(await Vl(e))}async function fr(e,t={}){let r=await Vl(e);return{document:r?gt(r.toString("utf8"),t):null,identity:ql(r)}}async function no(e){return(await Mi(e))?.config??null}var Rb=16*1024;async function ao(e,t){if(!t)return;let r=await Fi(e);if(!io(r,t))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as Av}from"crypto";import{promises as B}from"fs";import se from"path";function Vi(e,t){let r=se.relative(e,t);return r===""||!se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${se.sep}`)}function _v(e,t){return I({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function qi(e,t){return I({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Tv(e,t){return qi(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Wl(e){let t=await B.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 B.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Nt(e){for(let t of e){let r=await B.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!_v(t,r)||await B.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Iv(e,t,r){let[i,n]=await Promise.all([B.lstat(e),B.realpath(e),r?Nt(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!qi(i,t)||r&&!Vi(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function jv(e,t){let r=se.resolve(e),i=se.resolve(t);if(!Vi(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Wl(r)],a=se.relative(r,i).split(se.sep).filter(Boolean),o=r;for(let s of a){await Nt(n),o=se.join(o,s);try{await B.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Wl(o);if(!Vi(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Nt(n),n}async function $v(e){let t;try{t=await B.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function zl(e,t,r={}){let i=se.dirname(e),n=r.containedRoot?await jv(r.containedRoot,i):null;n||await B.mkdir(i,{recursive:!0});let a=se.join(i,`.${se.basename(e)}.${Av()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await B.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([B.lstat(a),B.realpath(a)]);if(await Nt(n),!l.isFile()||l.isSymbolicLink()||!qi(s,l)||!Vi(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(),!qi(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await Iv(a,c,n),await r.beforeCommit?.(),n){await Nt(n);let l=await B.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!Tv(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await B.link(a,e),await B.unlink(a)):await B.rename(a,e),await $v(i)}catch(l){if(await o?.close(),!n)await B.rm(a,{force:!0});else try{await Nt(n),await B.rm(a,{force:!0})}catch{}throw l}}async function J(e,t,r={}){await zl(e,t,r)}async function Jl(e,t,r={}){await zl(e,t,r)}async function Y(e,t,r={}){await J(e,JSON.stringify(t,null,2)+`
|
|
170
|
-
`,r)}import{existsSync as Gl,promises as Ze}from"fs";import A from"path";import Ov from"os";var Wi=".comet/config.yaml",Hv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function oo(e){try{return await Ze.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Dv(e){try{let t=await Ze.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function kt(e,t){let r=A.relative(e,t);return r===""||!A.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${A.sep}`)}async function bt(e){let t=[],r=e;for(;!await oo(r);){let n=A.dirname(r);if(n===r)break;t.push(A.basename(r)),r=n}let i=await Ze.realpath(r);return A.resolve(i,...t.reverse())}async function so(e){try{return(await Ze.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function co(e){let t=A.resolve(e);try{(await Ze.stat(t)).isDirectory()||(t=A.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=A.resolve(Ov.homedir());for(;;){if(!(t===i&&r!==i)){let o=A.join(t,...Wi.split("/")),s=t===r||await Dv(o);if(await oo(o)&&s)return t}if(await oo(A.join(t,".git")))return t;let a=A.dirname(t);if(a===t)return r;t=a}}function pr(e){return Xe(e)}async function Lv(e,t){let r=pr(t),i=A.resolve(e,...r.split("/")),n=await Ze.realpath(e),a=await bt(i);if(!kt(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function pe(e,t){let r=pr(t),i=await Lv(e,r),n=A.join(i,"comet");if(await so(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([bt(i),bt(n)]);if(!kt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=A.resolve(e),c=A.join(s,".comet","runtime","native");if(await so(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Ze.realpath(s),bt(c)]);if(!kt(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:A.join(e,...Wi.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:A.join(n,"specs"),changesDir:A.join(n,"changes"),archiveDir:A.join(n,"archive"),runtimeDir:c,changesRuntimeDir:A.join(c,"changes"),locksDir:A.join(c,"locks"),transactionsDir:A.join(c,"transactions")}}function Ul(e){if(!Hv.test(e))throw new Error(`Invalid Native change name: ${e}`)}function mr(e,t){Ul(t);let r=A.join(e.changesRuntimeDir,t);if(!V(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Bv(e,t){Ul(t);let r=A.join(e.changesDir,t,"runtime");if(!V(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function me(e,t){let r=mr(e,t);if(Gl(r))return r;let i=Bv(e,t);return Gl(i)?i:r}function ce(e,t){let r=A.resolve(t);if(V(e.runtimeDir,r))return e.runtimeDir;if(V(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function V(e,t){return kt(A.resolve(e),A.resolve(t))}async function O(e,t){let r=A.resolve(e),i=A.resolve(t);if(!kt(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await so(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([bt(r),bt(i)]);if(!kt(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}function Kl(e="docs",t="en"){return Hi(e,t)}async function
|
|
171
|
-
`,"utf8"),await r.sync(),i=tu(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Se(e);if(!i||!n||n.owner.id!==t.id||!Ji(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function Uv(e,t){let r=await O(e.runtimeDir,e.locksDir);await ee.mkdir(r,{recursive:!0});let i=await O(e.runtimeDir,q.join(r,eu));await ee.mkdir(i,{recursive:!0});let n=ru(t),a=q.join(i,`.${n.id}.tmp`),o=q.join(i,`${n.id}.claim`);try{let s=await iu(a,n);await ee.rename(a,o);let c=await Se(o);if(!c||!Ji(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await ee.rm(a,{force:!0})}}async function Kv(e){let t=q.dirname(e.file),r=!1,i=q.basename(e.file);for(let n of await ee.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=q.join(t,n.name);if(q.resolve(a)!==q.resolve(e.file))try{let o=await Se(a),s=Jv(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await uo(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function nu(e){let t=await Se(e.file);if(t){if(t.owner.id!==e.owner.id||!lo(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await uo(t,q.dirname(e.file))}}async function Yv(e,t){let r=Date.now()+Vv;for(;;){let i=await Uv(e,t);if(!await Kv(i))return i;if(await nu(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function Xv(e){let t=zi.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return zi.set(e,n),await t,()=>{r(),zi.get(e)===n&&zi.delete(e)}}async function au(e,t,r){let i=q.resolve(e.locksDir),n=Xl.getStore();if(n?.has(i))return r();let a=await Xv(i);try{let o=await Yv(e,t),s=new Map(n??[]);return s.set(i,o),await Xl.run(s,async()=>{try{return await r()}finally{await nu(o)}})}finally{a()}}async function vr(e,t,r){return au(e,`acquire ${t}`,async()=>{let i=await O(e.runtimeDir,e.locksDir);await ee.mkdir(i,{recursive:!0});let n=await O(e.runtimeDir,q.join(i,qv(t))),a=ru(r),o=await iu(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function gr(e){await Se(e.file)&&await au({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${q.basename(e.file)}`,async()=>{let t=await Se(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!lo(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=q.join(e.locksDir,eu);await uo(t,r)})}function Qv(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}import{createHash as Zv}from"node:crypto";import{constants as Gi,promises as x}from"node:fs";import T from"node:path";function ve(e,t){let r=T.relative(e,t);return r===""||!T.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${T.sep}`)}function ou(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Ui(e,t){return I({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function su(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function St(e,t){return I({...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 et(e,t){let r=await x.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await x.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function wr(e,t,r){let i=T.resolve(e),n=T.resolve(t);if(!ve(i,n))throw new Error(`${r} is outside its managed root`);let a=[await et(i,r)],o=i;for(let s of T.relative(i,n).split(T.sep).filter(Boolean)){await F(a,r),o=T.join(o,s);let c=await et(o,r);if(!ve(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await F(a,r),a}async function F(e,t){for(let r of e){let i=await x.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ui(r,i)||await x.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function eg(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function G(e){let t=ou(e.maxBytes),r=T.resolve(e.file),i=await wr(e.root,T.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>et(T.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await F(i,e.label);let a=await x.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=su(a),s=await x.realpath(r);if(!ve(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ve(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Gi.O_RDONLY:Gi.O_RDONLY|Gi.O_NOFOLLOW|Gi.O_NONBLOCK,l=await x.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([x.lstat(r),x.realpath(r)]);if(await F(i,e.label),await F(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!St(o,u)||!St(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await eg(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),x.lstat(r),x.realpath(r)]);if(await F(i,e.label),await F(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!St(o,v)||!St(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:Zv("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function tt(e){let t=await wr(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await x.readdir(e.directory,{withFileTypes:!0});else{let i=ou(e.maxEntries);r=[];let n=await x.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await F(t,e.label),{entries:r,verify:()=>F(t,e.label)}}async function tg(e){let t=T.resolve(e.directory),r=T.resolve(e.quarantine);if(T.dirname(r)!==T.dirname(t)||!ve(T.resolve(e.root),r)||r===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let i=await wr(e.root,T.dirname(t),e.label),n=await et(t,e.label);if(!ve(i[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await F(i,e.label);let a=await x.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Ui(n,a)||await x.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await x.lstat(r),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await x.rename(t,r),await F(i,e.label);let o=await x.lstat(r);if(!o.isDirectory()||o.isSymbolicLink()||!Ui(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(r);try{throw await x.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:r,parentChain:i,identity:n}}async function cu(e){await tg(e)}async function fo(e){let t=T.resolve(e.file),r=await wr(e.root,T.dirname(t),e.label),i=await x.lstat(t);if(!i.isFile()||i.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=su(i),a=await x.realpath(t);if(!ve(r[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await G({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([x.lstat(t),x.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!St(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await F(r,e.label);let[l,u]=await Promise.all([x.lstat(t),x.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!St(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await x.rm(t),await F(r,e.label)}async function ho(e){let t=T.resolve(e.directory),r=await wr(e.root,T.dirname(t),e.label),i=await et(t,e.label);if(!ve(r[0].realPath,i.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await F(r,e.label);let n=await x.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!Ui(i,n)||await x.realpath(t)!==i.realPath)throw new Error(`${e.label} changed before removal`);await x.rmdir(t),await F(r,e.label)}async function yr(e){let t=T.resolve(e.root),r=T.resolve(e.directory);if(!ve(t,r))throw new Error(`${e.label} is outside its managed root`);let i=[await et(t,e.label)],n=t;for(let a of T.relative(t,r).split(T.sep).filter(Boolean)){await F(i,e.label),n=T.join(n,a);try{await x.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await et(n,e.label);if(!ve(i[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);i.push(o)}await F(i,e.label)}async function Nr(e){let t=await G({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 Jl(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 x.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await G({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 r=await G({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(r.hash!==t.hash||r.size!==t.size)throw new Error(`${e.label} target could not be verified`);return r}import{promises as Yi}from"fs";import Ee from"path";import{TextDecoder as rg}from"util";var ig=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),ng=new Set(["id","type","source","target","staged","backup"]),ag=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),og=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),sg=new Set(["sequence","timestamp","type","operationId"]),du=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),fu=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),cg=256*1024,lg=1024*1024,hu=16*1024,Xi=1024,Ck=64*1024*1024;var pu=new rg("utf-8",{fatal:!0});function br(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function kr(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Ct(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function po(e,t){if(typeof e!="string"||e.length===0||Ee.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Ki(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function lu(e,t){if(po(e,t),e.includes("\\")||e!==Ee.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 ug(e,t){let r=br(e,`transaction operations[${t}]`);if(kr(r,ng,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);po(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&po(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function mu(e){let t=br(e,"Native Archive transaction journal");if(kr(t,ag,"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"||!du.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(!Ct(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ki(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=br(s,`Archive transaction operations[${c}]`);if(kr(l,og,`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`);lu(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&lu(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Ki(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(Ki(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`);Ki(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function mo(e){let t=br(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return mu(t);if(kr(t,ig,"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"||!du.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Ee.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Ee.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(!Ct(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(ug),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function vu(e,t){let r=br(e,`Native transaction event at line ${t}`);if(kr(r,sg,`Native transaction event at line ${t}`),r.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Ct(r.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof r.type!="string"||!fu.has(r.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let i=r.type==="operation-started"||r.type==="operation-completed";if(i&&(typeof r.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.operationId)||Buffer.byteLength(r.operationId,"utf8")>256)||!i&&r.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:r.sequence,timestamp:r.timestamp,type:r.type,...typeof r.operationId=="string"?{operationId:r.operationId}:{}}}function dg(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let i=0;i<e.length;i+=1){let n=t[i],a=e[i];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let r=[[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[i,n,a,o]of r){if(e.length<=i)continue;let s=e.slice(i,Math.min(i+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&&!Ct(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Ct(e)}function Et(e,t){return e.length<t.length&&t.startsWith(e)}function fg(e){let t='","operationId":"';if(Et(e,t))return!0;if(!e.startsWith(t))return!1;let r=e.slice(t.length),i=r.indexOf('"');if(i===-1)return r.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(r);let n=r.slice(0,i);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?Et(r.slice(i),'"}'):!1}function hg(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>hu)return!1;let r=`{"sequence":${t},"timestamp":"`;if(Et(e,r))return!0;if(!e.startsWith(r))return!1;let i=e.slice(r.length),n=i.slice(0,Math.min(24,i.length));if(!dg(n))return!1;if(i.length<24)return!0;if(!Ct(n))return!1;let a='","type":"',o=i.slice(24);if(Et(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of fu){if(Et(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(fg(l))return!0}else if(Et(l,'"}'))return!0}return!1}function pg(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>hu)throw new Error(`Native transaction event at line ${t} is too large`);return vu(JSON.parse(e),t)}function mg(e){let t=e.split(`
|
|
169
|
+
`)}function cv(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Le.posix.isAbsolute(r)||Le.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Xe(e){let t=cv(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Ol(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Oi(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Le.posix.isAbsolute(i)||Le.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function ke(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Hl(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Za(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>ji)throw new Error(`${t} exceeds ${ji} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>$i)throw new Error(`${t} contains more than ${$i} wildcard tokens`);return e}function jl(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>Za(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Ya(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function lv(e){if(e===void 0)return{...K,include:[...K.include],exclude:[...K.exclude]};let t=ke(e,"native.snapshot");return{include:jl(t.include,"native.snapshot.include",K.include),exclude:jl(t.exclude,"native.snapshot.exclude",K.exclude),max_files:Ya(t.max_files,K.max_files,"native.snapshot.max_files"),max_total_bytes:Ya(t.max_total_bytes,K.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Ya(t.max_duration_ms,K.max_duration_ms,"native.snapshot.max_duration_ms")}}function uv(e){if(e===void 0)return;let t=ke(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=ke(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:Xe(i),toArtifactRoot:Xe(n),stage:a,...o?{cleanup:o}:{}}}function dv(e){if(e===void 0)return;let t=ke(e,"native.finish");if(t.pull_request===void 0)return{};let r=ke(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Le.posix.isAbsolute(i[0])||Le.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??iv;if(!Number.isSafeInteger(n)||n<1||n>Il)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Il}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function fv(e,t={}){let r=ke(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??Xa;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=uv(r.pending_root_move),c=dv(r.finish);return{artifact_root:Xe(i),language:Hl(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:lv(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function hv(e){let t=ke(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Ol(t.artifact_layout),language:Hl(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function pv(e){let r=ke(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>Oi(i,`hook.allow_paths[${n}]`)))]}}function mv(e){if(e===void 0)return{...ar};let t=ke(e,"memory"),r=t.learning??ar.learning,i=t.retrieval??ar.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function eo(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function vv(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Le.posix.isAbsolute(r)||Le.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>_l)throw new Error(`${t} exceeds ${_l} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>Tl)throw new Error(`${t} contains more than ${Tl} wildcard tokens`);return r}function gv(e){let r=eo(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>vv(i,`knowledge.local.include[${n}]`)))]}}function wv(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function yv(e){let t=eo(e,"knowledge.remote"),r=wv(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function Nv(e){if(e===void 0)return{...Qa};let t=eo(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:gv(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:yv(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function bv(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function kv(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(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:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function gt(e,t={}){let r=(0,or.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=bv(n.ambient_resume),o=n.hook===void 0?void 0:pv(n.hook),s=mv(n.memory),c=Nv(n.knowledge),l=n.native===void 0?void 0:fv(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:hv(n.classic),d=kv(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 Dl(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 Ll(e){let t=e.knowledge??{...Qa};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...ar},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:Dl(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 U(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function lr(e,t){let r=Ll(t),i=gt((0,or.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...U(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=U(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=U(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...U(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...U(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=U(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=U(a.finish);o.finish={...s,pull_request:{...U(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...U(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=U(a.pending_root_move),c=Dl(i.native.pending_root_move),l=U(s.cleanup),u=U(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...U(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function Hi(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...ar},knowledge:{...Qa},native:{artifact_root:Xe(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Xa,snapshot:{...K,include:[...K.include],exclude:[...K.exclude]}}}}import{createHash as Ev}from"crypto";import{promises as Bi}from"fs";import Me from"path";import{constants as Di,promises as Qe}from"fs";function Be(e){return e!==0&&e!==0n&&e!=="0"}function he(e,t){return Be(e.dev)&&Be(t.dev)&&Be(e.ino)&&Be(t.ino)}function I(e,t){let r=Be(e.dev)&&Be(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Be(e.ino)&&Be(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var oe=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function to(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Bl(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ur(e){return{dev:e.dev,ino:e.ino,birthtime:to(e)}}function Li(e,t){let r=ur(e),i=ur(t);return he(r,i)?I(r,i):I(r,i)&&to(e)===to(t)&&Bl(e)===Bl(t)&&e.size===t.size}async function wt(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await Qe.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new oe("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new oe("too-large",`${i} exceeds ${t} bytes`);let o=await Qe.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ur(a)});let s=process.platform==="win32"?Di.O_RDONLY:Di.O_RDONLY|Di.O_NOFOLLOW|Di.O_NONBLOCK,c;try{c=await Qe.open(e,s)}catch(l){throw l.code==="ELOOP"?new oe("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Qe.lstat(e,{bigint:n}),Qe.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Li(a,l)||!Li(a,u))throw new oe("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ur(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:b}=await c.read(v,0,Math.min(v.length,y),null);if(b===0)break;if(p+=b,p>t)throw new oe("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,b)))}await r.hooks?.beforeFinalCheck?.();let[h,m,w]=await Promise.all([c.stat({bigint:n}),Qe.lstat(e,{bigint:n}),Qe.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||w!==o||!Li(a,h)||!Li(a,m))throw new oe("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:ur(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:w}}finally{await c.close()}}function Sv(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ro(e,t){let r=Me.relative(e,t);return r===""||!Me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Me.sep}`)}async function Ml(e,t){let r=Me.resolve(e),i=await Bi.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Bi.realpath(r)}async function Fl(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Me.join(n,r[a]);let o;try{o=await Bi.lstat(n)}catch(u){if(Sv(u))return{exists:!1,kind:"missing"};throw u}let s=Me.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await Bi.realpath(n);if(!ro(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function yt(e,t,r){let i=Oi(t,r.label),n=Me.resolve(e),a=await Ml(n,r.label),o=i.split("/"),s=Me.resolve(n,...o);if(!ro(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Fl(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Fe(e,t,r,i){let n=await yt(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Ml(n.projectRoot,i.label);return wt(n.target,r,{...i,verify:async(o,s)=>{if(!ro(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Fl(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var dr=".comet/config.yaml";function io(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function Cv(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Mi(e,t={}){return(await fr(e,t)).document}async function Vl(e){try{return(await Fe(e,dr,sr,{label:dr})).bytes}catch(t){if(Cv(t))return null;throw t}}function ql(e){return e?{exists:!0,sha256:Ev("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Fi(e){return ql(await Vl(e))}async function fr(e,t={}){let r=await Vl(e);return{document:r?gt(r.toString("utf8"),t):null,identity:ql(r)}}async function no(e){return(await Mi(e))?.config??null}var Ab=16*1024;async function ao(e,t){if(!t)return;let r=await Fi(e);if(!io(r,t))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as Av}from"crypto";import{promises as B}from"fs";import se from"path";function Vi(e,t){let r=se.relative(e,t);return r===""||!se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${se.sep}`)}function _v(e,t){return I({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function qi(e,t){return I({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Tv(e,t){return qi(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Wl(e){let t=await B.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 B.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Nt(e){for(let t of e){let r=await B.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!_v(t,r)||await B.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Iv(e,t,r){let[i,n]=await Promise.all([B.lstat(e),B.realpath(e),r?Nt(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!qi(i,t)||r&&!Vi(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function jv(e,t){let r=se.resolve(e),i=se.resolve(t);if(!Vi(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Wl(r)],a=se.relative(r,i).split(se.sep).filter(Boolean),o=r;for(let s of a){await Nt(n),o=se.join(o,s);try{await B.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Wl(o);if(!Vi(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Nt(n),n}async function $v(e){let t;try{t=await B.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function zl(e,t,r={}){let i=se.dirname(e),n=r.containedRoot?await jv(r.containedRoot,i):null;n||await B.mkdir(i,{recursive:!0});let a=se.join(i,`.${se.basename(e)}.${Av()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await B.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([B.lstat(a),B.realpath(a)]);if(await Nt(n),!l.isFile()||l.isSymbolicLink()||!qi(s,l)||!Vi(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(),!qi(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await Iv(a,c,n),await r.beforeCommit?.(),n){await Nt(n);let l=await B.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!Tv(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await B.link(a,e),await B.unlink(a)):await B.rename(a,e),await $v(i)}catch(l){if(await o?.close(),!n)await B.rm(a,{force:!0});else try{await Nt(n),await B.rm(a,{force:!0})}catch{}throw l}}async function J(e,t,r={}){await zl(e,t,r)}async function Jl(e,t,r={}){await zl(e,t,r)}async function Y(e,t,r={}){await J(e,JSON.stringify(t,null,2)+`
|
|
170
|
+
`,r)}import{existsSync as Gl,promises as Ze}from"fs";import A from"path";import Ov from"os";var Wi=".comet/config.yaml",Hv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function oo(e){try{return await Ze.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Dv(e){try{let t=await Ze.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function kt(e,t){let r=A.relative(e,t);return r===""||!A.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${A.sep}`)}async function bt(e){let t=[],r=e;for(;!await oo(r);){let n=A.dirname(r);if(n===r)break;t.push(A.basename(r)),r=n}let i=await Ze.realpath(r);return A.resolve(i,...t.reverse())}async function so(e){try{return(await Ze.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function co(e){let t=A.resolve(e);try{(await Ze.stat(t)).isDirectory()||(t=A.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=A.resolve(Ov.homedir());for(;;){if(!(t===i&&r!==i)){let o=A.join(t,...Wi.split("/")),s=t===r||await Dv(o);if(await oo(o)&&s)return t}if(await oo(A.join(t,".git")))return t;let a=A.dirname(t);if(a===t)return r;t=a}}function pr(e){return Xe(e)}async function Lv(e,t){let r=pr(t),i=A.resolve(e,...r.split("/")),n=await Ze.realpath(e),a=await bt(i);if(!kt(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function pe(e,t){let r=pr(t),i=await Lv(e,r),n=A.join(i,"comet");if(await so(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([bt(i),bt(n)]);if(!kt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=A.resolve(e),c=A.join(s,".comet","runtime","native");if(await so(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Ze.realpath(s),bt(c)]);if(!kt(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:A.join(e,...Wi.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:A.join(n,"specs"),changesDir:A.join(n,"changes"),archiveDir:A.join(n,"archive"),runtimeDir:c,changesRuntimeDir:A.join(c,"changes"),locksDir:A.join(c,"locks"),transactionsDir:A.join(c,"transactions")}}function Ul(e){if(!Hv.test(e))throw new Error(`Invalid Native change name: ${e}`)}function mr(e,t){Ul(t);let r=A.join(e.changesRuntimeDir,t);if(!V(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Bv(e,t){Ul(t);let r=A.join(e.changesDir,t,"runtime");if(!V(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function me(e,t){let r=mr(e,t);if(Gl(r))return r;let i=Bv(e,t);return Gl(i)?i:r}function ce(e,t){let r=A.resolve(t);if(V(e.runtimeDir,r))return e.runtimeDir;if(V(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function V(e,t){return kt(A.resolve(e),A.resolve(t))}async function O(e,t){let r=A.resolve(e),i=A.resolve(t);if(!kt(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await so(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([bt(r),bt(i)]);if(!kt(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}function Kl(e="docs",t="en"){return Hi(e,t)}async function ee(e){let t=(await Mi(e))?.config??null;return t?.native?t:null}async function Ve(e,t,r={}){let i=await fr(e,{allowPartialProject:!0}),n=lr(i.document?.value??{},t),a=Mv.join(e,...Wi.split("/"));await J(a,cr(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await ao(e,i.identity)}})}import{createHash as hw,randomUUID as pw}from"crypto";import{promises as We}from"fs";import j from"path";import{AsyncLocalStorage as Fv}from"async_hooks";import{randomUUID as Ql}from"crypto";import{promises as te}from"fs";import Zl from"os";import q from"path";var Yl=16*1024,eu=".coordinator",Vv=5e3,Xl=new Fv,zi=new Map;function qv(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function Wv(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function tu(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 Ji(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return he(r,i)?I(r,i):I(r,i)&&e.size===t.size}function lo(e,t){return Ji(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Se(e){let t,r;try{let i=await wt(e,Yl,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof oe?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Yl} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:Wv(JSON.parse(t.toString("utf8")),e),identity:tu(r)}}async function zv(e){return(await Se(e))?.owner??null}function Jv(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Zl.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Qv(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Gv(e,t){try{await te.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await te.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function uo(e,t){let r=await Se(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!lo(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await te.mkdir(t,{recursive:!0});let i=q.join(t,`${q.basename(e.file)}.${e.owner.id}.${Ql()}.removed`);try{await te.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Se(i);if(!n||n.owner.id!==e.owner.id||!Ji(n.identity,e.identity))throw await Gv(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await te.rm(i,{force:!0}),"removed"}function ru(e){return{id:Ql(),pid:process.pid,hostname:Zl.hostname(),createdAt:new Date().toISOString(),operation:e}}async function iu(e,t){let r;try{r=await te.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await zv(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
|
|
171
|
+
`,"utf8"),await r.sync(),i=tu(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Se(e);if(!i||!n||n.owner.id!==t.id||!Ji(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function Uv(e,t){let r=await O(e.runtimeDir,e.locksDir);await te.mkdir(r,{recursive:!0});let i=await O(e.runtimeDir,q.join(r,eu));await te.mkdir(i,{recursive:!0});let n=ru(t),a=q.join(i,`.${n.id}.tmp`),o=q.join(i,`${n.id}.claim`);try{let s=await iu(a,n);await te.rename(a,o);let c=await Se(o);if(!c||!Ji(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await te.rm(a,{force:!0})}}async function Kv(e){let t=q.dirname(e.file),r=!1,i=q.basename(e.file);for(let n of await te.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=q.join(t,n.name);if(q.resolve(a)!==q.resolve(e.file))try{let o=await Se(a),s=Jv(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await uo(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function nu(e){let t=await Se(e.file);if(t){if(t.owner.id!==e.owner.id||!lo(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await uo(t,q.dirname(e.file))}}async function Yv(e,t){let r=Date.now()+Vv;for(;;){let i=await Uv(e,t);if(!await Kv(i))return i;if(await nu(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function Xv(e){let t=zi.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return zi.set(e,n),await t,()=>{r(),zi.get(e)===n&&zi.delete(e)}}async function au(e,t,r){let i=q.resolve(e.locksDir),n=Xl.getStore();if(n?.has(i))return r();let a=await Xv(i);try{let o=await Yv(e,t),s=new Map(n??[]);return s.set(i,o),await Xl.run(s,async()=>{try{return await r()}finally{await nu(o)}})}finally{a()}}async function vr(e,t,r){return au(e,`acquire ${t}`,async()=>{let i=await O(e.runtimeDir,e.locksDir);await te.mkdir(i,{recursive:!0});let n=await O(e.runtimeDir,q.join(i,qv(t))),a=ru(r),o=await iu(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function gr(e){await Se(e.file)&&await au({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${q.basename(e.file)}`,async()=>{let t=await Se(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!lo(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=q.join(e.locksDir,eu);await uo(t,r)})}function Qv(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}import{createHash as Zv}from"node:crypto";import{constants as Gi,promises as x}from"node:fs";import T from"node:path";function ve(e,t){let r=T.relative(e,t);return r===""||!T.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${T.sep}`)}function ou(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Ui(e,t){return I({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function su(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function St(e,t){return I({...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 et(e,t){let r=await x.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await x.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function wr(e,t,r){let i=T.resolve(e),n=T.resolve(t);if(!ve(i,n))throw new Error(`${r} is outside its managed root`);let a=[await et(i,r)],o=i;for(let s of T.relative(i,n).split(T.sep).filter(Boolean)){await F(a,r),o=T.join(o,s);let c=await et(o,r);if(!ve(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await F(a,r),a}async function F(e,t){for(let r of e){let i=await x.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ui(r,i)||await x.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function eg(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function G(e){let t=ou(e.maxBytes),r=T.resolve(e.file),i=await wr(e.root,T.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>et(T.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await F(i,e.label);let a=await x.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=su(a),s=await x.realpath(r);if(!ve(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ve(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Gi.O_RDONLY:Gi.O_RDONLY|Gi.O_NOFOLLOW|Gi.O_NONBLOCK,l=await x.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([x.lstat(r),x.realpath(r)]);if(await F(i,e.label),await F(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!St(o,u)||!St(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await eg(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),x.lstat(r),x.realpath(r)]);if(await F(i,e.label),await F(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!St(o,v)||!St(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:Zv("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function tt(e){let t=await wr(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await x.readdir(e.directory,{withFileTypes:!0});else{let i=ou(e.maxEntries);r=[];let n=await x.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await F(t,e.label),{entries:r,verify:()=>F(t,e.label)}}async function tg(e){let t=T.resolve(e.directory),r=T.resolve(e.quarantine);if(T.dirname(r)!==T.dirname(t)||!ve(T.resolve(e.root),r)||r===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let i=await wr(e.root,T.dirname(t),e.label),n=await et(t,e.label);if(!ve(i[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await F(i,e.label);let a=await x.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Ui(n,a)||await x.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await x.lstat(r),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await x.rename(t,r),await F(i,e.label);let o=await x.lstat(r);if(!o.isDirectory()||o.isSymbolicLink()||!Ui(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(r);try{throw await x.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:r,parentChain:i,identity:n}}async function cu(e){await tg(e)}async function fo(e){let t=T.resolve(e.file),r=await wr(e.root,T.dirname(t),e.label),i=await x.lstat(t);if(!i.isFile()||i.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=su(i),a=await x.realpath(t);if(!ve(r[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await G({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([x.lstat(t),x.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!St(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await F(r,e.label);let[l,u]=await Promise.all([x.lstat(t),x.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!St(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await x.rm(t),await F(r,e.label)}async function ho(e){let t=T.resolve(e.directory),r=await wr(e.root,T.dirname(t),e.label),i=await et(t,e.label);if(!ve(r[0].realPath,i.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await F(r,e.label);let n=await x.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!Ui(i,n)||await x.realpath(t)!==i.realPath)throw new Error(`${e.label} changed before removal`);await x.rmdir(t),await F(r,e.label)}async function yr(e){let t=T.resolve(e.root),r=T.resolve(e.directory);if(!ve(t,r))throw new Error(`${e.label} is outside its managed root`);let i=[await et(t,e.label)],n=t;for(let a of T.relative(t,r).split(T.sep).filter(Boolean)){await F(i,e.label),n=T.join(n,a);try{await x.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await et(n,e.label);if(!ve(i[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);i.push(o)}await F(i,e.label)}async function Nr(e){let t=await G({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 Jl(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 x.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await G({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 r=await G({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(r.hash!==t.hash||r.size!==t.size)throw new Error(`${e.label} target could not be verified`);return r}import{promises as Yi}from"fs";import Ee from"path";import{TextDecoder as rg}from"util";var ig=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),ng=new Set(["id","type","source","target","staged","backup"]),ag=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),og=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),sg=new Set(["sequence","timestamp","type","operationId"]),du=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),fu=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),cg=256*1024,lg=1024*1024,hu=16*1024,Xi=1024,Pk=64*1024*1024;var pu=new rg("utf-8",{fatal:!0});function br(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function kr(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Ct(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function po(e,t){if(typeof e!="string"||e.length===0||Ee.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Ki(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function lu(e,t){if(po(e,t),e.includes("\\")||e!==Ee.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 ug(e,t){let r=br(e,`transaction operations[${t}]`);if(kr(r,ng,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);po(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&po(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function mu(e){let t=br(e,"Native Archive transaction journal");if(kr(t,ag,"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"||!du.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(!Ct(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ki(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=br(s,`Archive transaction operations[${c}]`);if(kr(l,og,`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`);lu(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&lu(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Ki(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(Ki(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`);Ki(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function mo(e){let t=br(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return mu(t);if(kr(t,ig,"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"||!du.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Ee.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Ee.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(!Ct(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(ug),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function vu(e,t){let r=br(e,`Native transaction event at line ${t}`);if(kr(r,sg,`Native transaction event at line ${t}`),r.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Ct(r.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof r.type!="string"||!fu.has(r.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let i=r.type==="operation-started"||r.type==="operation-completed";if(i&&(typeof r.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.operationId)||Buffer.byteLength(r.operationId,"utf8")>256)||!i&&r.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:r.sequence,timestamp:r.timestamp,type:r.type,...typeof r.operationId=="string"?{operationId:r.operationId}:{}}}function dg(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let i=0;i<e.length;i+=1){let n=t[i],a=e[i];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let r=[[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[i,n,a,o]of r){if(e.length<=i)continue;let s=e.slice(i,Math.min(i+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&&!Ct(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Ct(e)}function Et(e,t){return e.length<t.length&&t.startsWith(e)}function fg(e){let t='","operationId":"';if(Et(e,t))return!0;if(!e.startsWith(t))return!1;let r=e.slice(t.length),i=r.indexOf('"');if(i===-1)return r.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(r);let n=r.slice(0,i);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?Et(r.slice(i),'"}'):!1}function hg(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>hu)return!1;let r=`{"sequence":${t},"timestamp":"`;if(Et(e,r))return!0;if(!e.startsWith(r))return!1;let i=e.slice(r.length),n=i.slice(0,Math.min(24,i.length));if(!dg(n))return!1;if(i.length<24)return!0;if(!Ct(n))return!1;let a='","type":"',o=i.slice(24);if(Et(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of fu){if(Et(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(fg(l))return!0}else if(Et(l,'"}'))return!0}return!1}function pg(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>hu)throw new Error(`Native transaction event at line ${t} is too large`);return vu(JSON.parse(e),t)}function mg(e){let t=e.split(`
|
|
172
172
|
`),r=t.at(-1)==="";if(r&&t.pop(),t.length>Xi)throw new Error(`Native transaction event log exceeds ${Xi} events`);let i=[];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=!r&&n===t.length-1;try{i.push(pg(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&hg(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return i}function gu(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
173
173
|
`)}
|
|
174
|
-
`}function vg(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Ee.join(e.transactionsDir,t)}function Qi(e,t){let r=vg(e,t);return{directory:r,journal:Ee.join(r,"transaction.json"),events:Ee.join(r,"events.jsonl"),staged:Ee.join(r,"staged"),backups:Ee.join(r,"backups")}}async function rt(e,t){let r=Qi(e,t);return await Promise.all(Object.values(r).map(i=>O(e.runtimeDir,i))),r}async function wu(e,t,r={}){let i=await rt(e,t);try{await Yi.lstat(i.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await G({root:e.runtimeDir,file:i.events,maxBytes:lg,label:`Native transaction event log ${t}`,hooks:r.hooks}),a;try{a=pu.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=mg(a),s=gu(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 uu(e,t,r){let i=await wu(e,t);if(i.exists!==r.exists||i.hash!==r.hash||i.size!==r.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function vo(e,t,r,i){let n=await rt(e,t),a=await wu(e,t),o=a.events.find(c=>c.type===r&&c.operationId===i);if(o)return a.needsRepair&&await J(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>uu(e,t,a)}),o;if(a.events.length>=Xi)throw new Error(`Native transaction event log ${t} exceeds ${Xi} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:r,...i?{operationId:i}:{}};return vu(s,s.sequence),await Yi.mkdir(n.directory,{recursive:!0}),await J(n.events,gu([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>uu(e,t,a)}),s}async function yu(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=mo(t);let r=await rt(e,t.id);await Yi.mkdir(r.staged,{recursive:!0}),await Yi.mkdir(r.backups,{recursive:!0}),await Y(r.journal,t,{containedRoot:e.runtimeDir}),await vo(e,t.id,"prepared")}async function Sr(e,t,r={}){let i=await rt(e,t),n=await G({root:e.runtimeDir,file:i.journal,maxBytes:cg,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(pu.decode(n.bytes)),o=mo(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function gg(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=mo({...t,status:r});return await Y((await rt(e,t.id)).journal,i,{containedRoot:e.runtimeDir}),i}async function go(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await vo(e,t.id,r),r==="commit"?gg(e,t,"committed"):t}import{createHash as ow}from"node:crypto";import{promises as cn}from"node:fs";import qe from"node:path";import{execFileSync as wg}from"child_process";import en from"path";function Zi(e,t){return wg("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function yg(e,t){let r=en.normalize(e),i=en.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ge(e){try{let t=en.resolve(Zi(e,["rev-parse","--show-toplevel"])),i=Zi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?en.resolve(i.slice(9)):t,a=null;try{a=Zi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!yg(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Er(e,t){try{let r=Zi(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}import{createHash as Sg}from"node:crypto";import{promises as le}from"node:fs";import te from"node:path";import{TextDecoder as Eg}from"node:util";var Ng=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),bg=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function kg(e){return e.toLowerCase().startsWith(".env")}function Cr(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>kg(i))?"environment-file":r.some(i=>bg.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Ng.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var rn=1024*1024;function wo(e,t){let r=te.relative(e,t);return r===""||!te.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${te.sep}`)}function Cg(e){let t=te.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})||te.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Cr(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function Pg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function xg(e,t){return I({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function tn(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return he(r,i)?I(r,i):I(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Nu(e){let t=await le.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Rg(e,t){let r=te.resolve(e),i=te.resolve(t);if(!wo(r,i))throw new Error("Native artifact path is outside its root");let n=[await Nu(r)],a=r;for(let o of te.relative(r,i).split(te.sep).filter(Boolean)){a=te.join(a,o);let s=await Nu(a);if(!wo(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function bu(e){for(let t of e){let r=await le.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!xg(t,r)||await le.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function we(e){let t=Cg(e.ref),r=e.maxBytes===null?null:Pg(e.maxBytes??rn),i=te.resolve(e.root,...t.split("/")),n=await Rg(e.root,te.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await le.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await le.realpath(i);if(!wo(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await le.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),le.lstat(i),le.realpath(i)]);if(await bu(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!tn(a,c)||!tn(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let b=r===null?p.length:r+1-f,k=await s.read(p,0,Math.min(p.length,b),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),le.lstat(i),le.realpath(i)]);if(await bu(n),!h.isFile()||h.isSymbolicLink()||m!==o||!tn(c,v)||!tn(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let w=Buffer.concat(d,f),y;try{y=new Eg("utf-8",{fatal:!0}).decode(w)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:b})}return{ref:t,size:f,hash:e.includeHash===!1?null:Sg("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}var Pu=Rt(mt(),1);var yo={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:"验证预期"}},Ag={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:"结论"}},_g={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:"结论"}},Tg=new Map,ku=new Map;for(let e of Object.keys(yo)){for(let[t,r]of Object.entries(yo[e]))Tg.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Ag[e]))ku.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(_g[e]))ku.set(r.toLocaleLowerCase("en-US"),t)}function Ig(e,t){return yo[e][t]}function nn(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Ig(e,r)}
|
|
174
|
+
`}function vg(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Ee.join(e.transactionsDir,t)}function Qi(e,t){let r=vg(e,t);return{directory:r,journal:Ee.join(r,"transaction.json"),events:Ee.join(r,"events.jsonl"),staged:Ee.join(r,"staged"),backups:Ee.join(r,"backups")}}async function rt(e,t){let r=Qi(e,t);return await Promise.all(Object.values(r).map(i=>O(e.runtimeDir,i))),r}async function wu(e,t,r={}){let i=await rt(e,t);try{await Yi.lstat(i.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await G({root:e.runtimeDir,file:i.events,maxBytes:lg,label:`Native transaction event log ${t}`,hooks:r.hooks}),a;try{a=pu.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=mg(a),s=gu(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 uu(e,t,r){let i=await wu(e,t);if(i.exists!==r.exists||i.hash!==r.hash||i.size!==r.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function vo(e,t,r,i){let n=await rt(e,t),a=await wu(e,t),o=a.events.find(c=>c.type===r&&c.operationId===i);if(o)return a.needsRepair&&await J(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>uu(e,t,a)}),o;if(a.events.length>=Xi)throw new Error(`Native transaction event log ${t} exceeds ${Xi} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:r,...i?{operationId:i}:{}};return vu(s,s.sequence),await Yi.mkdir(n.directory,{recursive:!0}),await J(n.events,gu([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>uu(e,t,a)}),s}async function yu(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=mo(t);let r=await rt(e,t.id);await Yi.mkdir(r.staged,{recursive:!0}),await Yi.mkdir(r.backups,{recursive:!0}),await Y(r.journal,t,{containedRoot:e.runtimeDir}),await vo(e,t.id,"prepared")}async function Sr(e,t,r={}){let i=await rt(e,t),n=await G({root:e.runtimeDir,file:i.journal,maxBytes:cg,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(pu.decode(n.bytes)),o=mo(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function gg(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=mo({...t,status:r});return await Y((await rt(e,t.id)).journal,i,{containedRoot:e.runtimeDir}),i}async function go(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await vo(e,t.id,r),r==="commit"?gg(e,t,"committed"):t}import{createHash as ow}from"node:crypto";import{promises as cn}from"node:fs";import qe from"node:path";import{execFileSync as wg}from"child_process";import en from"path";function Zi(e,t){return wg("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function yg(e,t){let r=en.normalize(e),i=en.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ge(e){try{let t=en.resolve(Zi(e,["rev-parse","--show-toplevel"])),i=Zi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?en.resolve(i.slice(9)):t,a=null;try{a=Zi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!yg(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Er(e,t){try{let r=Zi(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}import{createHash as Sg}from"node:crypto";import{promises as le}from"node:fs";import re from"node:path";import{TextDecoder as Eg}from"node:util";var Ng=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),bg=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function kg(e){return e.toLowerCase().startsWith(".env")}function Cr(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>kg(i))?"environment-file":r.some(i=>bg.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Ng.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var rn=1024*1024;function wo(e,t){let r=re.relative(e,t);return r===""||!re.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${re.sep}`)}function Cg(e){let t=re.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})||re.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Cr(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function Pg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function xg(e,t){return I({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function tn(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return he(r,i)?I(r,i):I(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Nu(e){let t=await le.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Rg(e,t){let r=re.resolve(e),i=re.resolve(t);if(!wo(r,i))throw new Error("Native artifact path is outside its root");let n=[await Nu(r)],a=r;for(let o of re.relative(r,i).split(re.sep).filter(Boolean)){a=re.join(a,o);let s=await Nu(a);if(!wo(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function bu(e){for(let t of e){let r=await le.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!xg(t,r)||await le.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function we(e){let t=Cg(e.ref),r=e.maxBytes===null?null:Pg(e.maxBytes??rn),i=re.resolve(e.root,...t.split("/")),n=await Rg(e.root,re.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await le.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await le.realpath(i);if(!wo(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await le.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),le.lstat(i),le.realpath(i)]);if(await bu(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!tn(a,c)||!tn(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let b=r===null?p.length:r+1-f,k=await s.read(p,0,Math.min(p.length,b),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),le.lstat(i),le.realpath(i)]);if(await bu(n),!h.isFile()||h.isSymbolicLink()||m!==o||!tn(c,v)||!tn(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let w=Buffer.concat(d,f),y;try{y=new Eg("utf-8",{fatal:!0}).decode(w)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:b})}return{ref:t,size:f,hash:e.includeHash===!1?null:Sg("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}var Pu=Rt(mt(),1);var yo={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:"验证预期"}},Ag={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:"结论"}},_g={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:"结论"}},Tg=new Map,ku=new Map;for(let e of Object.keys(yo)){for(let[t,r]of Object.entries(yo[e]))Tg.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Ag[e]))ku.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(_g[e]))ku.set(r.toLocaleLowerCase("en-US"),t)}function Ig(e,t){return yo[e][t]}function nn(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Ig(e,r)}
|
|
175
175
|
`).join(`
|
|
176
|
-
`)}import{createHash as jg}from"crypto";function
|
|
177
|
-
${Eo(t)}`).digest("hex")}var
|
|
176
|
+
`)}import{createHash as jg}from"crypto";function ie(e){return jg("sha256").update(e).digest("hex")}var Qk={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var Zk=8*1024*1024;var eS=64*1024,tS=64*1024;var rS={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},iS={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var nS=(1n<<256n)-1n;var Mg=Rt(mt(),1);var NS=4*1024*1024;var Fg=null;function Vg(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Su(e,t){return(...r)=>{let i=Fg;if(i===null)return t(...r);let n=Vg(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var CS=Su("hookWritePolicy",async e=>(await no(e))?.hook??{allow_paths:[]});var NE=256*1024;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};var xu=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],sC=new Set(xu),Kg=new Set([...xu,"minimum_runtime_version","revision"]),cC=new Set([...Kg,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]);var an=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Pr=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},on=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},lC=nn("en");import{createHash as Yg}from"crypto";function ue(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function Xg(e,t){t.has(e)&&ue("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||ue("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&ue("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ue("symbol properties are not supported"),`[${e.map(i=>So(i,t)).join(",")}]`}finally{t.delete(e)}}function Qg(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&ue("only plain objects are supported"),t.has(e)&&ue("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ue("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&ue("accessor properties are not supported"),`${JSON.stringify(o)}:${So(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function So(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)||ue("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?Xg(e,t):Qg(e,t);case"bigint":case"function":case"symbol":case"undefined":return ue(`${typeof e} values are not supported`)}return ue("unsupported value type")}function Eo(e){return So(e,new Set)}function X(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 Yg("sha256").update(`${e}
|
|
177
|
+
${Eo(t)}`).digest("hex")}var gC=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ru=Object.freeze({maxCriteria:1024});var Au=Rt(mt(),1);var ju="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",BC=new RegExp(`^portable-archive-(${ju})\\.json$`,"u"),MC=new RegExp(`^portable-migration-(${ju})\\.json$`,"u");var xr=/^[a-f0-9]{64}$/u,$u=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,sw=16*1024,Po=process.platform;function Lu(e,t){let r=qe.relative(e,t);return qe.isAbsolute(r)||r===".."||r.startsWith(`..${qe.sep}`)?null:r.replaceAll("\\","/")||"."}function Bu(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Mu(e,t){if(e.length===0||Bu(e)||e.includes("\\")||qe.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=qe.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function xo(e,t){return ow("sha256").update(`${e}
|
|
178
178
|
${t}`).digest("hex")}async function Ou(e,t){let r=await cn.realpath(t),i=await cn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Po==="win32"?qe.normalize(r).toLowerCase():r;return xo(e,`${n}
|
|
179
179
|
${i.dev}
|
|
180
180
|
${i.ino}
|
|
181
181
|
${i.birthtimeMs}`)}async function Hu(e,t){let r=await cn.realpath(t),i=await cn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Po==="win32"?qe.normalize(r).toLowerCase():r;return xo(e,n)}function cw(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 Co(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Bu(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Fu(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Co(e.changeBranch,"Native workspace change branch"),Co(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 lw(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!$u.test(t.baseCommit)||typeof t.targetCommit!="string"||!$u.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Co(t.targetBranch,"Native workspace Git target branch")}function ln(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!xr.test(String(t.projectRootId))||!xr.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");cw(t.capturedAt),Mu(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&&!xr.test(String(t.projectRootPathId))||a&&!xr.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!xr.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&lw(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(Fu(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 Vu(e,t){return qe.join(me(e,t),"workspace.json")}function uw(e,t){let r=Vu(e,t),i=ce(e,r),n=Lu(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Mu(n,"Native workspace file ref")}}async function dw(e,t){try{let r=uw(e,t),i=await we({root:r.root,ref:r.ref,maxBytes:sw});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function qu(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Lu(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=ge(e.paths.projectRoot),i=r.isGitWorktree?Er(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:Er(e.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([Ou("comet.native.workspace-project-root.v2",e.paths.projectRoot),Ou("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Hu("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Hu("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&&Fu(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:xo("comet.native.workspace-session.v2",`${s}
|
|
182
182
|
${c}
|
|
183
|
-
${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return ln(p),p}async function bo(e){let t=await qu(e),r=Vu(e.paths,e.name),i=ce(e.paths,r);return await O(i,r),await Y(r,t,{containedRoot:i}),t}async function Pt(e,t){let r=await dw(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(ln(r),r)}async function sn(e){ln(e.identity);let t=await qu({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),Po==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function ko(e){if(ln(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 sn(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ge(e.paths.projectRoot);return e.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}var Ao=64*1024*1024,
|
|
184
|
-
`}function Ew(e){return hw("sha256").update(e).digest("hex")}function Cw(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 r=e,i=Object.keys(r).sort(),n=r.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof r.ref!="string"||r.ref.length===0||r.ref.includes("\\")||j.posix.normalize(r.ref)!==r.ref||r.ref.startsWith("/")||r.ref.split("/").includes("..")||Buffer.byteLength(r.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(r.type==="directory")return{ref:r.ref,type:"directory"};if(r.type!=="file"||typeof r.size!="number"||!Number.isSafeInteger(r.size)||r.size<0||typeof r.hash!="string"||!/^[a-f0-9]{64}$/u.test(r.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:r.ref,type:"file",size:r.size,hash:r.hash}}function Pw(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let i=e;if(JSON.stringify(Object.keys(i).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||i.schema!=="comet.native.root-move-cleanup.v1"||i.transactionId!==t||i.kind!==r||!Array.isArray(i.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=i.entries.map(Cw);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=j.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:r,entries:n}}async function xw(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},r=Sw(t);if(Buffer.byteLength(r,"utf8")>Gu)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await J(Uu(e.paths,e.id,e.kind),r,{containedRoot:e.paths.runtimeDir}),Ew(r)}async function Rw(e){let t=await G({root:e.paths.runtimeDir,file:Uu(e.paths,e.id,e.cleanup.kind),maxBytes:Gu,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 Pw(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Ro(e){let t=await Ar(e.quarantine,{rejectSymlinks:!0}),r=new Map(e.manifest.entries.map(i=>[i.ref,i]));for(let i of t){let n=r.get(i.ref);if(!n||JSON.stringify(n)!==JSON.stringify(i))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${i.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 Wu(e){return e.ref.split("/").length}async function Aw(e){let r=[...await Ro({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>Wu(a)-Wu(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),i=0;for(let n of r){let a=j.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await fo({root:e.projectRoot,file:a,maxBytes:Ao,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await ho({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),i+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,i)}await Ro({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await ho({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function dn(e,t,r=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:r,pending_root_move:t}}}function _w(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 zu(e){let t=dn(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Ve(e.projectRoot,t),t}async function Rr(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 r=dn(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 Ve(e.projectRoot,r),r}async function Ju(e){let t=e.config,r=t.native.pending_root_move;if(!r||r.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=r.cleanup;if(i&&i.kind!==e.kind)throw new Error(`Native root move has unfinished ${i.kind} cleanup; cannot start ${e.kind}`);let n=await X(e.target),a=await X(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!i){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 xw({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Ar(e.target,{rejectSymlinks:!0})});i={kind:e.kind,state:"prepared",manifestHash:s},t=await Rr({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})}let o=await Rw({paths:e.stablePaths,id:e.id,cleanup:i});if(n=await X(e.target),a=await X(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(i.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await cu({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(i.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Rr({projectRoot:e.projectRoot,config:t,id:e.id})}return await Ro({quarantine:e.quarantine,manifest:o,exact:i.state!=="deleting"}),i.state==="prepared"&&(i={...i,state:"quarantined"},t=await Rr({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),i.state==="quarantined"&&(i={...i,state:"deleting"},t=await Rr({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),await Aw({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Rr({projectRoot:e.projectRoot,config:t,id:e.id})}async function Tw(e){let t=e.config,r=t.native.pending_root_move.stage;if(r==="copying"){if(!await X(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=kw(e.staging);t=await Ju({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 Ar(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([j.resolve(e.lockFile)])}),await yw(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await un(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await zu({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),r="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(r==="ready"){if(await X(e.destinationPaths.nativeRoot)){if(await X(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await un(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await X(e.staging))throw new Error("Native move staging tree is missing");await un(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await We.rename(e.staging,e.destinationPaths.nativeRoot)}t=await zu({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),r="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(r!=="switched")throw new Error(`Unsupported Native root-move stage: ${r}`);if(!await X(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let i=bw(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await X(e.sourcePaths.nativeRoot)&&await un(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Ju({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:i,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await gw(e.destinationPaths);let n=await Sr(e.destinationPaths,e.pending.id);await go(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 Ve(e.projectRoot,o),o}async function Ku(e){let t=await Z(e.projectRoot)??Kl("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let r=pr(e.toArtifactRoot);if(r===t.native.artifact_root)throw new Error(`Native artifact root is already ${r}`);let i=await pe(e.projectRoot,t.native.artifact_root),n=await pe(e.projectRoot,r);if(V(i.nativeRoot,n.nativeRoot)||V(n.nativeRoot,i.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await X(i.nativeRoot))throw new Error(`Native source root does not exist: ${i.nativeRoot}`);if(await mw(i),await X(n.nativeRoot))throw new Error(`Native destination is occupied: ${n.nativeRoot}`);let a=await vr(i,"root-move",`move root to ${r}`),o=pw(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:r,stage:"copying"},c=_w({id:o,paths:i,now:e.now??new Date}),l=Nw(n,o);try{if(await vw(i,a.file),await ww(i),await X(l))throw new Error(`Native move staging path is occupied: ${l}`);return await Ve(e.projectRoot,dn(t,s)),await yu(i,c),await e.hooks?.afterRootMoveStage?.("copying",c),await Tw({projectRoot:e.projectRoot,config:dn(t,s),pending:s,sourcePaths:i,destinationPaths:n,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:i.nativeRoot,toNativeRoot:n.nativeRoot,transactionId:o}}finally{await gr(a)}}import jr from"path";import{realpathSync as My}from"fs";var Pe={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Yu(e){return e?e.command?`${Pe.next} ${e.command}`:e.ask_user?`${Pe.next} ${e.ask_user}`:null:null}function Xu(e,t){let r=[e.summary],i=Yu(e.next);return i&&r.push(i),e.user_message&&r.push("",Pe.relay,e.user_message),t!==void 0&&r.push("",Pe.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
183
|
+
${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return ln(p),p}async function bo(e){let t=await qu(e),r=Vu(e.paths,e.name),i=ce(e.paths,r);return await O(i,r),await Y(r,t,{containedRoot:i}),t}async function Pt(e,t){let r=await dw(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(ln(r),r)}async function sn(e){ln(e.identity);let t=await qu({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),Po==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function ko(e){if(ln(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 sn(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ge(e.paths.projectRoot);return e.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}var Ao=64*1024*1024,vP=256*1024,Gu=16*1024*1024;async function Q(e){try{return await We.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function mw(e){let t;try{t=await We.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;throw r}for(let r of t){if(!r.isDirectory()||r.isSymbolicLink())continue;let i;try{i=await Sr(e,r.name)}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction ${r.name} has no journal; run doctor before moving`,{cause:n}):n}if(i.status!=="committed"&&i.status!=="rolled-back")throw new Error(`Native transaction ${i.id} is unfinished; recover it before moving`)}}async function vw(e,t){for(let r of await We.readdir(e.locksDir,{withFileTypes:!0})){let i=j.join(e.locksDir,r.name);if(j.resolve(i)!==j.resolve(t)&&(r.isFile()||r.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${i}`)}}async function gw(e){let t;try{t=await We.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;throw r}for(let r of t.sort((i,n)=>i.name.localeCompare(n.name))){if(!r.isDirectory()||r.isSymbolicLink())continue;let i=await Pt(e,r.name);if(i){await bo({paths:e,name:r.name,revision:i.capturedRevision,...i.schema==="comet.native.workspace.v3"?{binding:{isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch},...i.finish?{finish:i.finish}:{}}:{}});continue}}}async function ww(e){let t;try{t=await We.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;throw r}for(let r of t.sort((i,n)=>i.name.localeCompare(n.name)))if(!(!r.isDirectory()||r.isSymbolicLink()))try{let i=await Pt(e,r.name);if(i?.schema==="comet.native.workspace.v3"){let n=await ko({paths:e,identity:i});if(n.state!=="aligned")throw new Error(n.message??"workspace binding is not aligned")}else if(i){let n=await sn({paths:e,identity:i});if(n.state!=="aligned")throw new Error(`legacy workspace ownership is ${n.state}`)}}catch(i){throw new Error(`Native workspace identity for ${r.name} must be aligned and repaired before moving the root`,{cause:i})}}async function Ar(e,t){let r=[];async function i(n){let a=await tt({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=j.join(n,s.name);if(t.excludedFiles?.has(j.resolve(c))){await a.verify();continue}let l=await We.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())r.push({ref:j.relative(e,c).split(j.sep).join("/"),type:"directory"}),await i(c);else if(s.isFile()&&l.isFile()){let u=await G({root:e,file:c,maxBytes:Ao,label:`Native root file ${j.relative(e,c)}`});r.push({ref:j.relative(e,c).split(j.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 i(e),r.sort((n,a)=>n.ref.localeCompare(a.ref))}async function yw(e,t,r,i){await yr({root:i,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await tt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=j.join(a,l.name);if(j.resolve(u)===j.resolve(r)){await s.verify();continue}let d=await We.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=j.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await yr({root:i,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:i,target:f,maxBytes:Ao,label:`Native root move file ${j.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 un(e,t,r,i){let n=await Ar(e,{rejectSymlinks:!0,excludedFiles:r?new Set([j.resolve(r)]):void 0}),a=await Ar(t,{rejectSymlinks:!0,excludedFiles:i?new Set([j.resolve(i)]):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 Nw(e,t){return j.join(e.artifactRoot,`.comet-native-move-${t}`)}function bw(e,t){return j.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function kw(e){return`${e}.removing`}function Uu(e,t,r){return j.join(Qi(e,t).directory,`root-move-cleanup-${r}.json`)}function Sw(e){return JSON.stringify(e,null,2)+`
|
|
184
|
+
`}function Ew(e){return hw("sha256").update(e).digest("hex")}function Cw(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 r=e,i=Object.keys(r).sort(),n=r.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof r.ref!="string"||r.ref.length===0||r.ref.includes("\\")||j.posix.normalize(r.ref)!==r.ref||r.ref.startsWith("/")||r.ref.split("/").includes("..")||Buffer.byteLength(r.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(r.type==="directory")return{ref:r.ref,type:"directory"};if(r.type!=="file"||typeof r.size!="number"||!Number.isSafeInteger(r.size)||r.size<0||typeof r.hash!="string"||!/^[a-f0-9]{64}$/u.test(r.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:r.ref,type:"file",size:r.size,hash:r.hash}}function Pw(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let i=e;if(JSON.stringify(Object.keys(i).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||i.schema!=="comet.native.root-move-cleanup.v1"||i.transactionId!==t||i.kind!==r||!Array.isArray(i.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=i.entries.map(Cw);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=j.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:r,entries:n}}async function xw(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},r=Sw(t);if(Buffer.byteLength(r,"utf8")>Gu)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await J(Uu(e.paths,e.id,e.kind),r,{containedRoot:e.paths.runtimeDir}),Ew(r)}async function Rw(e){let t=await G({root:e.paths.runtimeDir,file:Uu(e.paths,e.id,e.cleanup.kind),maxBytes:Gu,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 Pw(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Ro(e){let t=await Ar(e.quarantine,{rejectSymlinks:!0}),r=new Map(e.manifest.entries.map(i=>[i.ref,i]));for(let i of t){let n=r.get(i.ref);if(!n||JSON.stringify(n)!==JSON.stringify(i))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${i.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 Wu(e){return e.ref.split("/").length}async function Aw(e){let r=[...await Ro({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>Wu(a)-Wu(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),i=0;for(let n of r){let a=j.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await fo({root:e.projectRoot,file:a,maxBytes:Ao,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await ho({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),i+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,i)}await Ro({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await ho({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function dn(e,t,r=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:r,pending_root_move:t}}}function _w(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 zu(e){let t=dn(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Ve(e.projectRoot,t),t}async function Rr(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 r=dn(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 Ve(e.projectRoot,r),r}async function Ju(e){let t=e.config,r=t.native.pending_root_move;if(!r||r.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=r.cleanup;if(i&&i.kind!==e.kind)throw new Error(`Native root move has unfinished ${i.kind} cleanup; cannot start ${e.kind}`);let n=await Q(e.target),a=await Q(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!i){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 xw({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Ar(e.target,{rejectSymlinks:!0})});i={kind:e.kind,state:"prepared",manifestHash:s},t=await Rr({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})}let o=await Rw({paths:e.stablePaths,id:e.id,cleanup:i});if(n=await Q(e.target),a=await Q(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(i.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await cu({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(i.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Rr({projectRoot:e.projectRoot,config:t,id:e.id})}return await Ro({quarantine:e.quarantine,manifest:o,exact:i.state!=="deleting"}),i.state==="prepared"&&(i={...i,state:"quarantined"},t=await Rr({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),i.state==="quarantined"&&(i={...i,state:"deleting"},t=await Rr({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),await Aw({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Rr({projectRoot:e.projectRoot,config:t,id:e.id})}async function Tw(e){let t=e.config,r=t.native.pending_root_move.stage;if(r==="copying"){if(!await Q(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=kw(e.staging);t=await Ju({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 Ar(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([j.resolve(e.lockFile)])}),await yw(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await un(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await zu({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),r="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(r==="ready"){if(await Q(e.destinationPaths.nativeRoot)){if(await Q(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await un(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Q(e.staging))throw new Error("Native move staging tree is missing");await un(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await We.rename(e.staging,e.destinationPaths.nativeRoot)}t=await zu({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),r="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(r!=="switched")throw new Error(`Unsupported Native root-move stage: ${r}`);if(!await Q(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let i=bw(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Q(e.sourcePaths.nativeRoot)&&await un(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Ju({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:i,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await gw(e.destinationPaths);let n=await Sr(e.destinationPaths,e.pending.id);await go(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 Ve(e.projectRoot,o),o}async function Ku(e){let t=await ee(e.projectRoot)??Kl("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let r=pr(e.toArtifactRoot);if(r===t.native.artifact_root)throw new Error(`Native artifact root is already ${r}`);let i=await pe(e.projectRoot,t.native.artifact_root),n=await pe(e.projectRoot,r);if(V(i.nativeRoot,n.nativeRoot)||V(n.nativeRoot,i.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await Q(i.nativeRoot))throw new Error(`Native source root does not exist: ${i.nativeRoot}`);if(await mw(i),await Q(n.nativeRoot))throw new Error(`Native destination is occupied: ${n.nativeRoot}`);let a=await vr(i,"root-move",`move root to ${r}`),o=pw(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:r,stage:"copying"},c=_w({id:o,paths:i,now:e.now??new Date}),l=Nw(n,o);try{if(await vw(i,a.file),await ww(i),await Q(l))throw new Error(`Native move staging path is occupied: ${l}`);return await Ve(e.projectRoot,dn(t,s)),await yu(i,c),await e.hooks?.afterRootMoveStage?.("copying",c),await Tw({projectRoot:e.projectRoot,config:dn(t,s),pending:s,sourcePaths:i,destinationPaths:n,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:i.nativeRoot,toNativeRoot:n.nativeRoot,transactionId:o}}finally{await gr(a)}}import jr from"path";import{realpathSync as My}from"fs";var Pe={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Yu(e){return e?e.command?`${Pe.next} ${e.command}`:e.ask_user?`${Pe.next} ${e.ask_user}`:null:null}function Xu(e,t){let r=[e.summary],i=Yu(e.next);return i&&r.push(i),e.user_message&&r.push("",Pe.relay,e.user_message),t!==void 0&&r.push("",Pe.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
185
185
|
`)}
|
|
186
186
|
`}function Qu(e,t,r){let i=[e.summary],n=Yu(e.next);return n&&i.push(n),e.user_message&&i.push("",Pe.relay,e.user_message),i.push("",`${Pe.detail} ${t}`),r!==void 0&&i.push("",Pe.details,JSON.stringify(r,null,2)),i.join(`
|
|
187
|
-
`)}var jw=["outcome","scope","nonGoals","acceptanceExamples"],$P=[...jw,"constraints","decisions","openQuestions","verificationExpectations"];var $w=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Zu=1024*1024;var td="scoped-text-safety",Ow=1,Hw=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Dw="comet.native.checker-policy.v1";var XP=ie(Dw,{policy:td,version:Ow,limits:Hw,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Lw=["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"],QP=new Set(Lw);var Fw=Zu,mx=3*Fw;var rd={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:[]},qw=re("comet-native-runtime:v3:scope-reopen"),Vx=[{skillVersion:"3",skillHash:re("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:re("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:re("comet-native-runtime:v1")}];var nd=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],kR=new Set(nd),Yw=new Set([...nd,"minimum_runtime_version","revision"]),SR=new Set([...Yw,"operation"]),ER=512*1024,Xw=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),CR=new Set([...Xw,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var _R={maxAcceptanceCriteria:Ru.maxCriteria};var OR={maxSpecs:64,maxFileBytes:rn,maxTotalBytes:4*1024*1024};import{execFile as cy}from"node:child_process";import{promisify as ly}from"node:util";var DR=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var UR={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var mA=512*1024;var Ir=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var LA=64*1024;var BA=3600*1e3;var MA=ly(cy);var fn=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};var C_={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var $_=16*1024*1024,O_=256*1024,H_=16*1024;var V_=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var z_=16*1024;var ky=Rt(mt(),1);var G_=8*1024*1024;var hn=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};var ij=nn("en");var wj=16*1024;var s$=16*1024*1024,pn=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},mn=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function C(e,t,r){return e==="zh-CN"?r:t}var _o={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function cd(e,t){return typeof e=="string"&&_o[e]?C(t,_o[e].en,_o[e].zh):typeof e=="string"?e:""}function To(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 Py(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function ld(e,t){let r=[];e.failed>0&&r.push(C(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(C(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(C(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=C(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function ud(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Io(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function xy(e,t,r){return e==="done"?C(r,"complete","已完成"):e==="await-user"?C(r,"waiting for a user decision","等待用户决定"):e==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):t?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function Ry(e,t,r){let i=Io(e),n=[];r&&n.push(r);let a=C(i,`Change ${e.change}`,`需求 ${e.change}`),o=cd(e.phase,i),s=xy(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(ld(t,i));let c=e.userCommunication,l=dd(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function dd(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:C(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:C(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:C(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function Ay(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function _y(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=cd(e.phase,t),n=e.status==="await-user"?C(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?C(t,"paused","已暂停"):e.status==="done"?C(t,"complete","已完成"):C(t,"in progress","进行中"),a=To(e.acceptance)?`${C(t,", ",",")}${ld(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function Ty(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function Iy(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 jy(e){if(e.healthy){let i=e.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=$y(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:C("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:C("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function $y(e){return ud(e)?dd(e,Io(e)):void 0}function fd(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(Iy(t))return jy(t);if(Ay(t)){let i=Ty(t.items);return{summary:[t.total===t.items.length?C(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):C(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>_y(a,i))].join(`
|
|
188
|
-
`)}}let r=t.continuation;if(ud(r))return Ry(r,Oy(t),Hy(t,Io(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:C(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function Oy(e){if(To(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(To(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return Py(r.acceptance)}return null}function Hy(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return C(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?C(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function hd(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:C("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:C("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:C("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:C("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:C("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:C("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:C("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:C("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:C("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var pd=["--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."],$o=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:pd,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> [--
|
|
189
|
-
comet native next <change-name> --
|
|
190
|
-
comet native
|
|
187
|
+
`)}var jw=["outcome","scope","nonGoals","acceptanceExamples"],OP=[...jw,"constraints","decisions","openQuestions","verificationExpectations"];var $w=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Zu=1024*1024;var td="scoped-text-safety",Ow=1,Hw=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Dw="comet.native.checker-policy.v1";var QP=X(Dw,{policy:td,version:Ow,limits:Hw,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Lw=["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"],ZP=new Set(Lw);var Fw=Zu,vx=3*Fw;var rd={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:[]},qw=ie("comet-native-runtime:v3:scope-reopen"),qx=[{skillVersion:"3",skillHash:ie("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ie("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ie("comet-native-runtime:v1")}];var nd=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],SR=new Set(nd),Yw=new Set([...nd,"minimum_runtime_version","revision"]),ER=new Set([...Yw,"operation"]),CR=512*1024,Xw=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),PR=new Set([...Xw,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var TR={maxAcceptanceCriteria:Ru.maxCriteria};var HR={maxSpecs:64,maxFileBytes:rn,maxTotalBytes:4*1024*1024};import{execFile as cy}from"node:child_process";import{promisify as ly}from"node:util";var LR=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var KR={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var vA=512*1024;var Ir=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var BA=64*1024;var MA=3600*1e3;var FA=ly(cy);var fn=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};var P_={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var O_=16*1024*1024,H_=256*1024,D_=16*1024;var q_=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var J_=16*1024;var ky=Rt(mt(),1);var U_=8*1024*1024;var hn=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};var cj=nn("en");var Sj=16*1024;var f$=16*1024*1024,pn=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},mn=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function C(e,t,r){return e==="zh-CN"?r:t}var _o={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function cd(e,t){return typeof e=="string"&&_o[e]?C(t,_o[e].en,_o[e].zh):typeof e=="string"?e:""}function To(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 Py(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function ld(e,t){let r=[];e.failed>0&&r.push(C(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(C(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(C(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=C(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function ud(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Io(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function xy(e,t,r){return e==="done"?C(r,"complete","已完成"):e==="await-user"?C(r,"waiting for a user decision","等待用户决定"):e==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):t?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function Ry(e,t,r){let i=Io(e),n=[];r&&n.push(r);let a=C(i,`Change ${e.change}`,`需求 ${e.change}`),o=cd(e.phase,i),s=xy(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(ld(t,i));let c=e.userCommunication,l=dd(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function dd(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:C(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:C(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:C(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function Ay(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function _y(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=cd(e.phase,t),n=e.status==="await-user"?C(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?C(t,"paused","已暂停"):e.status==="done"?C(t,"complete","已完成"):C(t,"in progress","进行中"),a=To(e.acceptance)?`${C(t,", ",",")}${ld(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function Ty(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function Iy(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 jy(e){if(e.healthy){let i=e.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=$y(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:C("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:C("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function $y(e){return ud(e)?dd(e,Io(e)):void 0}function fd(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(Iy(t))return jy(t);if(Ay(t)){let i=Ty(t.items);return{summary:[t.total===t.items.length?C(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):C(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>_y(a,i))].join(`
|
|
188
|
+
`)}}let r=t.continuation;if(ud(r))return Ry(r,Oy(t),Hy(t,Io(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:C(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function Oy(e){if(To(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(To(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return Py(r.acceptance)}return null}function Hy(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return C(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?C(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function hd(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:C("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:C("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:C("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:C("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:C("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:C("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:C("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:C("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:C("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var pd=["--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."],$o=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:pd,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>]
|
|
189
|
+
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>]
|
|
190
|
+
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]
|
|
191
|
+
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 jo(e,t){return`${e}:
|
|
191
192
|
${t.map(r=>` ${r}`).join(`
|
|
192
193
|
`)}`}function Dy(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return $o[r]||t.length>1&&$o[t[0]]?.subcommands?r:t[0]}function Ly(e=[]){let t=Dy(e),r=$o[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",jo("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...pd];return n&&n.length>0&&i.push("",jo("Options",n)),i.push("",`Output:
|
|
193
194
|
${r.output}`),r.examples&&i.push("",jo("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
194
195
|
`)}
|
|
195
|
-
`}}var By=Ly().usage;var
|
|
196
|
+
`}}var By=Ly().usage;var I$=10*1024*1024,ye=class extends Error{};function Ho(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new ye(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function vd(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new ye(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new ye(`${t} requires a value`);return e.splice(i,2),n}function Do(e){if(e.length>0)throw new ye(`Unexpected argument: ${e[0]}`)}function Lo(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new ye(`${t} is required`);return r}function Oo(e,t){let r=jr.normalize(md(e)),i=jr.normalize(md(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function md(e){let t=jr.resolve(e);try{return My.native(t)}catch{return t}}function Fy(e){let t=jr.resolve(e),r=ge(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=ge(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Oo(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Oo(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Oo(process.cwd(),r.currentWorktreeRoot)?jr.resolve(process.cwd()):r.currentWorktreeRoot}async function gd(e){return e?Fy(e):co(process.cwd())}function wd(e){return JSON.stringify(e,null,2)+`
|
|
196
197
|
`}function Bo(e,t,r){return{command:e,exitCode:0,data:t,text:r??wd(t)}}function Vy(e,t){if(t instanceof ye)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof pn)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 mn)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof an)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 Pr)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 hn)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof on)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 fn)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Ir)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function yd(e,t){let r=Vy(e,t),i=r.error;if(!i)return r;let n=hd({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function Nd(e,t,r=!1){let i=e.envelope??fd(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
197
198
|
`}:e.error?{exitCode:e.exitCode,stderr:i?Qu(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Xu(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==wd(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
198
199
|
${Pe.details}
|
|
199
200
|
${JSON.stringify(e.data,null,2)}
|
|
200
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}async function bd(e,t){let r=Lo(e,"root subcommand");if(r==="show"){Do(e);let i=await
|
|
201
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}async function bd(e,t){let r=Lo(e,"root subcommand");if(r==="show"){Do(e);let i=await ee(t);if(!i)throw new Error(".comet/config.yaml was not found");let n=await pe(t,i.native.artifact_root);return Bo("root show",{projectRoot:t,artifactRoot:i.native.artifact_root,language:i.native.language,nativeRoot:n.nativeRoot,pendingRootMove:i.native.pending_root_move??null})}if(r==="move"){let i=Lo(e,"artifact root");Do(e);let n=await Ku({projectRoot:t,toArtifactRoot:i});return Bo("root move",n,`Moved Comet Native to ${n.toNativeRoot}
|
|
201
202
|
`)}throw new ye(`Unknown root command: ${r}`)}async function kd(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Ho(n,"--json"),Ho(n,"--verbose"),c=vd(n,"--project-root");let d=[...n,...a],f=await gd(c);l=await t(d,f)}catch(d){l=yd(e,d)}let u=Nd(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
202
203
|
`)?"":`
|
|
203
204
|
`)),u.exitCode}process.exitCode=await kd("root",bd);
|