@rpamis/comet 0.4.0-rc.2 → 0.4.0-rc.4
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 +2 -1
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +55 -55
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +56 -56
- package/assets/skills/comet/scripts/comet-guard.mjs +80 -80
- package/assets/skills/comet/scripts/comet-handoff.mjs +69 -69
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +47 -47
- package/assets/skills/comet/scripts/comet-hook-router.mjs +140 -137
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +57 -57
- package/assets/skills/comet/scripts/comet-runtime.mjs +133 -133
- package/assets/skills/comet/scripts/comet-state.mjs +73 -73
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +25 -25
- package/assets/skills/comet-native/SKILL.md +8 -9
- 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 +5 -2
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +120 -119
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +136 -135
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +77 -76
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +61 -60
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +128 -127
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +133 -132
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +70 -69
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +170 -169
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +112 -111
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +102 -101
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +110 -109
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +108 -107
- package/assets/skills-zh/comet-native/SKILL.md +8 -9
- 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 +5 -2
- package/dist/app/commands/bundle.d.ts.map +1 -1
- package/dist/app/commands/bundle.js.map +1 -1
- package/dist/app/commands/dashboard.d.ts +1 -1
- package/dist/app/commands/dashboard.js +1 -1
- package/dist/app/commands/doctor.d.ts.map +1 -1
- package/dist/app/commands/doctor.js +1 -1
- package/dist/app/commands/doctor.js.map +1 -1
- package/dist/app/commands/init.js +2 -2
- package/dist/app/commands/init.js.map +1 -1
- package/dist/app/commands/platform-select-prompt.d.ts.map +1 -1
- package/dist/app/commands/platform-select-prompt.js +1 -0
- package/dist/app/commands/platform-select-prompt.js.map +1 -1
- package/dist/app/commands/update.d.ts.map +1 -1
- package/dist/app/commands/update.js +12 -5
- package/dist/app/commands/update.js.map +1 -1
- package/dist/domains/agent-learning/policy-compiler.d.ts.map +1 -1
- package/dist/domains/agent-learning/policy-compiler.js.map +1 -1
- package/dist/domains/agent-learning/types.d.ts.map +1 -1
- package/dist/domains/agent-learning/types.js.map +1 -1
- package/dist/domains/bundle/authoring.d.ts.map +1 -1
- package/dist/domains/bundle/authoring.js.map +1 -1
- package/dist/domains/bundle/next-action.d.ts.map +1 -1
- package/dist/domains/bundle/next-action.js.map +1 -1
- package/dist/domains/bundle/readiness-user-summary.d.ts.map +1 -1
- package/dist/domains/bundle/readiness-user-summary.js.map +1 -1
- package/dist/domains/bundle/types.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
- package/dist/domains/comet-entry/current-selection.d.ts.map +1 -1
- package/dist/domains/comet-entry/current-selection.js.map +1 -1
- package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
- package/dist/domains/comet-entry/init-workflow.js.map +1 -1
- package/dist/domains/comet-entry/types.d.ts.map +1 -1
- package/dist/domains/comet-memory/personal-memory.d.ts.map +1 -1
- package/dist/domains/comet-memory/personal-memory.js +41 -0
- package/dist/domains/comet-memory/personal-memory.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-memory/types.js.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 +114 -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-atomic-file.d.ts +1 -0
- package/dist/domains/comet-native/native-atomic-file.d.ts.map +1 -1
- package/dist/domains/comet-native/native-atomic-file.js +19 -0
- package/dist/domains/comet-native/native-atomic-file.js.map +1 -1
- package/dist/domains/comet-native/native-children.d.ts +2 -0
- package/dist/domains/comet-native/native-children.d.ts.map +1 -1
- package/dist/domains/comet-native/native-children.js +16 -4
- package/dist/domains/comet-native/native-children.js.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +7 -7
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
- package/dist/domains/comet-native/native-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-evidence-storage.d.ts.map +1 -1
- package/dist/domains/comet-native/native-evidence-storage.js.map +1 -1
- package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
- package/dist/domains/comet-native/native-lock.js +10 -1
- package/dist/domains/comet-native/native-lock.js.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.d.ts +4 -0
- package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.js +50 -5
- 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 +64 -7
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
- package/dist/domains/comet-native/native-output-language.js.map +1 -1
- package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-archive.js +17 -1
- package/dist/domains/comet-native/native-portable-archive.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts +11 -4
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +201 -44
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-portable-migration.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-migration.js.map +1 -1
- package/dist/domains/comet-native/native-portable-recovery.d.ts +2 -1
- package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-recovery.js +28 -3
- package/dist/domains/comet-native/native-portable-recovery.js.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.d.ts +28 -1
- package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.js +276 -14
- 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-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 +26 -31
- package/dist/domains/comet-native/native-runner-input.js.map +1 -1
- package/dist/domains/comet-native/native-schema-migration.d.ts.map +1 -1
- package/dist/domains/comet-native/native-schema-migration.js.map +1 -1
- package/dist/domains/comet-native/native-supervisor-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 +11 -1
- package/dist/domains/comet-native/native-supervisor.d.ts.map +1 -1
- package/dist/domains/comet-native/native-supervisor.js +68 -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-verification-receipt.d.ts.map +1 -1
- package/dist/domains/comet-native/native-verification-receipt.js.map +1 -1
- package/dist/domains/comet-native/native-workspace-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-native/native-workspace.d.ts.map +1 -1
- package/dist/domains/comet-native/native-workspace.js.map +1 -1
- package/dist/domains/comet-plugin/integration.d.ts +2 -0
- package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
- package/dist/domains/comet-plugin/integration.js +10 -6
- package/dist/domains/comet-plugin/integration.js.map +1 -1
- package/dist/domains/dashboard/collector.js +1 -1
- package/dist/domains/dashboard/default-plugin-host.d.ts +3 -0
- package/dist/domains/dashboard/default-plugin-host.d.ts.map +1 -1
- package/dist/domains/dashboard/default-plugin-host.js +38 -4
- package/dist/domains/dashboard/default-plugin-host.js.map +1 -1
- package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
- package/dist/domains/dashboard/native-adapter.js.map +1 -1
- package/dist/domains/dashboard/web/assets/abnfDiagram-VCTEODGH-Bql0JkFh.js +1 -0
- package/dist/domains/dashboard/web/assets/arc-CCUY9L8x.js +1 -0
- package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-F2w5dggy.js +1 -0
- package/dist/domains/dashboard/web/assets/architectureDiagram-5GKGNRK7-iYP_D3CC.js +36 -0
- package/dist/domains/dashboard/web/assets/array-BifhSqXX.js +1 -0
- package/dist/domains/dashboard/web/assets/blockDiagram-I7D4REHJ-DyW07-ad.js +129 -0
- package/dist/domains/dashboard/web/assets/browser-CgwPGwaV.js +107 -0
- package/dist/domains/dashboard/web/assets/c4Diagram-7LVT6UL2-DDD_Y9Gj.js +38 -0
- package/dist/domains/dashboard/web/assets/channel-DLABCQMO.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-4HAMMTFA-cZryt4d4.js +62 -0
- package/dist/domains/dashboard/web/assets/{chunk-5VM5RSS4-CopXcnFA.js → chunk-5VM5RSS4-ZNzvKenW.js} +2 -2
- package/dist/domains/dashboard/web/assets/chunk-75Z2AOVW-Ciqzt_fM.js +2 -0
- package/dist/domains/dashboard/web/assets/chunk-DU6HZSFF-0EtIdyLT.js +125 -0
- package/dist/domains/dashboard/web/assets/chunk-F27PBJKO-B09yMHfO.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-FOHPRMQF-DHwB1DNv.js +161 -0
- package/dist/domains/dashboard/web/assets/chunk-GMAD6QVW-D_hJqXpD.js +72 -0
- package/dist/domains/dashboard/web/assets/chunk-GVQU2GXP-DIvLb3as.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-IMKFNOWR-B_oII0H5.js +231 -0
- package/dist/domains/dashboard/web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-L3NEJ4N5-BALKwnUb.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-OSK3NFVY-zA0G74ff.js +10 -0
- package/dist/domains/dashboard/web/assets/chunk-P2QGCYS3-B9FFBdWw.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-POPQ4Y6H-Fwh05sRj.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-PWAF6VOD-cCaczJjE.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-SHT3W25Y-ffjS5Q53.js +168 -0
- package/dist/domains/dashboard/web/assets/chunk-SVP7TREG-IDmA7lw7.js +88 -0
- package/dist/domains/dashboard/web/assets/chunk-TICWLB2K-8Gmmm4In.js +206 -0
- package/dist/domains/dashboard/web/assets/chunk-XXDRQBXY-DS9V6N2-.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-DJ9Y8TBe.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-DJ9Y8TBe.js +1 -0
- package/dist/domains/dashboard/web/assets/cose-bilkent-JH36ORCC-DTBreOtW.js +1 -0
- package/dist/domains/dashboard/web/assets/cynefin-OW5HDTMX-DQuEyCa9.js +1 -0
- package/dist/domains/dashboard/web/assets/cynefinDiagram-5FMLGOSQ-Bb0YxnR5.js +62 -0
- package/dist/domains/dashboard/web/assets/cytoscape.esm-CGd-uY3x.js +321 -0
- package/dist/domains/dashboard/web/assets/dagre-GXQ25YYZ-DCdqnZ1z.js +4 -0
- package/dist/domains/dashboard/web/assets/dagre-PrKaheQc.js +1 -0
- package/dist/domains/dashboard/web/assets/defaultLocale-BFoDCU3G.js +1 -0
- package/dist/domains/dashboard/web/assets/demo-DrJ2uuUL.js +456 -0
- package/dist/domains/dashboard/web/assets/diagram-S7CK7UJ4-CBO5Oebq.js +30 -0
- package/dist/domains/dashboard/web/assets/diagram-UQ7AKVKN-Do5KGiae.js +41 -0
- package/dist/domains/dashboard/web/assets/diagram-VSXAHHWV-4Xskky28.js +3 -0
- package/dist/domains/dashboard/web/assets/diagram-VX7I27RA-DHaxCMg1.js +24 -0
- package/dist/domains/dashboard/web/assets/diagram-Z3DM3KII-_b0C8RCs.js +24 -0
- package/dist/domains/dashboard/web/assets/dist-D_v6faRz.js +1 -0
- package/dist/domains/dashboard/web/assets/ebnfDiagram-PWID7BFC-BlWWQsBx.js +1 -0
- package/dist/domains/dashboard/web/assets/erDiagram-RLTQ6QDP-CaZks0yu.js +99 -0
- package/dist/domains/dashboard/web/assets/es-DMM6Y5Bv.js +10 -0
- package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-LE_eXkBk.js +1 -0
- package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-Dhg9N1uf.js +1 -0
- package/dist/domains/dashboard/web/assets/ganttDiagram-EL5Y4UJY-BSjOQ_Cg.js +292 -0
- package/dist/domains/dashboard/web/assets/gitGraph-4MIJSDKK-DYwq3-1L.js +1 -0
- package/dist/domains/dashboard/web/assets/gitGraphDiagram-WWUBYQGX-oVngpACZ.js +106 -0
- package/dist/domains/dashboard/web/assets/graphlib-DS17s2tU.js +1 -0
- package/dist/domains/dashboard/web/assets/index-7epoYLF6.js +261 -0
- package/dist/domains/dashboard/web/assets/index-C5iz4lns.css +1 -0
- package/dist/domains/dashboard/web/assets/info-A6RAGUB7-CLoje88f.js +1 -0
- package/dist/domains/dashboard/web/assets/infoDiagram-27XIBGKW-sS6zp9EL.js +2 -0
- package/dist/domains/dashboard/web/assets/init-C-OQMol4.js +1 -0
- package/dist/domains/dashboard/web/assets/ishikawaDiagram-5VMMS53U-kETJqqgb.js +70 -0
- package/dist/domains/dashboard/web/assets/journeyDiagram-3NMN7TZE-ByJPB5Tw.js +139 -0
- package/dist/domains/dashboard/web/assets/kanban-definition-UXKFOSKX-JKqPn1FZ.js +89 -0
- package/dist/domains/dashboard/web/assets/katex-CXMH3UgJ.js +257 -0
- package/dist/domains/dashboard/web/assets/line-CnHo6lWD.js +1 -0
- package/dist/domains/dashboard/web/assets/linear-B2pLEjo4.js +1 -0
- package/dist/domains/dashboard/web/assets/marked.esm-BtJme7Pf.js +65 -0
- package/dist/domains/dashboard/web/assets/mermaid-parser.core-OtNk5rQN.js +7 -0
- package/dist/domains/dashboard/web/assets/mermaid.core-D1ElL3aM.js +44 -0
- package/dist/domains/dashboard/web/assets/mindmap-definition-YA3MSWOX-BxJqN_qn.js +96 -0
- package/dist/domains/dashboard/web/assets/ordinal-BDEzSJ7C.js +1 -0
- package/dist/domains/dashboard/web/assets/packet-AYTQ26CC-DM9DL0wE.js +1 -0
- package/dist/domains/dashboard/web/assets/path-fybaL0A-.js +1 -0
- package/dist/domains/dashboard/web/assets/pegDiagram-XKGWAZYB-BDe-x6aH.js +1 -0
- package/dist/domains/dashboard/web/assets/pie-WAS4IAKB-ClmkkApZ.js +1 -0
- package/dist/domains/dashboard/web/assets/pieDiagram-E7YTZNPT-DSFQ6yQn.js +39 -0
- package/dist/domains/dashboard/web/assets/purify.es-ChwZkWde.js +3 -0
- package/dist/domains/dashboard/web/assets/quadrantDiagram-AXDQQJYC-CV2lLCpu.js +7 -0
- package/dist/domains/dashboard/web/assets/radar-RG4KPBEZ-BduOvwgQ.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-74A4TZTK-BYnUo_HE.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CPiOAGi2.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-DOuNY-jw.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-DjNccNww.js +1 -0
- package/dist/domains/dashboard/web/assets/railroadDiagram-O6MQD6OU-Y0OnScVm.js +1 -0
- package/dist/domains/dashboard/web/assets/requirementDiagram-BXWQKSXE-Dqs0b-_F.js +84 -0
- package/dist/domains/dashboard/web/assets/rough.esm-Dy-Kn_BL.js +1 -0
- package/dist/domains/dashboard/web/assets/sankeyDiagram-P5KCCOFB-DafYyCgJ.js +40 -0
- package/dist/domains/dashboard/web/assets/sequenceDiagram-WJ2MYXX4-DEu4sb48.js +162 -0
- package/dist/domains/dashboard/web/assets/sizeCapture-INFHLROL-B0uUizjq.js +1 -0
- package/dist/domains/dashboard/web/assets/src-je_XM8Ul.js +1 -0
- package/dist/domains/dashboard/web/assets/stateDiagram-D77RDMKH-vHbZoYCK.js +1 -0
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-C4dywNHK.js +1 -0
- package/dist/domains/dashboard/web/assets/swimlanes-42K2YHIH-DxEqhoUX.js +1 -0
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-CHhHUVep.js +8 -0
- package/dist/domains/dashboard/web/assets/timeline-definition-24CTP7MA-B4XpTytf.js +120 -0
- package/dist/domains/dashboard/web/assets/treeView-Q6P3EWNA-CrismRW3.js +1 -0
- package/dist/domains/dashboard/web/assets/treemap-WGGIJYW6-BGFmknIY.js +1 -0
- package/dist/domains/dashboard/web/assets/vennDiagram-4TSXK5OY-DphMzj7N.js +34 -0
- package/dist/domains/dashboard/web/assets/wardley-WFR3VGLG-DmeLufag.js +1 -0
- package/dist/domains/dashboard/web/assets/wardleyDiagram-VM6X3IG4-BUDxONKk.js +78 -0
- package/dist/domains/dashboard/web/assets/xychartDiagram-S5SC5T6Z-BjqVHkW2.js +7 -0
- package/dist/domains/dashboard/web/index.html +16 -16
- package/dist/domains/factory/artifacts.d.ts.map +1 -1
- package/dist/domains/factory/artifacts.js.map +1 -1
- package/dist/domains/factory/types.d.ts.map +1 -1
- package/dist/domains/integrations/codegraph.d.ts.map +1 -1
- package/dist/domains/integrations/codegraph.js.map +1 -1
- package/dist/domains/project-knowledge/deterministic-extractors.d.ts.map +1 -1
- package/dist/domains/project-knowledge/deterministic-extractors.js +7 -6
- package/dist/domains/project-knowledge/deterministic-extractors.js.map +1 -1
- 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 +19 -10
- package/dist/domains/project-knowledge/index-store.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 +27 -8
- 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 +26 -1
- package/dist/domains/project-knowledge/local-provider.js.map +1 -1
- package/dist/domains/project-knowledge/local-store.d.ts +23 -1
- package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
- package/dist/domains/project-knowledge/local-store.js +179 -22
- 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 +55 -8
- package/dist/domains/project-knowledge/plugin.js.map +1 -1
- 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/skill/platform-inspect.d.ts +1 -1
- package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
- package/dist/domains/skill/platform-inspect.js +50 -10
- package/dist/domains/skill/platform-inspect.js.map +1 -1
- package/dist/domains/skill/platform-install.d.ts +10 -5
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +107 -17
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/domains/skill/uninstall.d.ts.map +1 -1
- package/dist/domains/skill/uninstall.js +38 -61
- package/dist/domains/skill/uninstall.js.map +1 -1
- package/dist/domains/workflow-contract/contained-atomic-write.d.ts +1 -0
- package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
- package/dist/domains/workflow-contract/contained-atomic-write.js +19 -0
- package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
- package/dist/domains/workflow-contract/global-config.d.ts +8 -0
- package/dist/domains/workflow-contract/global-config.d.ts.map +1 -1
- package/dist/domains/workflow-contract/global-config.js +25 -0
- package/dist/domains/workflow-contract/global-config.js.map +1 -1
- package/dist/domains/workflow-contract/index.d.ts +1 -1
- package/dist/domains/workflow-contract/index.d.ts.map +1 -1
- package/dist/domains/workflow-contract/index.js +1 -1
- package/dist/domains/workflow-contract/index.js.map +1 -1
- package/dist/domains/workflow-contract/project-config.d.ts +1 -1
- package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config.js +1 -0
- package/dist/domains/workflow-contract/project-config.js.map +1 -1
- package/dist/domains/workflow-contract/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/domains/workflow-contract/types.d.ts.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/platforms.d.ts +4 -0
- package/dist/platform/install/platforms.d.ts.map +1 -1
- package/dist/platform/install/platforms.js +15 -3
- package/dist/platform/install/platforms.js.map +1 -1
- package/dist/platform/paths/project-knowledge-storage.d.ts +1 -1
- package/dist/platform/paths/project-knowledge-storage.d.ts.map +1 -1
- package/dist/platform/paths/project-knowledge-storage.js +9 -4
- package/dist/platform/paths/project-knowledge-storage.js.map +1 -1
- package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +13 -13
- package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +13 -13
- package/package.json +24 -24
- package/dist/domains/dashboard/web/assets/abnfDiagram-N423BO3Z-BkUJc7LK.js +0 -1
- package/dist/domains/dashboard/web/assets/arc-DY4Y9tSO.js +0 -1
- package/dist/domains/dashboard/web/assets/architectureDiagram-T3A2C74G-7wC9YZS-.js +0 -36
- package/dist/domains/dashboard/web/assets/blockDiagram-VBNYF7ZC-Biqe-SaL.js +0 -132
- package/dist/domains/dashboard/web/assets/c4Diagram-5PPSVZJV-CccUFD1S.js +0 -10
- package/dist/domains/dashboard/web/assets/channel-DnRvSkOm.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-2GRJ4B5K-BUL4dDxo.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-2Q5K7J3B-BnKtDH9O.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-5RXB4S5H-C9pHQ1n3.js +0 -231
- package/dist/domains/dashboard/web/assets/chunk-6Q2QTUOP-CxrbngCi.js +0 -88
- package/dist/domains/dashboard/web/assets/chunk-GF5L2VYU-01mzgCUh.js +0 -206
- package/dist/domains/dashboard/web/assets/chunk-JWPE2WC7-wTiZVDvw.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-KBJHAD2P-Bxdv5bl-.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-RYQCIY6F-B5vF9l9A.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-XXDRQBXY-Dra3NnDp.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-D3E-rgaQ.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-D3E-rgaQ.js +0 -1
- package/dist/domains/dashboard/web/assets/cose-bilkent-JH36ORCC-DC96ge-n.js +0 -1
- package/dist/domains/dashboard/web/assets/cynefin-VYW2F7L2-Tt_NiopT.js +0 -166
- package/dist/domains/dashboard/web/assets/cynefinDiagram-MW4NZA55-BQ5__1hv.js +0 -62
- package/dist/domains/dashboard/web/assets/cytoscape.esm-D3_iZ_3b.js +0 -321
- package/dist/domains/dashboard/web/assets/dagre-VZM6K2ZE-Cr2zq3ro.js +0 -4
- package/dist/domains/dashboard/web/assets/defaultLocale-DX6XiGOO.js +0 -1
- package/dist/domains/dashboard/web/assets/demo-lxXhgJ9-.js +0 -456
- package/dist/domains/dashboard/web/assets/diagram-7IWD3JNH-BRpYDwPl.js +0 -30
- package/dist/domains/dashboard/web/assets/diagram-B4RE2ZJO-D7u-VBxW.js +0 -3
- package/dist/domains/dashboard/web/assets/diagram-LBJQPF4R-CHYuv2JD.js +0 -24
- package/dist/domains/dashboard/web/assets/diagram-Q27KOJAE-CV3ZE8Q3.js +0 -24
- package/dist/domains/dashboard/web/assets/diagram-UB23O5K3-co_OsTiQ.js +0 -41
- package/dist/domains/dashboard/web/assets/ebnfDiagram-BXEA7PRR-CETcWswS.js +0 -1
- package/dist/domains/dashboard/web/assets/erDiagram-JOGREHBK-edkItb7Z.js +0 -85
- package/dist/domains/dashboard/web/assets/flowDiagram-UKHOOZJN-D_oFJtSf.js +0 -156
- package/dist/domains/dashboard/web/assets/ganttDiagram-PKOTCBZU-CFjLVoA1.js +0 -292
- package/dist/domains/dashboard/web/assets/gitGraphDiagram-DS77QQ5N-BfD0tiKH.js +0 -106
- package/dist/domains/dashboard/web/assets/graph-DOmOIIwC.js +0 -1
- package/dist/domains/dashboard/web/assets/index-BzyqCfMb.css +0 -1
- package/dist/domains/dashboard/web/assets/index-CCKHH_A9.js +0 -10
- package/dist/domains/dashboard/web/assets/index-D8dxsTJY.js +0 -271
- package/dist/domains/dashboard/web/assets/index-DlSYK56b.js +0 -139
- package/dist/domains/dashboard/web/assets/infoDiagram-6WML65LV-Cx6xa9DS.js +0 -2
- package/dist/domains/dashboard/web/assets/init-Gi6I4Gst.js +0 -1
- package/dist/domains/dashboard/web/assets/ishikawaDiagram-WSZJBQD7-BjNLyyv_.js +0 -70
- package/dist/domains/dashboard/web/assets/journeyDiagram-NVQOT4AX-D2n9vrhx.js +0 -139
- package/dist/domains/dashboard/web/assets/kanban-definition-27J2QSJJ-kJL7v018.js +0 -89
- package/dist/domains/dashboard/web/assets/katex-HP8lGamR.js +0 -257
- package/dist/domains/dashboard/web/assets/layout-D-LzfAck.js +0 -1
- package/dist/domains/dashboard/web/assets/linear-CeHtd5-l.js +0 -1
- package/dist/domains/dashboard/web/assets/map-DxJ2ADlA.js +0 -1
- package/dist/domains/dashboard/web/assets/marked.esm-DECB3bxB.js +0 -64
- package/dist/domains/dashboard/web/assets/mermaid.core-B0EPSHs2.js +0 -306
- package/dist/domains/dashboard/web/assets/mindmap-definition-FAOFIHXS-bQQWINF4.js +0 -96
- package/dist/domains/dashboard/web/assets/ordinal-Cboi1Yqb.js +0 -1
- package/dist/domains/dashboard/web/assets/pegDiagram-VL7TDLO6-LxLY1W7W.js +0 -1
- package/dist/domains/dashboard/web/assets/pieDiagram-7S7Q4E2Y-BMDQqvuT.js +0 -39
- package/dist/domains/dashboard/web/assets/purify.es-Cz4mVeUR.js +0 -3
- package/dist/domains/dashboard/web/assets/quadrantDiagram-CIZ2JOQS-XWYjcuZN.js +0 -7
- package/dist/domains/dashboard/web/assets/railroadDiagram-AXF67PYL-p-OlQTa7.js +0 -1
- package/dist/domains/dashboard/web/assets/requirementDiagram-LRYGKXZP-BL4N8Vsl.js +0 -84
- package/dist/domains/dashboard/web/assets/sankeyDiagram-W5VNT64P-Btu-o6LN.js +0 -40
- package/dist/domains/dashboard/web/assets/sequenceDiagram-SI44F4Z6-9HpdQQ47.js +0 -162
- package/dist/domains/dashboard/web/assets/sizeCapture-X5ZJPWSS-5AnBiBHD.js +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-OKZ733FA-Dv8IDsai.js +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-DxOMyFOm.js +0 -1
- package/dist/domains/dashboard/web/assets/swimlanes-SLNWSIFB-BfJcN7dK.js +0 -2
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-BnHRSbDk.js +0 -8
- package/dist/domains/dashboard/web/assets/timeline-definition-Z64GVDOM-DEOuEHi5.js +0 -120
- package/dist/domains/dashboard/web/assets/vennDiagram-T6HMQDX7-BqsGpwgo.js +0 -34
- package/dist/domains/dashboard/web/assets/wardleyDiagram-T6FBY63Y-CXlOp9so.js +0 -78
- package/dist/domains/dashboard/web/assets/xychartDiagram-ELKLHX3M-DyqqtC9X.js +0 -7
|
@@ -1,145 +1,145 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`)}};
|
|
6
|
-
`)?
|
|
4
|
+
var ih=Object.create;var Ms=Object.defineProperty;var nh=Object.getOwnPropertyDescriptor;var ah=Object.getOwnPropertyNames;var oh=Object.getPrototypeOf,sh=Object.prototype.hasOwnProperty;var ni=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var ch=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ah(t))!sh.call(e,n)&&n!==r&&Ms(e,n,{get:()=>t[n],enumerable:!(i=nh(t,n))||i.enumerable});return e};var rr=(e,t,r)=>(r=e!=null?ih(oh(e)):{},ch(t||!e||!e.__esModule?Ms(r,"default",{value:e,enumerable:!0}):r,e));var x=w(M=>{"use strict";var ia=Symbol.for("yaml.alias"),Fs=Symbol.for("yaml.document"),ai=Symbol.for("yaml.map"),qs=Symbol.for("yaml.pair"),na=Symbol.for("yaml.scalar"),oi=Symbol.for("yaml.seq"),Ie=Symbol.for("yaml.node.type"),lh=e=>!!e&&typeof e=="object"&&e[Ie]===ia,uh=e=>!!e&&typeof e=="object"&&e[Ie]===Fs,dh=e=>!!e&&typeof e=="object"&&e[Ie]===ai,fh=e=>!!e&&typeof e=="object"&&e[Ie]===qs,Ws=e=>!!e&&typeof e=="object"&&e[Ie]===na,hh=e=>!!e&&typeof e=="object"&&e[Ie]===oi;function zs(e){if(e&&typeof e=="object")switch(e[Ie]){case ai:case oi:return!0}return!1}function ph(e){if(e&&typeof e=="object")switch(e[Ie]){case ia:case ai:case na:case oi:return!0}return!1}var mh=e=>(Ws(e)||zs(e))&&!!e.anchor;M.ALIAS=ia;M.DOC=Fs;M.MAP=ai;M.NODE_TYPE=Ie;M.PAIR=qs;M.SCALAR=na;M.SEQ=oi;M.hasAnchor=mh;M.isAlias=lh;M.isCollection=zs;M.isDocument=uh;M.isMap=dh;M.isNode=ph;M.isPair=fh;M.isScalar=Ws;M.isSeq=hh});var ir=w(aa=>{"use strict";var D=x(),G=Symbol("break visit"),Js=Symbol("skip children"),Se=Symbol("remove node");function si(e,t){let r=Gs(t);D.isDocument(e)?xt(null,e.contents,r,Object.freeze([e]))===Se&&(e.contents=null):xt(null,e,r,Object.freeze([]))}si.BREAK=G;si.SKIP=Js;si.REMOVE=Se;function xt(e,t,r,i){let n=Us(e,t,r,i);if(D.isNode(n)||D.isPair(n))return Ks(e,i,n),xt(e,n,r,i);if(typeof n!="symbol"){if(D.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=xt(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===G)return G;o===Se&&(t.items.splice(a,1),a-=1)}}}else if(D.isPair(t)){i=Object.freeze(i.concat(t));let a=xt("key",t.key,r,i);if(a===G)return G;a===Se&&(t.key=null);let o=xt("value",t.value,r,i);if(o===G)return G;o===Se&&(t.value=null)}}return n}async function ci(e,t){let r=Gs(t);D.isDocument(e)?await Pt(null,e.contents,r,Object.freeze([e]))===Se&&(e.contents=null):await Pt(null,e,r,Object.freeze([]))}ci.BREAK=G;ci.SKIP=Js;ci.REMOVE=Se;async function Pt(e,t,r,i){let n=await Us(e,t,r,i);if(D.isNode(n)||D.isPair(n))return Ks(e,i,n),Pt(e,n,r,i);if(typeof n!="symbol"){if(D.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Pt(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===G)return G;o===Se&&(t.items.splice(a,1),a-=1)}}}else if(D.isPair(t)){i=Object.freeze(i.concat(t));let a=await Pt("key",t.key,r,i);if(a===G)return G;a===Se&&(t.key=null);let o=await Pt("value",t.value,r,i);if(o===G)return G;o===Se&&(t.value=null)}}return n}function Gs(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Us(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(D.isMap(t))return r.Map?.(e,t,i);if(D.isSeq(t))return r.Seq?.(e,t,i);if(D.isPair(t))return r.Pair?.(e,t,i);if(D.isScalar(t))return r.Scalar?.(e,t,i);if(D.isAlias(t))return r.Alias?.(e,t,i)}function Ks(e,t,r){let i=t[t.length-1];if(D.isCollection(i))i.items[e]=r;else if(D.isPair(i))e==="key"?i.key=r:i.value=r;else if(D.isDocument(i))i.contents=r;else{let n=D.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}aa.visit=si;aa.visitAsync=ci});var oa=w(Xs=>{"use strict";var Ys=x(),vh=ir(),gh={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},wh=e=>e.replace(/[!,[\]{}]/g,t=>gh[t]),nr=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+wh(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Ys.isNode(t.contents)){let a={};vh.visit(t.contents,(o,s)=>{Ys.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
|
|
5
|
+
`)}};nr.defaultYaml={explicit:!1,version:"1.2"};nr.defaultTags={"!!":"tag:yaml.org,2002:"};Xs.Directives=nr});var li=w(ar=>{"use strict";var Qs=x(),yh=ir();function Nh(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Zs(e){let t=new Set;return yh.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function ec(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function bh(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Zs(e));let o=ec(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Qs.isScalar(o.node)||Qs.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}ar.anchorIsValid=Nh;ar.anchorNames=Zs;ar.createNodeAnchors=bh;ar.findNewAnchor=ec});var sa=w(tc=>{"use strict";function or(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=or(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=or(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=or(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=or(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}tc.applyReviver=or});var We=w(ic=>{"use strict";var kh=x();function rc(e,t,r){if(Array.isArray(e))return e.map((i,n)=>rc(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!kh.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}ic.toJS=rc});var ui=w(ac=>{"use strict";var Sh=sa(),nc=x(),Eh=We(),ca=class{constructor(t){Object.defineProperty(this,nc.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!nc.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=Eh.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Sh.applyReviver(a,{"":s},"",s):s}};ac.NodeBase=ca});var sr=w(oc=>{"use strict";var Ch=li(),xh=ir(),Rt=x(),Ph=ui(),Rh=We(),la=class extends Ph.NodeBase{constructor(t){super(Rt.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],xh.visit(t,{Node:(a,o)=>{(Rt.isAlias(o)||Rt.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Rh.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=di(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(Ch.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function di(e,t,r){if(Rt.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Rt.isCollection(t)){let i=0;for(let n of t.items){let a=di(e,n,r);a>i&&(i=a)}return i}else if(Rt.isPair(t)){let i=di(e,t.key,r),n=di(e,t.value,r);return Math.max(i,n)}return 1}oc.Alias=la});var $=w(ua=>{"use strict";var Ah=x(),_h=ui(),Ih=We(),Th=e=>!e||typeof e!="function"&&typeof e!="object",ze=class extends _h.NodeBase{constructor(t){super(Ah.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Ih.toJS(this.value,t,r)}toString(){return String(this.value)}};ze.BLOCK_FOLDED="BLOCK_FOLDED";ze.BLOCK_LITERAL="BLOCK_LITERAL";ze.PLAIN="PLAIN";ze.QUOTE_DOUBLE="QUOTE_DOUBLE";ze.QUOTE_SINGLE="QUOTE_SINGLE";ua.Scalar=ze;ua.isScalarValue=Th});var cr=w(cc=>{"use strict";var jh=sr(),pt=x(),sc=$(),$h="tag:yaml.org,2002:";function Oh(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function Hh(e,t,r){if(pt.isDocument(e)&&(e=e.contents),pt.isNode(e))return e;if(pt.isPair(e)){let d=r.schema[pt.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new jh.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=$h+t.slice(2));let l=Oh(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new sc.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[pt.MAP]:Symbol.iterator in Object(e)?o[pt.SEQ]:o[pt.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new sc.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}cc.createNode=Hh});var hi=w(fi=>{"use strict";var Dh=cr(),Ee=x(),Lh=ui();function da(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return Dh.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var lc=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,fa=class extends Lh.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>Ee.isNode(i)||Ee.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(lc(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(Ee.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,da(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Ee.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&Ee.isScalar(a)?a.value:a:Ee.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Ee.isPair(r))return!1;let i=r.value;return i==null||t&&Ee.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Ee.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Ee.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,da(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};fi.Collection=fa;fi.collectionFromPath=da;fi.isEmptyPath=lc});var lr=w(pi=>{"use strict";var Bh=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ha(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Vh=(e,t,r)=>e.endsWith(`
|
|
6
|
+
`)?ha(r,t):r.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)r===
|
|
10
|
-
`&&
|
|
11
|
-
`&&S!==" "&&(f=
|
|
12
|
-
${
|
|
13
|
-
${
|
|
14
|
-
`);i=
|
|
15
|
-
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function
|
|
8
|
+
`+ha(r,t):(e.endsWith(" ")?"":" ")+r;pi.indentComment=ha;pi.lineComment=Vh;pi.stringifyComment=Bh});var dc=w(ur=>{"use strict";var Mh="flow",pa="block",mi="quoted";function Fh(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let f,p,v=!1,h=-1,m=-1,y=-1;r===pa&&(h=uc(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(r===mi&&k==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}y=h}if(k===`
|
|
9
|
+
`)r===pa&&(h=uc(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(k===" "&&p&&p!==" "&&p!==`
|
|
10
|
+
`&&p!==" "){let S=e[h+1];S&&S!==" "&&S!==`
|
|
11
|
+
`&&S!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(r===mi){for(;p===" "||p===" ";)p=k,k=e[h+=1],v=!0;let S=h>y+1?h-2:m-1;if(u[S])return e;l.push(S),u[S]=!0,d=S+c,f=void 0}else v=!0}p=k}if(v&&s&&s(),l.length===0)return e;o&&o();let N=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let S=l[k],E=l[k+1]||e.length;S===0?N=`
|
|
12
|
+
${t}${e.slice(0,E)}`:(r===mi&&u[S]&&(N+=`${e[S]}\\`),N+=`
|
|
13
|
+
${t}${e.slice(S+1,E)}`)}return N}function uc(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
+
`);i=t,n=t+1,a=e[n]}return i}ur.FOLD_BLOCK=pa;ur.FOLD_FLOW=Mh;ur.FOLD_QUOTED=mi;ur.foldFlowLines=Fh});var fr=w(fc=>{"use strict";var he=$(),Je=dc(),gi=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),wi=e=>/^(%|---|\.\.\.)/m.test(e);function qh(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function dr(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(wi(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(
|
|
20
|
-
${r}`)+"'";return
|
|
18
|
+
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:Je.foldFlowLines(o,a,Je.FOLD_QUOTED,gi(t,!1))}function ma(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return dr(e,t);let r=t.indent||(wi(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${r}`)+"'";return t.implicitKey?i:Je.foldFlowLines(i,r,Je.FOLD_FLOW,gi(t,!1))}function At(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=dr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=ma:a&&!n?i=dr:i=r?ma:dr}return i(e,t)}var va;try{va=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{va=/\n+(?!\n|$)/g}function vi({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return At(r,i);let l=i.indent||(i.forceBlockIndent||wi(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===he.Scalar.BLOCK_FOLDED?!1:t===he.Scalar.BLOCK_LITERAL?!0:!qh(r,c,l.length);if(!r)return u?`|
|
|
24
24
|
`:`>
|
|
25
25
|
`;let d,f;for(f=r.length;f>0;--f){let E=r[f-1];if(E!==`
|
|
26
|
-
`&&E!==" "&&E!==" ")break}let
|
|
27
|
-
`);v===-1?d="-":r===
|
|
28
|
-
`&&(
|
|
29
|
-
`)y=m;else break}let N=r.substring(0,y<m?y+1:m);N&&(r=r.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let S=(
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,P=
|
|
26
|
+
`&&E!==" "&&E!==" ")break}let p=r.substring(f),v=p.indexOf(`
|
|
27
|
+
`);v===-1?d="-":r===p||v!==p.length-1?(d="+",a&&a()):d="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
|
|
28
|
+
`&&(p=p.slice(0,-1)),p=p.replace(va,`$&${l}`));let h=!1,m,y=-1;for(m=0;m<r.length;++m){let E=r[m];if(E===" ")h=!0;else if(E===`
|
|
29
|
+
`)y=m;else break}let N=r.substring(0,y<m?y+1:m);N&&(r=r.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let S=(h?l?"2":"1":"")+d;if(e&&(S+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let E=r.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,P=gi(i,!0);o!=="folded"&&t!==he.Scalar.BLOCK_FOLDED&&(P.onOverflow=()=>{g=!0});let b=Je.foldFlowLines(`${N}${E}${p}`,l,Je.FOLD_BLOCK,P);if(!g)return`>${S}
|
|
31
31
|
${l}${b}`}return r=r.replace(/\n+/g,`$&${l}`),`|${S}
|
|
32
|
-
${l}${N}${r}${
|
|
33
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let f=
|
|
37
|
-
${
|
|
38
|
-
${s}:`):(m=`${m}:`,f&&(m+=
|
|
32
|
+
${l}${N}${r}${p}`}function Wh(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
33
|
+
`)||u&&/[[\]{},]/.test(a))return At(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
+
`)?At(a,t):vi(e,t,r,i);if(!s&&!u&&n!==he.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return vi(e,t,r,i);if(wi(a)){if(c==="")return t.forceBlockIndent=!0,vi(e,t,r,i);if(s&&c===l)return At(a,t)}let d=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return At(a,t)}return s?d:Je.foldFlowLines(d,c,Je.FOLD_FLOW,gi(t,!1))}function zh(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==he.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=he.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case he.Scalar.BLOCK_FOLDED:case he.Scalar.BLOCK_LITERAL:return n||a?At(o.value,t):vi(o,t,r,i);case he.Scalar.QUOTE_DOUBLE:return dr(o.value,t);case he.Scalar.QUOTE_SINGLE:return ma(o.value,t);case he.Scalar.PLAIN:return Wh(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}fc.stringifyString=zh});var hr=w(ga=>{"use strict";var Jh=li(),Ge=x(),Gh=lr(),Uh=fr();function Kh(e,t){let r=Object.assign({blockQuote:!0,commentString:Gh.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function Yh(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(Ge.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function Xh(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Ge.isScalar(e)||Ge.isCollection(e))&&e.anchor;a&&Jh.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function Qh(e,t,r,i){if(Ge.isPair(e))return e.toString(t,r,i);if(Ge.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=Ge.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=Yh(t.doc.schema.tags,a));let o=Xh(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):Ge.isScalar(a)?Uh.stringifyString(a,t,r,i):a.toString(t,r,i);return o?Ge.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}ga.createStringifyContext=Kh;ga.stringify=Qh});var vc=w(mc=>{"use strict";var Te=x(),hc=$(),pc=hr(),pr=lr();function Zh({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,f=Te.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Te.isCollection(e)||!Te.isNode(e)&&typeof e=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let p=!d&&(!e||f&&t==null&&!r.inFlow||Te.isCollection(e)||(Te.isScalar(e)?e.type===hc.Scalar.BLOCK_FOLDED||e.type===hc.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=pc.stringify(e,r,()=>v=!0,()=>h=!0);if(!p&&!r.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=pr.lineComment(m,r.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=pr.lineComment(m,r.indent,l(f))),m=`? ${m}
|
|
38
|
+
${s}:`):(m=`${m}:`,f&&(m+=pr.lineComment(m,r.indent,l(f))));let y,N,k;Te.isNode(t)?(y=!!t.spaceBefore,N=t.commentBefore,k=t.comment):(y=!1,N=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!f&&Te.isScalar(t)&&(r.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!p&&Te.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let S=!1,E=pc.stringify(t,r,()=>S=!0,()=>h=!0),g=" ";if(f||y||N){if(g=y?`
|
|
39
39
|
`:"",N){let P=l(N);g+=`
|
|
40
|
-
${
|
|
40
|
+
${pr.indentComment(P,r.indent)}`}E===""&&!r.inFlow?g===`
|
|
41
41
|
`&&k&&(g=`
|
|
42
42
|
|
|
43
43
|
`):g+=`
|
|
44
|
-
${r.indent}`}else if(!
|
|
45
|
-
`),I=b!==-1,X=r.inFlow??
|
|
44
|
+
${r.indent}`}else if(!p&&Te.isCollection(t)){let P=E[0],b=E.indexOf(`
|
|
45
|
+
`),I=b!==-1,X=r.inFlow??t.flow??t.items.length===0;if(I||!X){let Ct=!1;if(I&&(P==="&"||P==="!")){let H=E.indexOf(" ");P==="&"&&H!==-1&&H<b&&E[H+1]==="!"&&(H=E.indexOf(" ",H+1)),(H===-1||b<H)&&(Ct=!0)}Ct||(g=`
|
|
46
46
|
${r.indent}`)}}else(E===""||E[0]===`
|
|
47
|
-
`)&&(g="");return m+=g+E,r.inFlow?S&&i&&i():k&&!S?m+=
|
|
48
|
-
${c}${
|
|
49
|
-
`}}return
|
|
50
|
-
`+
|
|
51
|
-
`)),v<
|
|
52
|
-
${a}${n}${
|
|
47
|
+
`)&&(g="");return m+=g+E,r.inFlow?S&&i&&i():k&&!S?m+=pr.lineComment(m,r.indent,l(k)):h&&n&&n(),m}mc.stringifyPair=Zh});var ya=w(wa=>{"use strict";var gc=ni("process");function ep(e,...t){e==="debug"&&console.log(...t)}function tp(e,t){(e==="debug"||e==="warn")&&(typeof gc.emitWarning=="function"?gc.emitWarning(t):console.warn(t))}wa.debug=ep;wa.warn=tp});var Si=w(ki=>{"use strict";var bi=x(),wc=$(),yi="<<",Ni={identify:e=>e===yi||typeof e=="symbol"&&e.description===yi,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new wc.Scalar(Symbol(yi)),{addToJSMap:yc}),stringify:()=>yi},rp=(e,t)=>(Ni.identify(t)||bi.isScalar(t)&&(!t.type||t.type===wc.Scalar.PLAIN)&&Ni.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Ni.tag&&r.default);function yc(e,t,r){let i=Nc(e,r);if(bi.isSeq(i))for(let n of i.items)Na(e,t,n);else if(Array.isArray(i))for(let n of i)Na(e,t,n);else Na(e,t,i)}function Na(e,t,r){let i=Nc(e,r);if(!bi.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Nc(e,t){return e&&bi.isAlias(t)?t.resolve(e.doc,e):t}ki.addMergeToJSMap=yc;ki.isMergeKey=rp;ki.merge=Ni});var ka=w(Sc=>{"use strict";var ip=ya(),bc=Si(),np=hr(),kc=x(),ba=We();function ap(e,t,{key:r,value:i}){if(kc.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(bc.isMergeKey(e,r))bc.addMergeToJSMap(e,t,i);else{let n=ba.toJS(r,"",e);if(t instanceof Map)t.set(n,ba.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=op(r,n,e),o=ba.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function op(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(kc.isNode(e)&&r?.doc){let i=np.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),ip.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Sc.addPairToJSMap=ap});var Ue=w(Sa=>{"use strict";var Ec=cr(),sp=vc(),cp=ka(),Ei=x();function lp(e,t,r){let i=Ec.createNode(e,void 0,r),n=Ec.createNode(t,void 0,r);return new Ci(i,n)}var Ci=class e{constructor(t,r=null){Object.defineProperty(this,Ei.NODE_TYPE,{value:Ei.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return Ei.isNode(r)&&(r=r.clone(t)),Ei.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return cp.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?sp.stringifyPair(this,t,r,i):JSON.stringify(this)}};Sa.Pair=Ci;Sa.createPair=lp});var Ea=w(xc=>{"use strict";var mt=x(),Cc=hr(),xi=lr();function up(e,t,r){return(t.inFlow??e.flow?fp:dp)(e,t,r)}function dp({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(mt.isNode(h))!d&&h.spaceBefore&&f.push(""),Pi(r,f,h.commentBefore,d),h.comment&&(m=h.comment);else if(mt.isPair(h)){let N=mt.isNode(h.key)?h.key:null;N&&(!d&&N.spaceBefore&&f.push(""),Pi(r,f,N.commentBefore,d))}d=!1;let y=Cc.stringify(h,u,()=>m=null,()=>d=!0);m&&(y+=xi.lineComment(y,a,l(m))),d&&m&&(d=!1),f.push(i+y)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let v=1;v<f.length;++v){let h=f[v];p+=h?`
|
|
48
|
+
${c}${h}`:`
|
|
49
|
+
`}}return e?(p+=`
|
|
50
|
+
`+xi.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function fp({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(mt.isNode(h))h.spaceBefore&&d.push(""),Pi(t,d,h.commentBefore,!1),h.comment&&(m=h.comment);else if(mt.isPair(h)){let N=mt.isNode(h.key)?h.key:null;N&&(N.spaceBefore&&d.push(""),Pi(t,d,N.commentBefore,!1),N.comment&&(l=!0));let k=mt.isNode(h.value)?h.value:null;k?(k.comment&&(m=k.comment),k.commentBefore&&(l=!0)):h.value==null&&N?.comment&&(m=N.comment)}m&&(l=!0);let y=Cc.stringify(h,c,()=>m=null);l||(l=d.length>u||y.includes(`
|
|
51
|
+
`)),v<e.length-1?y+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((N,k)=>N+k.length+2,2)+(y.length+2)>t.options.lineWidth)),l&&(y+=",")),m&&(y+=xi.lineComment(y,i,s(m))),d.push(y),u=d.length}let{start:f,end:p}=r;if(d.length===0)return f+p;if(!l){let v=d.reduce((h,m)=>h+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let h of d)v+=h?`
|
|
52
|
+
${a}${n}${h}`:`
|
|
53
53
|
`;return`${v}
|
|
54
|
-
${n}${
|
|
55
|
-
`:" ")}return
|
|
54
|
+
${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Pi({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=xi.indentComment(t(i),e);r.push(a.trimStart())}}xc.stringifyCollection=up});var Ye=w(xa=>{"use strict";var hp=Ea(),pp=ka(),mp=hi(),Ke=x(),Ri=Ue(),vp=$();function mr(e,t){let r=Ke.isScalar(t)?t.value:t;for(let i of e)if(Ke.isPair(i)&&(i.key===t||i.key===r||Ke.isScalar(i.key)&&i.key.value===r))return i}var Ca=class extends mp.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ke.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Ri.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;Ke.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new Ri.Pair(t,t?.value):i=new Ri.Pair(t.key,t.value);let n=mr(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Ke.isScalar(n.value)&&vp.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=mr(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=mr(this.items,t)?.value;return(!r&&Ke.isScalar(n)?n.value:n)??void 0}has(t){return!!mr(this.items,t)}set(t,r){this.add(new Ri.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)pp.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Ke.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),hp.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};xa.YAMLMap=Ca;xa.findPair=mr});var _t=w(Rc=>{"use strict";var gp=x(),Pc=Ye(),wp={collection:"map",default:!0,nodeClass:Pc.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return gp.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Pc.YAMLMap.from(e,t,r)};Rc.map=wp});var Xe=w(Ac=>{"use strict";var yp=cr(),Np=Ea(),bp=hi(),_i=x(),kp=$(),Sp=We(),Pa=class extends bp.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(_i.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Ai(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=Ai(t);if(typeof i!="number")return;let n=this.items[i];return!r&&_i.isScalar(n)?n.value:n}has(t){let r=Ai(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=Ai(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];_i.isScalar(n)&&kp.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(Sp.toJS(a,String(n++),r));return i}toString(t,r,i){return t?Np.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(yp.createNode(s,void 0,i))}}return a}};function Ai(e){let t=_i.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Ac.YAMLSeq=Pa});var It=w(Ic=>{"use strict";var Ep=x(),_c=Xe(),Cp={collection:"seq",default:!0,nodeClass:_c.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Ep.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>_c.YAMLSeq.from(e,t,r)};Ic.seq=Cp});var vr=w(Tc=>{"use strict";var xp=fr(),Pp={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),xp.stringifyString(e,t,r,i)}};Tc.string=Pp});var Ii=w(Oc=>{"use strict";var jc=$(),$c={identify:e=>e==null,createNode:()=>new jc.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new jc.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&$c.test.test(e)?e:t.options.nullStr};Oc.nullTag=$c});var Ra=w(Dc=>{"use strict";var Rp=$(),Hc={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Rp.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Hc.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Dc.boolTag=Hc});var Tt=w(Lc=>{"use strict";function Ap({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Lc.stringifyNumber=Ap});var _a=w(Ti=>{"use strict";var _p=$(),Aa=Tt(),Ip={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:Aa.stringifyNumber},Tp={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Aa.stringifyNumber(e)}},jp={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 _p.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Aa.stringifyNumber};Ti.float=jp;Ti.floatExp=Tp;Ti.floatNaN=Ip});var Ta=w($i=>{"use strict";var Bc=Tt(),ji=e=>typeof e=="bigint"||Number.isInteger(e),Ia=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Vc(e,t,r){let{value:i}=e;return ji(i)&&i>=0?r+i.toString(t):Bc.stringifyNumber(e)}var $p={identify:e=>ji(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Ia(e,2,8,r),stringify:e=>Vc(e,8,"0o")},Op={identify:ji,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Ia(e,0,10,r),stringify:Bc.stringifyNumber},Hp={identify:e=>ji(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Ia(e,2,16,r),stringify:e=>Vc(e,16,"0x")};$i.int=Op;$i.intHex=Hp;$i.intOct=$p});var Fc=w(Mc=>{"use strict";var Dp=_t(),Lp=Ii(),Bp=It(),Vp=vr(),Mp=Ra(),ja=_a(),$a=Ta(),Fp=[Dp.map,Bp.seq,Vp.string,Lp.nullTag,Mp.boolTag,$a.intOct,$a.int,$a.intHex,ja.floatNaN,ja.floatExp,ja.float];Mc.schema=Fp});var zc=w(Wc=>{"use strict";var qp=$(),Wp=_t(),zp=It();function qc(e){return typeof e=="bigint"||Number.isInteger(e)}var Oi=({value:e})=>JSON.stringify(e),Jp=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Oi},{identify:e=>e==null,createNode:()=>new qp.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Oi},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Oi},{identify:qc,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>qc(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Oi}],Gp={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Up=[Wp.map,zp.seq].concat(Jp,Gp);Wc.schema=Up});var Ha=w(Jc=>{"use strict";var gr=ni("buffer"),Oa=$(),Kp=fr(),Yp={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof gr.Buffer=="function")return gr.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof gr.Buffer=="function")s=o instanceof gr.Buffer?o.toString("base64"):gr.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Oa.Scalar.BLOCK_LITERAL),t!==Oa.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===Oa.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return Kp.stringifyString({comment:e,type:t,value:s},i,n,a)}};Jc.binary=Yp});var Li=w(Di=>{"use strict";var Hi=x(),Da=Ue(),Xp=$(),Qp=Xe();function Gc(e,t){if(Hi.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Hi.isPair(i)){if(Hi.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new Da.Pair(new Xp.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
|
|
56
56
|
${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
|
|
57
|
-
${a.comment}`:i.comment}i=n}t.items[r]=Oi.isPair(i)?i:new $a.Pair(i)}}else e("Expected a sequence for this tag");return t}function Kc(t,e,r){let{replacer:i}=r,n=new Xh.YAMLSeq(t);n.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,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($a.createPair(s,c,r))}return n}var Qh={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Uc,createNode:Kc};Hi.createPairs=Kc;Hi.pairs=Qh;Hi.resolvePairs=Uc});var Da=w(Ha=>{"use strict";var Yc=x(),Oa=qe(),mr=Ke(),Zh=Ye(),Xc=Di(),ht=class t extends Zh.YAMLSeq{constructor(){super(),this.add=mr.YAMLMap.prototype.add.bind(this),this.delete=mr.YAMLMap.prototype.delete.bind(this),this.get=mr.YAMLMap.prototype.get.bind(this),this.has=mr.YAMLMap.prototype.has.bind(this),this.set=mr.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Yc.isPair(n)?(a=Oa.toJS(n.key,"",r),o=Oa.toJS(n.value,a,r)):a=Oa.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(e,r,i){let n=Xc.createPairs(e,r,i),a=new this;return a.items=n.items,a}};ht.tag="tag:yaml.org,2002:omap";var em={collection:"seq",identify:t=>t instanceof Map,nodeClass:ht,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let r=Xc.resolvePairs(t,e),i=[];for(let{key:n}of r.items)Yc.isScalar(n)&&(i.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new ht,r)},createNode:(t,e,r)=>ht.from(t,e,r)};Ha.YAMLOMap=ht;Ha.omap=em});var rl=w(La=>{"use strict";var Qc=$();function Zc({value:t,source:e},r){return e&&(t?el:tl).test.test(e)?e:t?r.options.trueStr:r.options.falseStr}var el={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Qc.Scalar(!0),stringify:Zc},tl={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Qc.Scalar(!1),stringify:Zc};La.falseTag=tl;La.trueTag=el});var il=w(Li=>{"use strict";var tm=$(),Ba=It(),rm={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ba.stringifyNumber},im={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Ba.stringifyNumber(t)}},nm={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new tm.Scalar(parseFloat(t.replace(/_/g,""))),r=t.indexOf(".");if(r!==-1){let i=t.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:Ba.stringifyNumber};Li.float=nm;Li.floatExp=im;Li.floatNaN=rm});var al=w(gr=>{"use strict";var nl=It(),vr=t=>typeof t=="bigint"||Number.isInteger(t);function Bi(t,e,r,{intAsBigInt:i}){let n=t[0];if((n==="-"||n==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(r){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return n==="-"?BigInt(-1)*o:o}let a=parseInt(t,r);return n==="-"?-1*a:a}function Ma(t,e,r){let{value:i}=t;if(vr(i)){let n=i.toString(e);return i<0?"-"+r+n.substr(1):r+n}return nl.stringifyNumber(t)}var am={identify:vr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,r)=>Bi(t,2,2,r),stringify:t=>Ma(t,2,"0b")},om={identify:vr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,r)=>Bi(t,1,8,r),stringify:t=>Ma(t,8,"0")},sm={identify:vr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,r)=>Bi(t,0,10,r),stringify:nl.stringifyNumber},cm={identify:vr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,r)=>Bi(t,2,16,r),stringify:t=>Ma(t,16,"0x")};gr.int=sm;gr.intBin=am;gr.intHex=cm;gr.intOct=om});var Fa=w(Va=>{"use strict";var Fi=x(),Mi=Ge(),Vi=Ke(),mt=class t extends Vi.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let r;Fi.isPair(e)?r=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?r=new Mi.Pair(e.key,null):r=new Mi.Pair(e,null),Vi.findPair(this.items,r.key)||this.items.push(r)}get(e,r){let i=Vi.findPair(this.items,e);return!r&&Fi.isPair(i)?Fi.isScalar(i.key)?i.key.value:i.key:i}set(e,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Vi.findPair(this.items,e);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Mi.Pair(e))}toJSON(e,r){return super.toJSON(e,r,Set)}toString(e,r,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(e,r,i){let{replacer:n}=i,a=new this(e);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Mi.createPair(o,null,i));return a}};mt.tag="tag:yaml.org,2002:set";var lm={collection:"map",identify:t=>t instanceof Set,nodeClass:mt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,r)=>mt.from(t,e,r),resolve(t,e){if(Fi.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new mt,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Va.YAMLSet=mt;Va.set=lm});var Wa=w(qi=>{"use strict";var um=It();function qa(t,e){let r=t[0],i=r==="-"||r==="+"?t.substring(1):t,n=o=>e?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 ol(t){let{value:e}=t,r=o=>o;if(typeof e=="bigint")r=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return um.stringifyNumber(t);let i="";e<0&&(i="-",e*=r(-1));let n=r(60),a=[e%n];return e<60?a.unshift(0):(e=(e-a[0])/n,a.unshift(e%n),e>=60&&(e=(e-a[0])/n,a.unshift(e))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var dm={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:r})=>qa(t,r),stringify:ol},fm={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>qa(t,!1),stringify:ol},sl={identify:t=>t 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(t){let e=t.match(sl.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=e[8];if(u&&u!=="Z"){let d=qa(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};qi.floatTime=fm;qi.intTime=dm;qi.timestamp=sl});var ul=w(ll=>{"use strict";var pm=At(),hm=_i(),mm=_t(),vm=pr(),gm=ja(),cl=rl(),za=il(),Wi=al(),wm=ki(),ym=Da(),Nm=Di(),bm=Fa(),Ja=Wa(),km=[pm.map,mm.seq,vm.string,hm.nullTag,cl.trueTag,cl.falseTag,Wi.intBin,Wi.intOct,Wi.int,Wi.intHex,za.floatNaN,za.floatExp,za.float,gm.binary,wm.merge,ym.omap,Nm.pairs,bm.set,Ja.intTime,Ja.floatTime,Ja.timestamp];ll.schema=km});var Nl=w(Ka=>{"use strict";var hl=At(),Sm=_i(),ml=_t(),Em=pr(),Cm=Ca(),Ga=Pa(),Ua=Aa(),xm=qc(),Pm=Jc(),vl=ja(),wr=ki(),gl=Da(),wl=Di(),dl=ul(),yl=Fa(),zi=Wa(),fl=new Map([["core",xm.schema],["failsafe",[hl.map,ml.seq,Em.string]],["json",Pm.schema],["yaml11",dl.schema],["yaml-1.1",dl.schema]]),pl={binary:vl.binary,bool:Cm.boolTag,float:Ga.float,floatExp:Ga.floatExp,floatNaN:Ga.floatNaN,floatTime:zi.floatTime,int:Ua.int,intHex:Ua.intHex,intOct:Ua.intOct,intTime:zi.intTime,map:hl.map,merge:wr.merge,null:Sm.nullTag,omap:gl.omap,pairs:wl.pairs,seq:ml.seq,set:yl.set,timestamp:zi.timestamp},Rm={"tag:yaml.org,2002:binary":vl.binary,"tag:yaml.org,2002:merge":wr.merge,"tag:yaml.org,2002:omap":gl.omap,"tag:yaml.org,2002:pairs":wl.pairs,"tag:yaml.org,2002:set":yl.set,"tag:yaml.org,2002:timestamp":zi.timestamp};function Am(t,e,r){let i=fl.get(e);if(i&&!t)return r&&!i.includes(wr.merge)?i.concat(wr.merge):i.slice();let n=i;if(!n)if(Array.isArray(t))n=[];else{let a=Array.from(fl.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)n=n.concat(a);else typeof t=="function"&&(n=t(n.slice()));return r&&(n=n.concat(wr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?pl[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(pl).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},[])}Ka.coreKnownTags=Rm;Ka.getTags=Am});var Qa=w(bl=>{"use strict";var Ya=x(),_m=At(),Im=_t(),Tm=pr(),Ji=Nl(),jm=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,Xa=class t{constructor({compat:e,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?Ji.getTags(e,"compat"):e?Ji.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ji.coreKnownTags:{},this.tags=Ji.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Ya.MAP,{value:_m.map}),Object.defineProperty(this,Ya.SCALAR,{value:Tm.string}),Object.defineProperty(this,Ya.SEQ,{value:Im.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?jm:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};bl.Schema=Xa});var Sl=w(kl=>{"use strict";var $m=x(),Za=ur(),yr=or();function Om(t,e){let r=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(r.push(c),i=!0):t.directives.docStart&&(i=!0)}i&&r.push("---");let n=Za.createStringifyContext(t,e),{commentString:a}=n.options;if(t.commentBefore){r.length!==1&&r.unshift("");let c=a(t.commentBefore);r.unshift(yr.indentComment(c,""))}let o=!1,s=null;if(t.contents){if($m.isNode(t.contents)){if(t.contents.spaceBefore&&i&&r.push(""),t.contents.commentBefore){let u=a(t.contents.commentBefore);r.push(yr.indentComment(u,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Za.stringify(t.contents,n,()=>s=null,c);s&&(l+=yr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Za.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
|
|
58
|
-
`)?(r.push("..."),r.push(
|
|
57
|
+
${a.comment}`:i.comment}i=n}e.items[r]=Hi.isPair(i)?i:new Da.Pair(i)}}else t("Expected a sequence for this tag");return e}function Uc(e,t,r){let{replacer:i}=r,n=new Qp.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(Da.createPair(s,c,r))}return n}var Zp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Gc,createNode:Uc};Di.createPairs=Uc;Di.pairs=Zp;Di.resolvePairs=Gc});var Va=w(Ba=>{"use strict";var Kc=x(),La=We(),wr=Ye(),em=Xe(),Yc=Li(),vt=class e extends em.YAMLSeq{constructor(){super(),this.add=wr.YAMLMap.prototype.add.bind(this),this.delete=wr.YAMLMap.prototype.delete.bind(this),this.get=wr.YAMLMap.prototype.get.bind(this),this.has=wr.YAMLMap.prototype.has.bind(this),this.set=wr.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(Kc.isPair(n)?(a=La.toJS(n.key,"",r),o=La.toJS(n.value,a,r)):a=La.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=Yc.createPairs(t,r,i),a=new this;return a.items=n.items,a}};vt.tag="tag:yaml.org,2002:omap";var tm={collection:"seq",identify:e=>e instanceof Map,nodeClass:vt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Yc.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Kc.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new vt,r)},createNode:(e,t,r)=>vt.from(e,t,r)};Ba.YAMLOMap=vt;Ba.omap=tm});var tl=w(Ma=>{"use strict";var Xc=$();function Qc({value:e,source:t},r){return t&&(e?Zc:el).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Zc={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 Xc.Scalar(!0),stringify:Qc},el={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 Xc.Scalar(!1),stringify:Qc};Ma.falseTag=el;Ma.trueTag=Zc});var rl=w(Bi=>{"use strict";var rm=$(),Fa=Tt(),im={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:Fa.stringifyNumber},nm={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():Fa.stringifyNumber(e)}},am={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 rm.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:Fa.stringifyNumber};Bi.float=am;Bi.floatExp=nm;Bi.floatNaN=im});var nl=w(Nr=>{"use strict";var il=Tt(),yr=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 qa(e,t,r){let{value:i}=e;if(yr(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return il.stringifyNumber(e)}var om={identify:yr,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=>qa(e,2,"0b")},sm={identify:yr,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=>qa(e,8,"0")},cm={identify:yr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Vi(e,0,10,r),stringify:il.stringifyNumber},lm={identify:yr,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=>qa(e,16,"0x")};Nr.int=cm;Nr.intBin=om;Nr.intHex=lm;Nr.intOct=sm});var za=w(Wa=>{"use strict";var qi=x(),Mi=Ue(),Fi=Ye(),gt=class e extends Fi.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;qi.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Mi.Pair(t.key,null):r=new Mi.Pair(t,null),Fi.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Fi.findPair(this.items,t);return!r&&qi.isPair(i)?qi.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=Fi.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Mi.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(Mi.createPair(o,null,i));return a}};gt.tag="tag:yaml.org,2002:set";var um={collection:"map",identify:e=>e instanceof Set,nodeClass:gt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>gt.from(e,t,r),resolve(e,t){if(qi.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new gt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Wa.YAMLSet=gt;Wa.set=um});var Ga=w(Wi=>{"use strict";var dm=Tt();function Ja(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 al(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return dm.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 fm={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})=>Ja(e,r),stringify:al},hm={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=>Ja(e,!1),stringify:al},ol={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(ol.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=Ja(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$/,"")??""};Wi.floatTime=hm;Wi.intTime=fm;Wi.timestamp=ol});var ll=w(cl=>{"use strict";var pm=_t(),mm=Ii(),vm=It(),gm=vr(),wm=Ha(),sl=tl(),Ua=rl(),zi=nl(),ym=Si(),Nm=Va(),bm=Li(),km=za(),Ka=Ga(),Sm=[pm.map,vm.seq,gm.string,mm.nullTag,sl.trueTag,sl.falseTag,zi.intBin,zi.intOct,zi.int,zi.intHex,Ua.floatNaN,Ua.floatExp,Ua.float,wm.binary,ym.merge,Nm.omap,bm.pairs,km.set,Ka.intTime,Ka.floatTime,Ka.timestamp];cl.schema=Sm});var yl=w(Qa=>{"use strict";var hl=_t(),Em=Ii(),pl=It(),Cm=vr(),xm=Ra(),Ya=_a(),Xa=Ta(),Pm=Fc(),Rm=zc(),ml=Ha(),br=Si(),vl=Va(),gl=Li(),ul=ll(),wl=za(),Ji=Ga(),dl=new Map([["core",Pm.schema],["failsafe",[hl.map,pl.seq,Cm.string]],["json",Rm.schema],["yaml11",ul.schema],["yaml-1.1",ul.schema]]),fl={binary:ml.binary,bool:xm.boolTag,float:Ya.float,floatExp:Ya.floatExp,floatNaN:Ya.floatNaN,floatTime:Ji.floatTime,int:Xa.int,intHex:Xa.intHex,intOct:Xa.intOct,intTime:Ji.intTime,map:hl.map,merge:br.merge,null:Em.nullTag,omap:vl.omap,pairs:gl.pairs,seq:pl.seq,set:wl.set,timestamp:Ji.timestamp},Am={"tag:yaml.org,2002:binary":ml.binary,"tag:yaml.org,2002:merge":br.merge,"tag:yaml.org,2002:omap":vl.omap,"tag:yaml.org,2002:pairs":gl.pairs,"tag:yaml.org,2002:set":wl.set,"tag:yaml.org,2002:timestamp":Ji.timestamp};function _m(e,t,r){let i=dl.get(t);if(i&&!e)return r&&!i.includes(br.merge)?i.concat(br.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(dl.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(br.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?fl[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(fl).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},[])}Qa.coreKnownTags=Am;Qa.getTags=_m});var to=w(Nl=>{"use strict";var Za=x(),Im=_t(),Tm=It(),jm=vr(),Gi=yl(),$m=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,eo=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Gi.getTags(t,"compat"):t?Gi.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Gi.coreKnownTags:{},this.tags=Gi.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Za.MAP,{value:Im.map}),Object.defineProperty(this,Za.SCALAR,{value:jm.string}),Object.defineProperty(this,Za.SEQ,{value:Tm.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?$m:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Nl.Schema=eo});var kl=w(bl=>{"use strict";var Om=x(),ro=hr(),kr=lr();function Hm(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=ro.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(kr.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Om.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(kr.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=ro.stringify(e.contents,n,()=>s=null,c);s&&(l+=kr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(ro.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
+
`)?(r.push("..."),r.push(kr.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(kr.indentComment(a(c),"")))}return r.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}bl.stringifyDocument=Hm});var Sr=w(Sl=>{"use strict";var Dm=sr(),jt=hi(),ie=x(),Lm=Ue(),Bm=We(),Vm=to(),Mm=kl(),io=li(),Fm=sa(),qm=cr(),no=oa(),ao=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ie.NODE_TYPE,{value:ie.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 no.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,{[ie.NODE_TYPE]:{value:ie.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=ie.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){$t(this.contents)&&this.contents.add(t)}addIn(t,r){$t(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=io.anchorNames(this);t.anchor=!r||i.has(r)?io.findNewAnchor(r||"a",i):r}return new Dm.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=N=>typeof N=="number"||N instanceof String||N instanceof Number,y=r.filter(m).map(String);y.length>0&&(r=r.concat(y)),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}=io.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=qm.createNode(t,u,v);return s&&ie.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 Lm.Pair(n,a)}delete(t){return $t(this.contents)?this.contents.delete(t):!1}deleteIn(t){return jt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):$t(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return ie.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return jt.isEmptyPath(t)?!r&&ie.isScalar(this.contents)?this.contents.value:this.contents:ie.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return ie.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return jt.isEmptyPath(t)?this.contents!==void 0:ie.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=jt.collectionFromPath(this.schema,[t],r):$t(this.contents)&&this.contents.set(t,r)}setIn(t,r){jt.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=jt.collectionFromPath(this.schema,Array.from(t),r):$t(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 no.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 no.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 Vm.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=Bm.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"?Fm.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 Mm.stringifyDocument(this,t)}};function $t(e){if(ie.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Sl.Document=ao});var xr=w(Cr=>{"use strict";var Er=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},oo=class extends Er{constructor(t,r,i){super("YAMLParseError",t,r,i)}},so=class extends Er{constructor(t,r,i){super("YAMLWarning",t,r,i)}},Wm=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};
|
|
66
|
-
`))return!0;if(
|
|
67
|
-
`+
|
|
68
|
-
`+k.comment:N.comment=k.comment);let S=new
|
|
69
|
-
`+g.comment:l.comment=g.comment),d=g.end;continue}!o&&r.options.strict&&
|
|
70
|
-
`+P:b.comment=P,g.comment=g.comment.substring(P.length+1)}}if(!o&&!S&&!g.found){let P=E?
|
|
71
|
-
`+I.comment:b.comment=I.comment);let
|
|
72
|
-
`+m.comment:l.comment=m.comment),l.range=[i.offset,
|
|
73
|
-
`.repeat(Math.max(1,o.length-1)):"",m=i+n.length;return
|
|
74
|
-
`;for(let
|
|
65
|
+
`}};Cr.YAMLError=Er;Cr.YAMLParseError=oo;Cr.YAMLWarning=so;Cr.prettifyError=Wm});var Pr=w(El=>{"use strict";function zm(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,v=!1,h=null,m=null,y=null,N=null,k=null,S=null,E=null;for(let b of e)switch(v&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&b.type!=="comment"&&b.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),u=!0;break;case"comment":{u||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let I=b.source.substring(1)||" ";d?d+=f+I:d=I,f="",l=!1;break}case"newline":l?d?d+=b.source:(!S||r!=="seq-item-ind")&&(c=!0):f+=b.source,l=!0,p=!0,(m||y)&&(N=b),u=!0;break;case"anchor":m&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=b,E??(E=b.offset),l=!1,u=!1,v=!0;break;case"tag":{y&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),y=b,E??(E=b.offset),l=!1,u=!1,v=!0;break}case r:(m||y)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),S&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),S=b,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=b,l=!1,u=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,u=!1}let g=e[e.length-1],P=g?g.offset+g.source.length:n;return v&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:y,newlineAfterProp:N,end:P,start:E??P}}El.resolveProps=zm});var Ui=w(Cl=>{"use strict";function co(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(co(t.key)||co(t.value))return!0}return!1;default:return!0}}Cl.containsNewline=co});var lo=w(xl=>{"use strict";var Jm=Ui();function Gm(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&Jm.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}xl.flowIndentCheck=Gm});var uo=w(Rl=>{"use strict";var Pl=x();function Um(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Pl.isScalar(a)&&Pl.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}Rl.mapIncludes=Um});var $l=w(jl=>{"use strict";var Al=Ue(),Km=Ye(),_l=Pr(),Ym=Ui(),Il=lo(),Xm=uo(),Tl="All mapping items must start at the same column";function Qm({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Km.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let u of i.items){let{start:d,key:f,sep:p,value:v}=u,h=_l.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),m=!h.found;if(m){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==i.indent&&n(c,"BAD_INDENT",Tl)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Ym.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(c,"BAD_INDENT",Tl);r.atKey=!0;let y=h.end,N=f?e(r,f,h,n):t(r,y,d,null,h,n);r.schema.compat&&Il.flowIndentCheck(i.indent,f,n),r.atKey=!1,Xm.mapIncludes(r,s.items,N)&&n(y,"DUPLICATE_KEY","Map keys must be unique");let k=_l.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:N.range[2],onError:n,parentIndent:i.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){m&&(v?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<k.found.offset-1024&&n(N.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let S=v?e(r,v,k,n):t(r,c,p,null,k,n);r.schema.compat&&Il.flowIndentCheck(i.indent,v,n),c=S.range[2];let E=new Al.Pair(N,S);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{m&&n(N.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(N.comment?N.comment+=`
|
|
68
|
+
`+k.comment:N.comment=k.comment);let S=new Al.Pair(N);r.options.keepSourceTokens&&(S.srcToken=u),s.items.push(S)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}jl.resolveBlockMap=Qm});var Hl=w(Ol=>{"use strict";var Zm=Xe(),ev=Pr(),tv=lo();function rv({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Zm.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:d}of i.items){let f=ev.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(r,d,f,n):t(r,f.end,u,null,f,n);r.schema.compat&&tv.flowIndentCheck(i.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[i.offset,c,l??c],s}Ol.resolveBlockSeq=rv});var Ot=w(Dl=>{"use strict";function iv(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Dl.resolveEnd=iv});var Ml=w(Vl=>{"use strict";var nv=x(),av=Ue(),Ll=Ye(),ov=Xe(),sv=Ot(),Bl=Pr(),cv=Ui(),lv=uo(),fo="Block collections are not allowed within flow collections",ho=e=>e&&(e.type==="block-map"||e.type==="block-seq");function uv({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Ll.YAMLMap:ov.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let m=0;m<i.items.length;++m){let y=i.items[m],{start:N,key:k,sep:S,value:E}=y,g=Bl.resolveProps(N,{flow:s,indicator:"explicit-key-ind",next:k??S?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!g.found){if(!g.anchor&&!g.tag&&!S&&!E){m===0&&g.comma?n(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<i.items.length-1&&n(g.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),g.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+g.comment:l.comment=g.comment),d=g.end;continue}!o&&r.options.strict&&cv.containsNewline(k)&&n(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)g.comma&&n(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(g.comma||n(g.start,"MISSING_CHAR",`Missing , between ${s} items`),g.comment){let P="";e:for(let b of N)switch(b.type){case"comma":case"space":break;case"comment":P=b.source.substring(1);break e;default:break e}if(P){let b=l.items[l.items.length-1];nv.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
|
|
70
|
+
`+P:b.comment=P,g.comment=g.comment.substring(P.length+1)}}if(!o&&!S&&!g.found){let P=E?e(r,E,g,n):t(r,g.end,S,null,g,n);l.items.push(P),d=P.range[2],ho(E)&&n(P.range,"BLOCK_IN_FLOW",fo)}else{r.atKey=!0;let P=g.end,b=k?e(r,k,g,n):t(r,P,N,null,g,n);ho(k)&&n(b.range,"BLOCK_IN_FLOW",fo),r.atKey=!1;let I=Bl.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:E,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(I.found){if(!o&&!g.found&&r.options.strict){if(S)for(let H of S){if(H===I.found)break;if(H.type==="newline"){n(H,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}g.start<I.found.offset-1024&&n(I.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(I.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let X=E?e(r,E,I,n):I.found?t(r,I.end,S,null,I,n):null;X?ho(E)&&n(X.range,"BLOCK_IN_FLOW",fo):I.comment&&(b.comment?b.comment+=`
|
|
71
|
+
`+I.comment:b.comment=I.comment);let Ct=new av.Pair(b,X);if(r.options.keepSourceTokens&&(Ct.srcToken=y),o){let H=l;lv.mapIncludes(r,H.items,b)&&n(P,"DUPLICATE_KEY","Map keys must be unique"),H.items.push(Ct)}else{let H=new Ll.YAMLMap(r.schema);H.flow=!0,H.items.push(Ct);let Vs=(X??b).range;H.range=[b.range[0],Vs[1],Vs[2]],l.items.push(H)}d=X?X.range[2]:I.end}}let f=o?"}":"]",[p,...v]=i.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),y=u?`${m} must end with a ${f}`:`${m} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",y),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=sv.resolveEnd(v,h,r.options.strict,n);m.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+m.comment:l.comment=m.comment),l.range=[i.offset,h,m.offset]}else l.range=[i.offset,h,h];return l}Vl.resolveFlowCollection=uv});var ql=w(Fl=>{"use strict";var dv=x(),fv=$(),hv=Ye(),pv=Xe(),mv=$l(),vv=Hl(),gv=Ml();function po(e,t,r,i,n,a){let o=r.type==="block-map"?mv.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?vv.resolveBlockSeq(e,t,r,i,a):gv.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function wv(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(r.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=i,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!p||p.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===hv.YAMLMap.tagName&&s==="map"||o===pv.YAMLSeq.tagName&&s==="seq")return po(e,t,r,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),po(e,t,r,n,o)}let l=po(e,t,r,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=dv.isNode(u)?u:new fv.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Fl.composeCollection=wv});var vo=w(Wl=>{"use strict";var mo=$();function yv(e,t,r){let i=t.offset,n=Nv(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?mo.Scalar.BLOCK_FOLDED:mo.Scalar.BLOCK_LITERAL,o=t.source?bv(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,o.length-1)):"",m=i+n.length;return t.source&&(m+=t.source.length),{value:h,type:a,comment:n.comment,range:[i,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[m,y]=o[h];if(y===""||y==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&r(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=m.length),u=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+y.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",f="",p=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
|
|
74
|
+
`;for(let h=u;h<s;++h){let[m,y]=o[h];l+=m.length+y.length+1;let N=y[y.length-1]==="\r";if(N&&(y=y.slice(0,-1)),y&&m.length<c){let S=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-y.length-(N?2:1),"BAD_INDENT",S),m=""}a===mo.Scalar.BLOCK_LITERAL?(d+=f+m.slice(c)+y,f=`
|
|
75
75
|
`):m.length>c||y[0]===" "?(f===" "?f=`
|
|
76
|
-
`:!
|
|
76
|
+
`:!p&&f===`
|
|
77
77
|
`&&(f=`
|
|
78
78
|
|
|
79
79
|
`),d+=f+m.slice(c)+y,f=`
|
|
80
|
-
`,
|
|
80
|
+
`,p=!0):y===""?f===`
|
|
81
81
|
`?d+=`
|
|
82
82
|
`:f=`
|
|
83
|
-
`:(d+=f+y,f=" ",
|
|
84
|
-
`+o[
|
|
83
|
+
`:(d+=f+y,f=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
|
|
84
|
+
`+o[h][0].slice(c);d[d.length-1]!==`
|
|
85
85
|
`&&(d+=`
|
|
86
86
|
`);break;default:d+=`
|
|
87
|
-
`}let v=i+n.length+
|
|
87
|
+
`}let v=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,v,v]}}function Nv({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let p=n[f];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":r&&!l&&i(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":i(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;i(p,"UNEXPECTED_TOKEN",v);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function bv(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Wl.resolveBlockScalar=yv});var wo=w(Jl=>{"use strict";var go=$(),kv=Ot();function Sv(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(f,p,v)=>r(i+f,p,v);switch(n){case"scalar":s=go.Scalar.PLAIN,c=Ev(a,l);break;case"single-quoted-scalar":s=go.Scalar.QUOTE_SINGLE,c=Cv(a,l);break;case"double-quoted-scalar":s=go.Scalar.QUOTE_DOUBLE,c=xv(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let u=i+a.length,d=kv.resolveEnd(o,u,t,r);return{value:c,type:s,comment:d.comment,range:[i,u,d.offset]}}function Ev(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),zl(e)}function Cv(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),zl(e.slice(1,-1)).replace(/''/g,"'")}function zl(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
|
-
`,"sy")}catch{
|
|
89
|
+
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let n=i[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;i=r.exec(e);)i[1]===""?a===`
|
|
90
90
|
`?n+=a:a=`
|
|
91
|
-
`:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(
|
|
91
|
+
`:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function xv(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
|
|
92
92
|
`))if(n===`
|
|
93
|
-
`){let{fold:a,offset:o}=
|
|
94
|
-
`)for(a=
|
|
95
|
-
`)for(a=
|
|
96
|
-
`&&!(o==="\r"&&
|
|
97
|
-
`)&&(r+=i>a?
|
|
98
|
-
`||i==="\r")&&!(i==="\r"&&t
|
|
93
|
+
`){let{fold:a,offset:o}=Pv(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=Rv[a];if(o)r+=o;else if(a===`
|
|
94
|
+
`)for(a=e[i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="\r"&&e[i+1]===`
|
|
95
|
+
`)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=Av(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
|
|
96
|
+
`&&!(o==="\r"&&e[i+2]===`
|
|
97
|
+
`)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function Pv(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
|
|
98
|
+
`||i==="\r")&&!(i==="\r"&&e[t+2]!==`
|
|
99
99
|
`);)i===`
|
|
100
100
|
`&&(r+=`
|
|
101
|
-
`),
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var Rv={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Av(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Jl.resolveFlowScalar=Sv});var Kl=w(Ul=>{"use strict";var wt=x(),Gl=$(),_v=vo(),Iv=wo();function Tv(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?_v.resolveBlockScalar(e,t,i):Iv.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[wt.SCALAR]:c?l=jv(e.schema,n,c,r,i):t.type==="scalar"?l=$v(e,n,t,i):l=e.schema[wt.SCALAR];let u;try{let d=l.resolve(n,f=>i(r??t,"TAG_RESOLVE_FAILED",f),e.options);u=wt.isScalar(d)?d:new Gl.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",f),u=new Gl.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function jv(e,t,r,i,n){if(r==="!")return e[wt.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[wt.SCALAR])}function $v({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[wt.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[wt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}Ul.composeScalar=Tv});var Xl=w(Yl=>{"use strict";function Ov(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Yl.emptyScalarPosition=Ov});var eu=w(No=>{"use strict";var Hv=sr(),Dv=x(),Lv=ql(),Ql=Kl(),Bv=Ot(),Vv=Xl(),Mv={composeNode:Zl,composeEmptyNode:yo};function Zl(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=Fv(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Ql.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Lv.composeCollection(Mv,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=yo(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Dv.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function yo(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Vv.emptyScalarPosition(t,r,i),indent:-1,source:""},d=Ql.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Fv({options:e},{offset:t,source:r,end:i},n){let a=new Hv.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=Bv.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}No.composeEmptyNode=yo;No.composeNode=Zl});var iu=w(ru=>{"use strict";var qv=Sr(),tu=eu(),Wv=Ot(),zv=Pr();function Jv(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new qv.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=zv.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?tu.composeNode(l,n,u,o):tu.composeEmptyNode(l,u.end,i,null,u,o);let d=c.contents.range[2],f=Wv.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[r,d,f.offset],c}ru.composeDoc=Jv});var ko=w(ou=>{"use strict";var Gv=ni("process"),Uv=oa(),Kv=Sr(),Rr=xr(),nu=x(),Yv=iu(),Xv=Ot();function Ar(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function au(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":
|
|
106
|
-
${i}`:i;else if(n||
|
|
105
|
+
`)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var bo=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=Ar(r);a?this.warnings.push(new Rr.YAMLWarning(o,i,n)):this.errors.push(new Rr.YAMLParseError(o,i,n))},this.directives=new Uv.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=au(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(nu.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];nu.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
|
|
107
107
|
${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
|
|
108
|
-
${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)
|
|
109
|
-
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new
|
|
108
|
+
${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:au(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(Gv.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=Ar(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=Yv.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new Rr.YAMLParseError(Ar(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Rr.YAMLParseError(Ar(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=Xv.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
|
|
109
|
+
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Rr.YAMLParseError(Ar(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new Kv.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};ou.Composer=bo});var lu=w(Ki=>{"use strict";var Qv=vo(),Zv=wo(),eg=xr(),su=fr();function tg(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new eg.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Zv.resolveFlowScalar(e,t,i);case"block-scalar":return Qv.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function rg(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=su.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
111
|
`),u=s.substring(0,l),d=s.substring(l+1)+`
|
|
112
|
-
`,f=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:i,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function
|
|
114
|
-
`),i=
|
|
115
|
-
`;if(
|
|
116
|
-
`});for(let c of Object.keys(
|
|
117
|
-
`};delete
|
|
112
|
+
`,f=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return cu(f,c)||f.push({type:"newline",offset:-1,indent:i,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:i,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function ig(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=su.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":ng(e,c);break;case'"':So(e,c,"double-quoted-scalar");break;case"'":So(e,c,"single-quoted-scalar");break;default:So(e,c,"scalar")}}function ng(e,t){let r=t.indexOf(`
|
|
114
|
+
`),i=t.substring(0,r),n=t.substring(r+1)+`
|
|
115
|
+
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];cu(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function cu(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function So(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}Ki.createScalarToken=rg;Ki.resolveAsScalar=tg;Ki.setScalarValue=ig});var du=w(uu=>{"use strict";var ag=e=>"type"in e?Xi(e):Yi(e);function Xi(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Xi(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Yi(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Yi(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Yi(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Yi({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Xi(t)),r)for(let a of r)n+=a.source;return i&&(n+=Xi(i)),n}uu.stringify=ag});var mu=w(pu=>{"use strict";var Eo=Symbol("break visit"),og=Symbol("skip children"),fu=Symbol("remove item");function yt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),hu(Object.freeze([]),e,t)}yt.BREAK=Eo;yt.SKIP=og;yt.REMOVE=fu;yt.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};yt.parentCollection=(e,t)=>{let r=yt.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function hu(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=hu(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Eo)return Eo;s===fu&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}pu.visit=yt});var Qi=w(U=>{"use strict";var Co=lu(),sg=du(),cg=mu(),xo="\uFEFF",Po="",Ro="",Ao="",lg=e=>!!e&&"items"in e,ug=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function dg(e){switch(e){case xo:return"<BOM>";case Po:return"<DOC>";case Ro:return"<FLOW_END>";case Ao:return"<SCALAR>";default:return JSON.stringify(e)}}function fg(e){switch(e){case xo:return"byte-order-mark";case Po:return"doc-mode";case Ro:return"flow-error-end";case Ao:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
118
|
`:case`\r
|
|
119
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
121
|
-
\r `),
|
|
122
|
-
`?!0:r==="\r"?this.buffer[
|
|
123
|
-
`:!1}charAt(
|
|
124
|
-
`||!n&&!this.atEnd)return
|
|
125
|
-
`||i>=this.indentNext||!r&&!this.atEnd?
|
|
126
|
-
`,this.pos),this.lineEndPos=
|
|
119
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}U.createScalarToken=Co.createScalarToken;U.resolveAsScalar=Co.resolveAsScalar;U.setScalarValue=Co.setScalarValue;U.stringify=sg.stringify;U.visit=cg.visit;U.BOM=xo;U.DOCUMENT=Po;U.FLOW_END=Ro;U.SCALAR=Ao;U.isCollection=lg;U.isScalar=ug;U.prettyToken=dg;U.tokenType=fg});var To=w(gu=>{"use strict";var _r=Qi();function pe(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var vu=new Set("0123456789ABCDEFabcdef"),hg=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Zi=new Set(",[]{}"),pg=new Set(` ,[]{}
|
|
121
|
+
\r `),_o=e=>!e||pg.has(e),Io=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
|
|
122
|
+
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
123
|
+
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
|
|
124
|
+
`||!n&&!this.atEnd)return t+i+1}return r===`
|
|
125
|
+
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&pe(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
126
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===_r.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield _r.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&pe(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!pe(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&pe(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(_o),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&pe(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield _r.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(_o),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||pe(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
|
|
127
127
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
|
|
128
|
-
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let
|
|
129
|
-
`:
|
|
130
|
-
`)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(
|
|
131
|
-
`,a)}while(
|
|
132
|
-
`;)i=this.buffer[++n];
|
|
133
|
-
`&&a>=this.pos&&a+1+r>s)
|
|
128
|
+
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>pe(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
|
|
129
|
+
`:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
|
+
`)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
131
|
+
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
|
|
132
|
+
`;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
+
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield _r.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(pe(a)||t&&Zi.has(a))break;r=i}else if(pe(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(i+=1,n=`
|
|
135
|
-
`,a=this.buffer[i+1]):r=i),a==="#"||
|
|
136
|
-
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(
|
|
137
|
-
`?yield*this.pushCount(1):
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(
|
|
135
|
+
`,a=this.buffer[i+1]):r=i),a==="#"||t&&Zi.has(a))break;if(n===`
|
|
136
|
+
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Zi.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield _r.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(_o),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(pe(i)||r&&Zi.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!pe(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(hg.has(r))r=this.buffer[++t];else if(r==="%"&&vu.has(this.buffer[t+1])&&vu.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
|
+
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};gu.Lexer=Io});var $o=w(wu=>{"use strict";var jo=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};wu.LineCounter=jo});var Ho=w(Su=>{"use strict";var mg=ni("process"),yu=Qi(),vg=To();function Qe(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function Nu(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function ku(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function en(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Ht(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function tn(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function bu(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Qe(t.start,"explicit-key-ind")&&!Qe(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,ku(t.value)?t.value.end?tn(t.value.end,t.sep):t.value.end=t.sep:tn(t.start,t.sep),delete t.sep)}var Oo=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new vg.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,mg.env.LOG_TOKENS&&console.log("|",yu.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=yu.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&bu(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Nu(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Nu(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=en(this.peek(2)),i=Ht(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
140
|
-
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(
|
|
140
|
+
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){tn(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Qe(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(ku(r.key)&&!Qe(r.sep,"newline")){let o=Ht(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Qe(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Ht(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Qe(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Qe(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){tn(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Qe(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=en(i),a=Ht(n);bu(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
142
|
-
`,r)+1}return{type:
|
|
142
|
+
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=en(t),i=Ht(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=en(t),i=Ht(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Su.Parser=Oo});var Ru=w(Tr=>{"use strict";var Eu=ko(),gg=Sr(),Ir=xr(),wg=ya(),yg=x(),Ng=$o(),Cu=Ho();function xu(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Ng.LineCounter||null,prettyErrors:t}}function bg(e,t={}){let{lineCounter:r,prettyErrors:i}=xu(t),n=new Cu.Parser(r?.addNewLine),a=new Eu.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Ir.prettifyError(e,r)),s.warnings.forEach(Ir.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Pu(e,t={}){let{lineCounter:r,prettyErrors:i}=xu(t),n=new Cu.Parser(r?.addNewLine),a=new Eu.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Ir.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Ir.prettifyError(e,r)),o.warnings.forEach(Ir.prettifyError(e,r))),o}function kg(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Pu(e,r);if(!n)return null;if(n.warnings.forEach(a=>wg.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function Sg(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return yg.isDocument(e)&&!i?e.toString(r):new gg.Document(e,i,r).toString(r)}Tr.parse=kg;Tr.parseAllDocuments=bg;Tr.parseDocument=Pu;Tr.stringify=Sg});var Dt=w(R=>{"use strict";var Eg=ko(),Cg=Sr(),xg=to(),Do=xr(),Pg=sr(),Ze=x(),Rg=Ue(),Ag=$(),_g=Ye(),Ig=Xe(),Tg=Qi(),jg=To(),$g=$o(),Og=Ho(),rn=Ru(),Au=ir();R.Composer=Eg.Composer;R.Document=Cg.Document;R.Schema=xg.Schema;R.YAMLError=Do.YAMLError;R.YAMLParseError=Do.YAMLParseError;R.YAMLWarning=Do.YAMLWarning;R.Alias=Pg.Alias;R.isAlias=Ze.isAlias;R.isCollection=Ze.isCollection;R.isDocument=Ze.isDocument;R.isMap=Ze.isMap;R.isNode=Ze.isNode;R.isPair=Ze.isPair;R.isScalar=Ze.isScalar;R.isSeq=Ze.isSeq;R.Pair=Rg.Pair;R.Scalar=Ag.Scalar;R.YAMLMap=_g.YAMLMap;R.YAMLSeq=Ig.YAMLSeq;R.CST=Tg;R.Lexer=jg.Lexer;R.LineCounter=$g.LineCounter;R.Parser=Og.Parser;R.parse=rn.parse;R.parseAllDocuments=rn.parseAllDocuments;R.parseDocument=rn.parseDocument;R.stringify=rn.stringify;R.visit=Au.visit;R.visitAsync=Au.visitAsync});import Nw from"path";var $r=rr(Dt(),1);import et from"path";var Or=64*1024,nn=1024,an=64,_u=1024,Iu=64,Bo=5,jr={learning:!0,retrieval:!0},Vo={provider:"local"},Hg=12e4,Tu=6e5,Dg=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],Lg=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],Bg=[...Dg,...Lg].sort((e,t)=>e.localeCompare(t,"en"));var Z={include:["**/*"],exclude:[...Bg],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Lt={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
|
|
143
143
|
# ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
|
|
144
144
|
# learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
|
|
145
145
|
# retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
|
|
@@ -163,43 +163,44 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
|
|
|
163
163
|
# 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
|
|
164
164
|
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
165
165
|
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
166
|
-
# 可选值:true | false`}};function
|
|
167
|
-
`)){let s=
|
|
166
|
+
# 可选值:true | false`}};function $u(e,t){return Lt[t][e]}function Vg(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 Lt.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Lt.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in Lt.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in Lt.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 Lt.en)return s}return null}function Hr(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,$r.stringify)(e).trimEnd().split(`
|
|
167
|
+
`)){let s=Vg(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of $u(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 Mg(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||Ze.posix.isAbsolute(r)||Ze.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function wt(t){let e=Mg(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Hu(t,e="docs"){let r=t??e;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function an(t,e,r=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||Ze.posix.isAbsolute(i)||Ze.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return n.join("/")}function Te(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Du(t,e,r){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function on(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>rn)throw new Error(`${e} exceeds ${rn} characters`);let r=0;for(let i=0;i<t.length;i+=1)t[i]==="?"?r+=1:t[i]==="*"&&(r+=1,t[i+1]==="*"&&(i+=1));if(r>nn)throw new Error(`${e} contains more than ${nn} wildcard tokens`);return t}function $u(t,e,r){if(t===void 0)return[...r];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>on(i,e)))].sort((i,n)=>i.localeCompare(n,"en"))}function Oo(t,e,r){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Vg(t){if(t===void 0)return{...Z,include:[...Z.include],exclude:[...Z.exclude]};let e=Te(t,"native.snapshot");return{include:$u(e.include,"native.snapshot.include",Z.include),exclude:$u(e.exclude,"native.snapshot.exclude",Z.exclude),max_files:Oo(e.max_files,Z.max_files,"native.snapshot.max_files"),max_total_bytes:Oo(e.max_total_bytes,Z.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Oo(e.max_duration_ms,Z.max_duration_ms,"native.snapshot.max_duration_ms")}}function Fg(t){if(t===void 0)return;let e=Te(t,"native.pending_root_move"),r=e.id,i=e.from_artifact_root,n=e.to_artifact_root,a=e.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(e.cleanup!==void 0){let s=Te(e.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:wt(i),toArtifactRoot:wt(n),stage:a,...o?{cleanup:o}:{}}}function qg(t){if(t===void 0)return;let e=Te(t,"native.finish");if(e.pull_request===void 0)return{};let r=Te(e.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(Ze.posix.isAbsolute(i[0])||Ze.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??Og;if(!Number.isSafeInteger(n)||n<1||n>ju)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${ju}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function Wg(t,e={}){let r=Te(t,"native"),i=r.artifact_root??(e.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??Ho;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Fg(r.pending_root_move),c=qg(r.finish);return{artifact_root:wt(i),language:Du(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Vg(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function zg(t){let e=Te(t,"classic"),r=e.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=e.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Hu(e.artifact_layout),language:Du(e.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function Jg(t){let r=Te(t,"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)=>an(i,`hook.allow_paths[${n}]`)))]}}function Gg(t){if(t===void 0)return{..._r};let e=Te(t,"memory"),r=e.learning??_r.learning,i=e.retrieval??_r.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 Lo(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Ug(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Ze.posix.isAbsolute(r)||Ze.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${e} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${e} must target a Markdown file ending in .md`);if(r.length>Iu)throw new Error(`${e} exceeds ${Iu} 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>Tu)throw new Error(`${e} contains more than ${Tu} wildcard tokens`);return r}function Kg(t){let r=Lo(t,"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)=>Ug(i,`knowledge.local.include[${n}]`)))]}}function Yg(t){if(typeof t!="string"||t.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let e;try{e=new URL(t)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=e.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return e.toString()}function Xg(t){let e=Lo(t,"knowledge.remote"),r=Yg(e.endpoint),i=e.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=e.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=e.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 Qg(t){if(t===void 0)return{...Do};let e=Lo(t,"knowledge"),r=e.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=e.local===void 0?void 0:Kg(e.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=e.remote===void 0?void 0:Xg(e.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 Zg(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function ew(t,e,r,i,n,a,o,s){let c=t.schema!==void 0;if(!(c||t.default_workflow!==void 0||t.workflows!==void 0||!s.allowPartialProject&&t.native!==void 0)||s.allowPartialProject&&!c)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=t.workflows??[t.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(t.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:t.default_workflow,workflows:d,ambient_resume:o,...e?{hook:e}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Lt(t,e={}){let r=(0,Ir.parseDocument)(t,{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=Zg(n.ambient_resume),o=n.hook===void 0?void 0:Jg(n.hook),s=Gg(n.memory),c=Qg(n.knowledge),l=n.native===void 0?void 0:Wg(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),u=n.classic===void 0?void 0:zg(n.classic),d=ew(n,o,s,c,l,u,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Lu(t){return{id:t.id,from_artifact_root:t.fromArtifactRoot,to_artifact_root:t.toArtifactRoot,stage:t.stage,...t.cleanup?{cleanup:{kind:t.cleanup.kind,state:t.cleanup.state,manifest_hash:t.cleanup.manifestHash}}:{}}}function Bu(t){let e=t.knowledge??{...Do};return{schema:t.schema,default_workflow:t.default_workflow,workflows:t.workflows??[t.default_workflow],ambient_resume:t.ambient_resume,memory:t.memory??{..._r},knowledge:{provider:e.provider,...e.local&&e.local.include.length>0?{local:{include:[...e.local.include]}}:{},...e.remote?{remote:{endpoint:e.remote.endpoint,timeout_ms:e.remote.timeout_ms,...e.remote.token_env===void 0?{}:{token_env:e.remote.token_env},...e.remote.scope===void 0?{}:{scope:e.remote.scope}}}:{}},...t.hook?{hook:{allow_paths:[...t.hook.allow_paths]}}:{},...t.native?{native:{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,...t.native.finish?.pull_request?{finish:{pull_request:{provider:t.native.finish.pull_request.provider,command:[...t.native.finish.pull_request.command],timeout_ms:t.native.finish.pull_request.timeout_ms}}}:{},...t.native.pending_root_move?{pending_root_move:Lu(t.native.pending_root_move)}:{}}}:{},...t.classic?{classic:{artifact_layout:t.classic.artifact_layout,language:t.classic.language,context_compression:t.classic.context_compression,review_mode:t.classic.review_mode,auto_transition:t.classic.auto_transition}}:{}}}function Q(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function $r(t,e){let r=Bu(e),i=Lt((0,Ir.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...t,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...Q(t.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=Q(t.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=Q(t.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...Q(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...Q(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=Q(t.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=Q(a.finish);o.finish={...s,pull_request:{...Q(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={...Q(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=Q(a.pending_root_move),c=Lu(i.native.pending_root_move),l=Q(s.cleanup),u=Q(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={...Q(t.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 sn(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{..._r},knowledge:{...Do},native:{artifact_root:wt(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Ho,snapshot:{...Z,include:[...Z.include],exclude:[...Z.exclude]}}}}import{createHash as rw}from"crypto";import{promises as un}from"fs";import tt from"path";import{constants as cn,promises as yt}from"fs";function et(t){return t!==0&&t!==0n&&t!=="0"}function Ce(t,e){return et(t.dev)&&et(e.dev)&&et(t.ino)&&et(e.ino)}function T(t,e){let r=et(t.dev)&&et(e.dev);if(r&&t.dev!==e.dev)return!1;let i=et(t.ino)&&et(e.ino);return i&&t.ino!==e.ino?!1:r&&i?!0:t.birthtime===e.birthtime}var me=class extends Error{reason;constructor(e,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=e}};function Bo(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Mu(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Or(t){return{dev:t.dev,ino:t.ino,birthtime:Bo(t)}}function ln(t,e){let r=Or(t),i=Or(e);return Ce(r,i)?T(r,i):T(r,i)&&Bo(t)===Bo(e)&&Mu(t)===Mu(e)&&t.size===e.size}async function Bt(t,e,r={}){if(!Number.isSafeInteger(e)||e<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 yt.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new me("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new me("too-large",`${i} exceeds ${e} bytes`);let o=await yt.realpath(t);await r.verify?.("pre-open",{realPath:o,identity:Or(a)});let s=process.platform==="win32"?cn.O_RDONLY:cn.O_RDONLY|cn.O_NOFOLLOW|cn.O_NONBLOCK,c;try{c=await yt.open(t,s)}catch(l){throw l.code==="ELOOP"?new me("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),yt.lstat(t,{bigint:n}),yt.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ln(a,l)||!ln(a,u))throw new me("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Or(l)}),await r.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let N=e+1-h,{bytesRead:k}=await c.read(v,0,Math.min(v.length,N),null);if(k===0)break;if(h+=k,h>e)throw new me("too-large",`${i} exceeds ${e} bytes`);f.push(Buffer.from(v.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[p,m,y]=await Promise.all([c.stat({bigint:n}),yt.lstat(t,{bigint:n}),yt.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||y!==o||!ln(a,p)||!ln(a,m))throw new me("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:y,identity:Or(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:y}}finally{await c.close()}}function tw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Mo(t,e){let r=tt.relative(t,e);return r===""||!tt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${tt.sep}`)}async function Vu(t,e){let r=tt.resolve(t),i=await un.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return un.realpath(r)}async function Fu(t,e,r,i){let n=t;for(let a=0;a<r.length;a++){n=tt.join(n,r[a]);let o;try{o=await un.lstat(n)}catch(u){if(tw(u))return{exists:!1,kind:"missing"};throw u}let s=tt.relative(t,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 un.realpath(n);if(!Mo(e,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 Mt(t,e,r){let i=an(e,r.label),n=tt.resolve(t),a=await Vu(n,r.label),o=i.split("/"),s=tt.resolve(n,...o);if(!Mo(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Fu(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function rt(t,e,r,i){let n=await Mt(t,e,{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 Vu(n.projectRoot,i.label);return Bt(n.target,r,{...i,verify:async(o,s)=>{if(!Mo(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Fu(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Hr=".comet/config.yaml";function Vo(t,e){return t.exists===e.exists&&t.sha256===e.sha256}function iw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function dn(t,e={}){return(await Dr(t,e)).document}async function qu(t){try{return(await rt(t,Hr,Tr,{label:Hr})).bytes}catch(e){if(iw(e))return null;throw e}}function Wu(t){return t?{exists:!0,sha256:rw("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function fn(t){return Wu(await qu(t))}async function Dr(t,e={}){let r=await qu(t);return{document:r?Lt(r.toString("utf8"),e):null,identity:Wu(r)}}async function Fo(t){return(await dn(t))?.config??null}var IE=16*1024;async function qo(t,e){if(!e)return;let r=await fn(t);if(!Vo(r,e))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as sw}from"crypto";import{promises as V}from"fs";import ve from"path";function Wo(t,e){let r=ve.relative(t,e);return r===""||!ve.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ve.sep}`)}function cw(t,e){return T({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function zo(t,e){return T({dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs},{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs})}function lw(t,e){return zo(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function zu(t){let e=await V.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await V.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Br(t){for(let e of t){let r=await V.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!cw(e,r)||await V.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function uw(t,e){let r=ve.resolve(t),i=ve.resolve(e);if(!Wo(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await zu(r)],a=ve.relative(r,i).split(ve.sep).filter(Boolean),o=r;for(let s of a){await Br(n),o=ve.join(o,s);try{await V.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await zu(o);if(!Wo(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Br(n),n}async function dw(t){let e;try{e=await V.open(t,"r"),await e.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await e?.close()}}async function fw(t,e,r={}){let i=ve.dirname(t),n=r.containedRoot?await uw(r.containedRoot,i):null;n||await V.mkdir(i,{recursive:!0});let a=ve.join(i,`.${ve.basename(t)}.${sw()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await V.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([V.lstat(a),V.realpath(a)]);if(await Br(n),!l.isFile()||l.isSymbolicLink()||!zo(s,l)||!Wo(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),c=await o.stat(),!zo(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.beforeCommit?.(),n){await Br(n);let l=await V.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!lw(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await V.link(a,t),await V.unlink(a)):await V.rename(a,t),await dw(i)}catch(l){if(await o?.close(),!n)await V.rm(a,{force:!0});else try{await Br(n),await V.rm(a,{force:!0})}catch{}throw l}}async function ie(t,e,r={}){await fw(t,e,r)}async function ge(t,e,r={}){await ie(t,JSON.stringify(e,null,2)+`
|
|
170
|
-
`,r)}import{existsSync as Ju,promises as je}from"fs";import A from"path";import pw from"os";var pn=".comet/config.yaml",hw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Jo(t){try{return await je.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function mw(t){try{let e=await je.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Ft(t,e){let r=A.relative(t,e);return r===""||!A.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${A.sep}`)}async function Vt(t){let e=[],r=t;for(;!await Jo(r);){let n=A.dirname(r);if(n===r)break;e.push(A.basename(r)),r=n}let i=await je.realpath(r);return A.resolve(i,...e.reverse())}async function Go(t){try{return(await je.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Uo(t){let e=A.resolve(t);try{(await je.stat(e)).isDirectory()||(e=A.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let r=e,i=A.resolve(pw.homedir());for(;;){if(!(e===i&&r!==i)){let o=A.join(e,...pn.split("/")),s=e===r||await mw(o);if(await Jo(o)&&s)return e}if(await Jo(A.join(e,".git")))return e;let a=A.dirname(e);if(a===e)return r;e=a}}function Ko(t){return wt(t)}async function vw(t,e){let r=Ko(e),i=A.resolve(t,...r.split("/")),n=await je.realpath(t),a=await Vt(i);if(!Ft(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function $e(t,e){let r=Ko(e),i=await vw(t,r),n=A.join(i,"comet");if(await Go(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Vt(i),Vt(n)]);if(!Ft(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=A.resolve(t),c=A.join(s,".comet","runtime","native");if(await Go(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([je.realpath(s),Vt(c)]);if(!Ft(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:A.join(t,...pn.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")}}async function Gu(t){await Promise.all([t.specsDir,t.changesDir,t.archiveDir].map(async e=>{await _(t.nativeRoot,e),await je.mkdir(e,{recursive:!0})})),await Promise.all([t.changesRuntimeDir,t.locksDir,t.transactionsDir].map(async e=>{await _(t.projectRoot,e),await je.mkdir(e,{recursive:!0})}))}function Uu(t){if(!hw.test(t))throw new Error(`Invalid Native change name: ${t}`)}function it(t,e){Uu(e);let r=A.join(t.changesRuntimeDir,e);if(!F(t.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function gw(t,e){Uu(e);let r=A.join(t.changesDir,e,"runtime");if(!F(t.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function ne(t,e){let r=it(t,e);if(Ju(r))return r;let i=gw(t,e);return Ju(i)?i:r}function we(t,e){let r=A.resolve(e);if(F(t.runtimeDir,r))return t.runtimeDir;if(F(t.nativeRoot,r))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function F(t,e){return Ft(A.resolve(t),A.resolve(e))}async function _(t,e){let r=A.resolve(t),i=A.resolve(e);if(!Ft(r,i))throw new Error(`Path is outside the Native root: ${e}`);if(await Go(r))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([Vt(r),Vt(i)]);if(!Ft(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return i}var hn=on;function Ku(t="docs",e="en"){return sn(t,e)}async function W(t){let e=(await dn(t))?.config??null;return e?.native?e:null}async function mn(t){let e=await W(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Mr(t,e,r={}){let i=await Dr(t,{allowPartialProject:!0}),n=$r(i.document?.value??{},e),a=ww.join(t,...pn.split("/"));await ie(a,jr(n,e.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:t,beforeCommit:async()=>{await r.beforeCommit?.(),await qo(t,i.identity)}})}var qt="comet.native.v4",Vr="comet.native.local-execution.v4";var Yu=["multi-session","single-session"];function Yo(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}function Nt(t,e,r){return t.language==="zh-CN"?r:e}function yw(t,e){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e&&t.phase==="shape"&&t.status==="active")return{required:!0,message:Nt(t,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Nt(t,"Reply A or B","回复 A 或 B"),agentInstruction:Nt(t,"Relay the two coordination choices and wait for the user decision. Do not treat a generic confirmation as a mode selection or run --confirmed without --coordination-mode.","转述这两个推进方式并等待用户选择。不要把普通“确认”视为已选择推进方式,也不要在没有 --coordination-mode 时运行 --confirmed。")};if(t.phase==="verify"&&t.status==="active"&&t.loop.stage==="verify-ready")return r(Nt(t,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(t.phase==="verify"&&t.status==="active"&&t.loop.next_action==="await-verifier-result")return r(Nt(t,"Wait only while the dispatched Verifier task is still active. If it did not start, ended without a response, or is no longer available, immediately submit the matching verifier-unavailable or verifier-execution-error input. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、结束后没有返回结果或已经丢失,立即提交匹配的 verifier-unavailable 或 verifier-execution-error 输入。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(t.status==="blocked"&&t.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return t.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(t.phase==="verify"&&t.status==="await-user"&&t.verification?.assurance==="semantic-verification-unavailable")return t.language==="zh-CN"?{required:!0,message:"由于独立验收服务暂时不可用,目前只能完成自动检查。你可以选择接受当前检查结果,或者等验收服务恢复后再重试。",suggestedReply:null,agentInstruction:"向用户转述 message,并请用户明确选择是否接受只有自动检查的结果。不要把“继续”当作默认接受。"}:{required:!0,message:"Because independent verification is temporarily unavailable, only the automatic checks could be completed. You can accept the current check results or wait and retry when verification is available.",suggestedReply:null,agentInstruction:"Relay message and ask the user to explicitly choose whether to accept automatic checks only. Do not treat “Continue” as implicit acceptance."};if(t.phase==="verify"&&t.status==="await-user"&&t.loop.next_action==="resolve-verifier-blocker")return t.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(t.phase==="verify"&&t.status==="await-user"&&t.loop.next_action==="await-user"){let n=(t.loop.stop_reason??(t.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return t.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return r(Nt(t,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function Qo(t){return["comet","native","next",t.change,"--summary","<summary>",t.flag,"--expected-state-version",String(t.stateVersion),"--expected-action",t.action]}function vn(t,e){return{name:t,flag:e,valueKind:"text",required:!0,template:null}}function Xu(t,e){return{name:t,flag:e,valueKind:"confirmation",required:!0,template:null}}function Nw(t,e,r){return{name:t,flag:e,valueKind:"choice",required:!0,template:null,choices:[...r]}}function bw(t){return t?.coordinationChoiceRequired===!0||t?.schema==="comet.native.children.v2"&&t.children.length>=2}function kw(t){return["comet","native","next",t.change,"--summary","<summary>",...t.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--confirmed","--expected-state-version",String(t.stateVersion),"--expected-action","confirm-shape"]}function Fr(t){return{name:t.name,stateVersion:t.stateVersion,expectedAction:t.expectedAction,commandArgs:Qo({change:t.change,stateVersion:t.stateVersion,action:t.expectedAction,flag:t.flag}),requiredInputs:["summary",t.confirmationInput],inputOptions:[vn("summary","--summary"),Xu(t.name,t.flag)]}}function Xo(t){return[Fr({name:"revise-implementation",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Fr({name:"revise-requirements",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Qu(t,e){let r=bw(e)&&t.coordination_mode===void 0,i={schema:"comet.native.continuation.v2",skill:"comet-native",change:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,inputOptions:[],userCommunication:yw(t,r)},n=a=>({kind:a,candidateId:t.builder_handoff?.candidate_id??null,iteration:t.loop.iteration,attempt:t.loop.attempt});if(t.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(t.status==="await-user")return t.phase==="verify"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vn("summary","--summary")],commandAlternatives:[Fr({name:"accept-result",change:t.name,stateVersion:t.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Xo({change:t.name,stateVersion:t.state_version})],runnerAction:n("none")}:t.phase==="verify"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:Qo({change:t.name,stateVersion:t.state_version,action:"confirm-verifier-unavailable",flag:"--confirmed"}),requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:n("none")}:t.phase==="verify"&&t.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vn("summary","--summary")],commandAlternatives:[Fr({name:"resolve-verifier-blocker",change:t.name,stateVersion:t.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Xo({change:t.name,stateVersion:t.state_version})],runnerAction:n("none")}:t.phase==="verify"&&t.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vn("summary","--summary")],commandAlternatives:Xo({change:t.name,stateVersion:t.state_version}),runnerAction:n("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:n("none")};if(t.status==="blocked"){let a=t.blockers.some(({resolution_action:o})=>o==="retry-verifier");return{...i,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?Qo({change:t.name,stateVersion:t.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:a?["summary"]:["repair-runtime"],inputOptions:a?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:n(a?"retry-verifier":"none")}}if(t.phase==="shape")return{...i,disposition:r?"await-user":"continue",action:"confirm-shape",commandArgs:kw({change:t.name,stateVersion:t.state_version,coordinationRequired:r}),requiredInputs:["summary",...r?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...r?[Nw("coordination-mode","--coordination-mode",Yu)]:[],Xu("confirmed","--confirmed")],runnerAction:n("none")};if(t.phase==="build"){if(e){if(!e.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:n("none")};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(e.allDone)return{...i,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")};let a=e.children.some(({status:s})=>s==="blocked"||s==="needs-reverify"),o=e.children.some(({status:s})=>s==="ready"||s==="active");return{...i,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...i,disposition:"continue",action:t.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")}}if(t.phase==="verify"){let a=t.loop.next_action==="await-verifier-result",o=!!t.children_contract_hash,s={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...i,userCommunication:!a&&o?{...i.userCommunication,agentInstruction:`${i.userCommunication.agentInstruction} ${Nt(t,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:i.userCommunication,disposition:"continue",action:a?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:[a?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:a?[{kind:"verifier-response",response:{kind:"request-checks",iteration:t.loop.iteration,attempt:t.loop.attempt,checks:[s]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:t.loop.iteration,attempt:t.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:o?[s]:[]}}],runnerAction:n(a?"await-verifier":"dispatch-verifier")}}return t.phase==="archive"&&t.status==="active"&&t.loop.stage==="archive-ready"&&!t.archived?{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],commandAlternatives:[Fr({name:"revise-requirements",change:t.name,stateVersion:t.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}import{promises as ut}from"node:fs";import ei from"node:path";import{execFileSync as Sw}from"child_process";import qr from"path";function nt(t,e){return Sw("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Ew(t,e){let r=qr.normalize(t),i=qr.normalize(e);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function K(t){try{let e=qr.resolve(nt(t,["rev-parse","--show-toplevel"])),i=nt(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?qr.resolve(i.slice(9)):e,a=null;try{a=nt(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Ew(e,n),currentWorktreeRoot:e,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function gn(t){try{nt(t,["rev-parse","--is-inside-work-tree"]);let e=nt(t,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of e)n.startsWith("worktree ")?(i&&r.push(i),i={root:qr.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function Wt(t){return gn(t).map(e=>e.root)}function zt(t,e){try{return nt(t,["check-ref-format","--branch",e]),nt(t,["show-ref","--verify",`refs/heads/${e}`]),!0}catch{return!1}}function Wr(t,e){try{let r=nt(t,["rev-parse","--verify",`${e}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}import{createHash as Rw}from"node:crypto";import{promises as ye}from"node:fs";import ae from"node:path";import{TextDecoder as Aw}from"node:util";var Cw=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),xw=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Pw(t){return t.toLowerCase().startsWith(".env")}function zr(t){let r=t.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Pw(i))?"environment-file":r.some(i=>xw.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Cw.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var yn=1024*1024;function Zo(t,e){let r=ae.relative(t,e);return r===""||!ae.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ae.sep}`)}function _w(t){let e=ae.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ae.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let r=t.toLowerCase(),i=zr(t);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${t}`);return t}function Iw(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function Tw(t,e){return T({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function wn(t,e){let r={...t,birthtime:t.birthtimeMs},i={...e,birthtime:e.birthtimeMs};return Ce(r,i)?T(r,i):T(r,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Zu(t){let e=await ye.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await ye.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function jw(t,e){let r=ae.resolve(t),i=ae.resolve(e);if(!Zo(r,i))throw new Error("Native artifact path is outside its root");let n=[await Zu(r)],a=r;for(let o of ae.relative(r,i).split(ae.sep).filter(Boolean)){a=ae.join(a,o);let s=await Zu(a);if(!Zo(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function ed(t){for(let e of t){let r=await ye.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!Tw(e,r)||await ye.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function oe(t){let e=_w(t.ref),r=t.maxBytes===null?null:Iw(t.maxBytes??yn),i=ae.resolve(t.root,...e.split("/")),n=await jw(t.root,ae.dirname(i));await t.hooks?.afterParentChainCaptured?.();let a=await ye.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);let o=await ye.realpath(i);if(!Zo(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await ye.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),ye.lstat(i),ye.realpath(i)]);if(await ed(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!wn(a,c)||!wn(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?h.length:r+1-f,S=await s.read(h,0,Math.min(h.length,k),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);d.push(Buffer.from(h.subarray(0,S.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([s.stat(),ye.lstat(i),ye.realpath(i)]);if(await ed(n),!p.isFile()||p.isSymbolicLink()||m!==o||!wn(c,v)||!wn(c,p))throw new Error(`Native artifact changed while reading: ${e}`);let y=Buffer.concat(d,f),N;try{N=new Aw("utf-8",{fatal:!0}).decode(y)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:f,hash:t.includeHash===!1?null:Rw("sha256").update(y).digest("hex"),text:N}}finally{await s.close()}}var Rb=Zt(Ht(),1);import{execFileSync as $w}from"node:child_process";var Ow=3e4,Hw=8*1024*1024,es=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function Dw(t,e){try{return $w("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Ow,maxBuffer:Hw,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new es(t,e,i)}}function xe(t,e){return Dw(t,e).trim()}function ts(t){return xe(t,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function rs(t,e){xe(t,["check-ref-format","--branch",e])}import{createHash as Lw}from"crypto";function Ne(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function Bw(t,e){e.has(t)&&Ne("cyclic structures are not supported"),e.add(t);try{let r=Object.keys(t);for(let i=0;i<t.length;i+=1)Object.prototype.hasOwnProperty.call(t,i)||Ne("sparse arrays are not supported");return(r.length!==t.length||r.some((i,n)=>i!==String(n)))&&Ne("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&Ne("symbol properties are not supported"),`[${t.map(i=>is(i,e)).join(",")}]`}finally{e.delete(t)}}function Mw(t,e){let r=Object.getPrototypeOf(t);r!==Object.prototype&&r!==null&&Ne("only plain objects are supported"),e.has(t)&&Ne("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&Ne("symbol properties are not supported"),e.add(t);try{let i=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&Ne("accessor properties are not supported"),`${JSON.stringify(o)}:${is(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function is(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||Ne("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?Bw(t,e):Mw(t,e);case"bigint":case"function":case"symbol":case"undefined":return Ne(`${typeof t} values are not supported`)}return Ne("unsupported value type")}function ns(t){return is(t,new Set)}function se(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return Lw("sha256").update(`${t}
|
|
171
|
-
${ns(e)}`).digest("hex")}var Nn=Zt(Ht(),1);import{promises as Vw}from"node:fs";var Fw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ww=/^A[1-9][0-9]*$/u,zw=/^[a-f0-9]{64}$/u,Jw=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]);function z(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function J(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function L(t,e,r){if(typeof t!="string"||!r?.empty&&t.length===0)throw new Error(`${e} must be ${r?.empty?"a string":"a non-empty string"}`);return t}function as(t,e){return t===null?null:L(t,e)}function Gw(t,e){let r=L(t,e);if(!zw.test(r))throw new Error(`${e} must be a SHA-256 hash`);return r}function Jt(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function j(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function Uw(t,e){return t===null?null:j(t,e,Number.MIN_SAFE_INTEGER)}function O(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function Pe(t,e,r){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((i,n)=>r(i,n))}function bn(t,e){return Pe(t,e,(r,i)=>L(r,`${e}[${i}]`))}function bt(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function Gt(t,e){let r=L(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO date or timestamp`);return r}function os(t,e,r=!1){let i=L(t,e);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return i}function ce(t,e){let r=z(t,e);return J(r,new Set(["text","truncated"]),e),{text:L(r.text,`${e}.text`,{empty:!0}),truncated:Jt(r.truncated,`${e}.truncated`)}}function Kw(t,e){let r=`Native spec_changes[${e}]`,i=z(t,r);J(i,new Set(["capability","operation","source"]),r);let n=L(i.capability,`${r}.capability`);if(!qw.test(n))throw new Error(`${r}.capability is invalid`);let a=O(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:os(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function Yw(t){let e="Native workspace",r=z(t,e);J(r,new Set(["isolation","change_branch","target_branch","finish"]),e);let i=O(r.isolation,["current","branch","worktree"],`${e}.isolation`),n=as(r.change_branch,`${e}.change_branch`),a=as(r.target_branch,`${e}.target_branch`),o=r.finish===null?null:O(r.finish,["merge","push","pull-request","keep"],`${e}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function Xw(t){let e="Native loop",r=z(t,e);J(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),e);let i=bn(r.previous_unresolved_ids,`${e}.previous_unresolved_ids`);bt(i,`${e}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:O(r.stop_reason,["budget","stalled"],`${e}.stop_reason`);return{stage:O(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:j(r.goal_cycle,`${e}.goal_cycle`,1),iteration:j(r.iteration,`${e}.iteration`),attempt:j(r.attempt,`${e}.attempt`),retry_epoch:j(r.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:j(r.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:j(r.no_progress_count,`${e}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:j(r.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:i,next_action:as(r.next_action,`${e}.next_action`)}}function Qw(t,e){let r=`Native acceptance[${e}]`,i=z(t,r);J(i,new Set(["id","source","text","result","reason"]),r);let n=L(i.id,`${r}.id`);if(!Ww.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:os(i.source,`${r}.source`),text:L(i.text,`${r}.text`),result:O(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ce(i.reason,`${r}.reason`)}}function Zw(t,e){let r=`Native builder_handoff.checks[${e}]`,i=z(t,r);return J(i,new Set(["name","result","note"]),r),{name:ce(i.name,`${r}.name`),result:O(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ce(i.note,`${r}.note`)}}function ey(t){let e="Native builder_handoff",r=z(t,e);J(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),e);let i=bn(r.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);bt(i,`${e}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:z(r.review,`${e}.review`);return n&&J(n,new Set(["status","summary","reviewer_execution_ref"]),`${e}.review`),{candidate_id:L(r.candidate_id,`${e}.candidate_id`),identity_provider:L(r.identity_provider,`${e}.identity_provider`),builder_execution_ref:L(r.builder_execution_ref,`${e}.builder_execution_ref`),iteration:j(r.iteration,`${e}.iteration`,1),summary:ce(r.summary,`${e}.summary`),addressed_acceptance_ids:i,checks:Pe(r.checks,`${e}.checks`,Zw),checks_truncated:Jt(r.checks_truncated,`${e}.checks_truncated`),known_limits:Pe(r.known_limits,`${e}.known_limits`,(a,o)=>ce(a,`${e}.known_limits[${o}]`)),known_limits_truncated:Jt(r.known_limits_truncated,`${e}.known_limits_truncated`),review:n?{status:O(n.status,["passed"],`${e}.review.status`),summary:ce(n.summary,`${e}.review.summary`),reviewer_execution_ref:L(n.reviewer_execution_ref,`${e}.review.reviewer_execution_ref`)}:null,submitted_at:Gt(r.submitted_at,`${e}.submitted_at`)}}function ty(t,e){let r=`Native blockers[${e}]`,i=z(t,r);J(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=bn(i.acceptance_ids,`${r}.acceptance_ids`);return bt(n,`${r}.acceptance_ids`),{owner:O(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ce(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:O(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function ry(t,e){let r=`Native verification.checks[${e}]`,i=z(t,r);return J(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:L(i.id,`${r}.id`),name:ce(i.name,`${r}.name`),argv_display:Pe(i.argv_display,`${r}.argv_display`,(n,a)=>ce(n,`${r}.argv_display[${a}]`)),argv_truncated:Jt(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:os(i.cwd_ref,`${r}.cwd_ref`,!0),status:O(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Uw(i.exit_code,`${r}.exit_code`),duration_ms:j(i.duration_ms,`${r}.duration_ms`)}}function iy(t){let e="Native verification",r=z(t,e);J(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let i=Pe(r.checks,`${e}.checks`,ry);bt(i.map(a=>a.id),`${e}.checks IDs`);let n=L(r.identity_provider,`${e}.identity_provider`);return{candidate_id:L(r.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:L(r.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:j(r.iteration,`${e}.iteration`,1),attempt:j(r.attempt,`${e}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":O(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:O(r.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:i,summary:ce(r.summary,`${e}.summary`),risks:Pe(r.risks,`${e}.risks`,(a,o)=>ce(a,`${e}.risks[${o}]`)),risks_truncated:Jt(r.risks_truncated,`${e}.risks_truncated`),completed_at:Gt(r.completed_at,`${e}.completed_at`)}}function ny(t,e){let r=`Native history[${e}]`,i=z(t,r);J(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=bn(i.unresolved_ids,`${r}.unresolved_ids`);return bt(n,`${r}.unresolved_ids`),{goal_cycle:j(i.goal_cycle,`${r}.goal_cycle`,1),iteration:j(i.iteration,`${r}.iteration`),attempt:j(i.attempt,`${r}.attempt`),outcome:O(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ce(i.summary,`${r}.summary`),completed_at:Gt(i.completed_at,`${r}.completed_at`)}}function ay(t){let e="Native history_overflow.outcome_counts",r=z(t,e),i=["pass","fail","blocked","execution-error","recovery"];return J(r,new Set(i),e),{pass:j(r.pass,`${e}.pass`),fail:j(r.fail,`${e}.fail`),blocked:j(r.blocked,`${e}.blocked`),"execution-error":j(r["execution-error"],`${e}.execution-error`),recovery:j(r.recovery,`${e}.recovery`)}}function oy(t){let e="Native history_overflow",r=z(t,e);J(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let i=j(r.dropped_entries,`${e}.dropped_entries`),n=r.first_dropped_at===null?null:Gt(r.first_dropped_at,`${e}.first_dropped_at`),a=r.last_dropped_at===null?null:Gt(r.last_dropped_at,`${e}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=ay(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function sy(t){let e=new Set(t.acceptance.map(r=>r.id));for(let r of t.loop.previous_unresolved_ids)if(!e.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of t.blockers)for(let i of r.acceptance_ids)if(!e.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(t.builder_handoff){if(!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.builder_handoff.review?.reviewer_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,n=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function cy(t){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let r=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(r!==null&&t.loop.stage!==r)throw new Error(`Native status ${t.status} requires loop stage ${r}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function Ut(t){let e=z(t,"Native portable state");if(J(e,Jw,"Native portable state"),e.schema!==qt)throw new Error(`Native portable state schema must be ${qt}`);let r=L(e.name,"Native state name");if(!Fw.test(r))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Pe(e.spec_changes,"Native spec_changes",Kw);bt(i.map(s=>s.capability),"Native spec change capabilities");let n=Pe(e.acceptance,"Native acceptance",Qw);bt(n.map(s=>s.id),"Native acceptance IDs");let a=Pe(e.history,"Native history",ny);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:qt,name:r,language:O(e.language,["en","zh-CN"],"Native state language"),phase:O(e.phase,["shape","build","verify","archive"],"Native state phase"),status:O(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:j(e.state_version,"Native state_version",1),brief:"brief.md",...e.children_contract_hash===void 0?{}:{children_contract_hash:Gw(e.children_contract_hash,"Native children contract hash")},...e.coordination_mode===void 0?{}:{coordination_mode:O(e.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:Yw(e.workspace),loop:Xw(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:ey(e.builder_handoff),blockers:Pe(e.blockers,"Native blockers",ty),verification:e.verification===null?null:iy(e.verification),history:a,history_overflow:oy(e.history_overflow),verification_result:O(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:O(e.verification_report,["verification.md"],"Native verification_report"),archived:Jt(e.archived,"Native archived"),created_at:Gt(e.created_at,"Native created_at")};return sy(o),cy(o),o}function rd(t){let e=t.createdAt instanceof Date?t.createdAt.toISOString():t.createdAt??new Date().toISOString();return Ut({schema:qt,name:t.name,language:t.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:t.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:t.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:Yo(),verification_result:"pending",verification_report:null,archived:!1,created_at:e})}function ly(t,e){let r=(0,Nn.parseDocument)(t,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${e} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function ss(t){let e=await Vw.readFile(t,"utf8");return Ut(ly(e,"Native portable state"))}async function id(t,e,r={}){let i=Ut(e);await ie(t,(0,Nn.stringify)(i),r)}import{promises as wb}from"fs";import yb from"path";import{AsyncLocalStorage as uy}from"async_hooks";import{randomUUID as od}from"crypto";import{promises as le}from"fs";import sd from"os";import B from"path";var nd=16*1024,cd=".coordinator",dy=5e3,ad=new uy,kn=new Map;function fy(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function py(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let r=t;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: ${e}`);return r}function ld(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function cs(t,e){let r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return Ce(r,i)?T(r,i):T(r,i)&&t.size===e.size}function ls(t,e){return cs(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function Oe(t){let e,r;try{let i=await Bt(t,nd,{bigint:!0,label:"Native lock"});e=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof me?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${nd} bytes: ${t}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:i}):new Error(`Native lock changed while reading: ${t}`,{cause:i}):i}return{file:t,owner:py(JSON.parse(e.toString("utf8")),t),identity:ld(r)}}async function hy(t){return(await Oe(t))?.owner??null}function ud(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==sd.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=Ny(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function my(t,e){try{await le.lstat(e);return}catch(r){if(r.code!=="ENOENT")throw r}try{await le.rename(t,e)}catch(r){if(r.code!=="ENOENT")throw r}}async function us(t,e){let r=await Oe(t.file);if(!r)return"missing";if(r.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!ls(r.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await le.mkdir(e,{recursive:!0});let i=B.join(e,`${B.basename(t.file)}.${t.owner.id}.${od()}.removed`);try{await le.rename(t.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Oe(i);if(!n||n.owner.id!==t.owner.id||!cs(n.identity,t.identity))throw await my(i,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await le.rm(i,{force:!0}),"removed"}function dd(t){return{id:od(),pid:process.pid,hostname:sd.hostname(),createdAt:new Date().toISOString(),operation:t}}async function fd(t,e){let r;try{r=await le.open(t,"wx")}catch(i){if(i.code==="EEXIST"){let n=await hy(t);throw new Error(`Native lock is already held: ${t}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:i})}throw i}try{return await r.writeFile(JSON.stringify(e,null,2)+`
|
|
172
|
-
`,"utf8"),await r.sync(),ld(await r.stat({bigint:!0}))}finally{await r.close()}}async function vy(t,e){let r=await _(t.runtimeDir,t.locksDir);await le.mkdir(r,{recursive:!0});let i=await _(t.runtimeDir,B.join(r,cd));await le.mkdir(i,{recursive:!0});let n=dd(e),a=B.join(i,`.${n.id}.tmp`),o=B.join(i,`${n.id}.claim`);try{let s=await fd(a,n);await le.rename(a,o);let c=await Oe(o);if(!c||!cs(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await le.rm(a,{force:!0})}}async function gy(t){let e=B.dirname(t.file),r=!1,i=B.basename(t.file);for(let n of await le.readdir(e,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=B.join(e,n.name);if(B.resolve(a)!==B.resolve(t.file))try{let o=await Oe(a),s=ud(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await us(o,e);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function pd(t){let e=await Oe(t.file);if(e){if(e.owner.id!==t.owner.id||!ls(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await us(e,B.dirname(t.file))}}async function wy(t,e){let r=Date.now()+dy;for(;;){let i=await vy(t,e);if(!await gy(i))return i;if(await pd(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function yy(t){let e=kn.get(t)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=e.then(()=>i);return kn.set(t,n),await e,()=>{r(),kn.get(t)===n&&kn.delete(t)}}async function ds(t,e,r){let i=B.resolve(t.locksDir),n=ad.getStore();if(n?.has(i))return r();let a=await yy(i);try{let o=await wy(t,e),s=new Map(n??[]);return s.set(i,o),await ad.run(s,async()=>{try{return await r()}finally{await pd(o)}})}finally{a()}}async function hd(t,e,r){let i=[...new Map(t.map(a=>[B.resolve(a.locksDir),a])).values()].sort((a,o)=>B.resolve(a.locksDir).localeCompare(B.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?ds(o,e,()=>n(a+1)):r()};return n(0)}async function Sn(t,e,r){return ds(t,`acquire ${e}`,async()=>{let i=await _(t.runtimeDir,t.locksDir);await le.mkdir(i,{recursive:!0});let n=await _(t.runtimeDir,B.join(i,fy(e))),a=dd(r),o=await fd(n,a);return{file:n,nativeRoot:t.runtimeDir,locksDir:i,owner:a,identity:o}})}async function En(t){await Oe(t.file)&&await ds({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${B.basename(t.file)}`,async()=>{let e=await Oe(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!ls(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let r=B.join(t.locksDir,cd);await us(e,r)})}function Ny(t){try{return process.kill(t,0),!0}catch(e){let r=e.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function md(t){return ud(await Oe(t))}import XN from"node:path";var bs=Zt(Ht(),1);import{promises as $n}from"fs";import Y from"path";var fs={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:"验证预期"}},by={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:"结论"}},ky={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:"结论"}},Sy=new Map,vd=new Map;for(let t of Object.keys(fs)){for(let[e,r]of Object.entries(fs[t]))Sy.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(by[t]))vd.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(ky[t]))vd.set(r.toLocaleLowerCase("en-US"),e)}function Ey(t,e){return fs[t][e]}function Jr(t){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Ey(t,r)}
|
|
169
|
+
`)}function Mg(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||et.posix.isAbsolute(r)||et.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 Nt(e){let t=Mg(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Ou(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 on(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||et.posix.isAbsolute(i)||et.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 je(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Hu(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 sn(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>nn)throw new Error(`${t} exceeds ${nn} 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>an)throw new Error(`${t} contains more than ${an} wildcard tokens`);return e}function ju(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=>sn(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Lo(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 Fg(e){if(e===void 0)return{...Z,include:[...Z.include],exclude:[...Z.exclude]};let t=je(e,"native.snapshot");return{include:ju(t.include,"native.snapshot.include",Z.include),exclude:ju(t.exclude,"native.snapshot.exclude",Z.exclude),max_files:Lo(t.max_files,Z.max_files,"native.snapshot.max_files"),max_total_bytes:Lo(t.max_total_bytes,Z.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Lo(t.max_duration_ms,Z.max_duration_ms,"native.snapshot.max_duration_ms")}}function qg(e){if(e===void 0)return;let t=je(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=je(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:Nt(i),toArtifactRoot:Nt(n),stage:a,...o?{cleanup:o}:{}}}function Wg(e){if(e===void 0)return;let t=je(e,"native.finish");if(t.pull_request===void 0)return{};let r=je(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(et.posix.isAbsolute(i[0])||et.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??Hg;if(!Number.isSafeInteger(n)||n<1||n>Tu)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Tu}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function zg(e,t={}){let r=je(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??Bo;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=qg(r.pending_root_move),c=Wg(r.finish);return{artifact_root:Nt(i),language:Hu(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Fg(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function Jg(e){let t=je(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:Ou(t.artifact_layout),language:Hu(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function Gg(e){let r=je(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)=>on(i,`hook.allow_paths[${n}]`)))]}}function Ug(e){if(e===void 0)return{...jr};let t=je(e,"memory"),r=t.learning??jr.learning,i=t.retrieval??jr.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 Mo(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Kg(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")||et.posix.isAbsolute(r)||et.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>_u)throw new Error(`${t} exceeds ${_u} 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>Iu)throw new Error(`${t} contains more than ${Iu} wildcard tokens`);return r}function Yg(e){let r=Mo(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)=>Kg(i,`knowledge.local.include[${n}]`)))]}}function Xg(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 Qg(e){let t=Mo(e,"knowledge.remote"),r=Xg(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 Zg(e){if(e===void 0)return{...Vo};let t=Mo(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:Yg(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:Qg(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 ew(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function tw(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 Bt(e,t={}){let r=(0,$r.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=ew(n.ambient_resume),o=n.hook===void 0?void 0:Gg(n.hook),s=Ug(n.memory),c=Zg(n.knowledge),l=n.native===void 0?void 0:zg(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:Jg(n.classic),d=tw(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 Du(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 Lu(e){let t=e.knowledge??{...Vo};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...jr},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:Du(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 Q(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Dr(e,t){let r=Lu(t),i=Bt((0,$r.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={...Q(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=Q(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=Q(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...Q(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...Q(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=Q(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=Q(a.finish);o.finish={...s,pull_request:{...Q(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={...Q(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=Q(a.pending_root_move),c=Du(i.native.pending_root_move),l=Q(s.cleanup),u=Q(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={...Q(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 cn(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...jr},knowledge:{...Vo},native:{artifact_root:Nt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Bo,snapshot:{...Z,include:[...Z.include],exclude:[...Z.exclude]}}}}import{createHash as iw}from"crypto";import{promises as dn}from"fs";import rt from"path";import{constants as ln,promises as bt}from"fs";function tt(e){return e!==0&&e!==0n&&e!=="0"}function Ce(e,t){return tt(e.dev)&&tt(t.dev)&&tt(e.ino)&&tt(t.ino)}function T(e,t){let r=tt(e.dev)&&tt(t.dev);if(r&&e.dev!==t.dev)return!1;let i=tt(e.ino)&&tt(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var me=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function Fo(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Bu(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Lr(e){return{dev:e.dev,ino:e.ino,birthtime:Fo(e)}}function un(e,t){let r=Lr(e),i=Lr(t);return Ce(r,i)?T(r,i):T(r,i)&&Fo(e)===Fo(t)&&Bu(e)===Bu(t)&&e.size===t.size}async function Vt(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 bt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new me("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new me("too-large",`${i} exceeds ${t} bytes`);let o=await bt.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Lr(a)});let s=process.platform==="win32"?ln.O_RDONLY:ln.O_RDONLY|ln.O_NOFOLLOW|ln.O_NONBLOCK,c;try{c=await bt.open(e,s)}catch(l){throw l.code==="ELOOP"?new me("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),bt.lstat(e,{bigint:n}),bt.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!un(a,l)||!un(a,u))throw new me("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Lr(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-p,{bytesRead:k}=await c.read(v,0,Math.min(v.length,N),null);if(k===0)break;if(p+=k,p>t)throw new me("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[h,m,y]=await Promise.all([c.stat({bigint:n}),bt.lstat(e,{bigint:n}),bt.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||y!==o||!un(a,h)||!un(a,m))throw new me("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:y,identity:Lr(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:y}}finally{await c.close()}}function rw(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function qo(e,t){let r=rt.relative(e,t);return r===""||!rt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${rt.sep}`)}async function Vu(e,t){let r=rt.resolve(e),i=await dn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return dn.realpath(r)}async function Mu(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=rt.join(n,r[a]);let o;try{o=await dn.lstat(n)}catch(u){if(rw(u))return{exists:!1,kind:"missing"};throw u}let s=rt.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 dn.realpath(n);if(!qo(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 Mt(e,t,r){let i=on(t,r.label),n=rt.resolve(e),a=await Vu(n,r.label),o=i.split("/"),s=rt.resolve(n,...o);if(!qo(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Mu(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function it(e,t,r,i){let n=await Mt(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 Vu(n.projectRoot,i.label);return Vt(n.target,r,{...i,verify:async(o,s)=>{if(!qo(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Mu(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Br=".comet/config.yaml";function Wo(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function nw(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function fn(e,t={}){return(await Vr(e,t)).document}async function Fu(e){try{return(await it(e,Br,Or,{label:Br})).bytes}catch(t){if(nw(t))return null;throw t}}function qu(e){return e?{exists:!0,sha256:iw("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function hn(e){return qu(await Fu(e))}async function Vr(e,t={}){let r=await Fu(e);return{document:r?Bt(r.toString("utf8"),t):null,identity:qu(r)}}async function zo(e){return(await fn(e))?.config??null}var OE=16*1024;async function Jo(e,t){if(!t)return;let r=await hn(e);if(!Wo(r,t))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as cw}from"crypto";import{promises as L}from"fs";import ve from"path";function pn(e,t){let r=ve.relative(e,t);return r===""||!ve.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ve.sep}`)}function lw(e,t){return T({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function mn(e,t){return T({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function uw(e,t){return mn(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Wu(e){let t=await L.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 L.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ft(e){for(let t of e){let r=await L.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!lw(t,r)||await L.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function dw(e,t,r){let[i,n]=await Promise.all([L.lstat(e),L.realpath(e),r?Ft(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!mn(i,t)||r&&!pn(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function fw(e,t){let r=ve.resolve(e),i=ve.resolve(t);if(!pn(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Wu(r)],a=ve.relative(r,i).split(ve.sep).filter(Boolean),o=r;for(let s of a){await Ft(n),o=ve.join(o,s);try{await L.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Wu(o);if(!pn(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ft(n),n}async function hw(e){let t;try{t=await L.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 pw(e,t,r={}){let i=ve.dirname(e),n=r.containedRoot?await fw(r.containedRoot,i):null;n||await L.mkdir(i,{recursive:!0});let a=ve.join(i,`.${ve.basename(e)}.${cw()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await L.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([L.lstat(a),L.realpath(a)]);if(await Ft(n),!l.isFile()||l.isSymbolicLink()||!mn(s,l)||!pn(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(),!mn(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 dw(a,c,n),await r.beforeCommit?.(),n){await Ft(n);let l=await L.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!uw(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await L.link(a,e),await L.unlink(a)):await L.rename(a,e),await hw(i)}catch(l){if(await o?.close(),!n)await L.rm(a,{force:!0});else try{await Ft(n),await L.rm(a,{force:!0})}catch{}throw l}}async function ne(e,t,r={}){await pw(e,t,r)}async function ge(e,t,r={}){await ne(e,JSON.stringify(t,null,2)+`
|
|
170
|
+
`,r)}import{existsSync as zu,promises as $e}from"fs";import A from"path";import mw from"os";var vn=".comet/config.yaml",vw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Go(e){try{return await $e.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function gw(e){try{let t=await $e.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Wt(e,t){let r=A.relative(e,t);return r===""||!A.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${A.sep}`)}async function qt(e){let t=[],r=e;for(;!await Go(r);){let n=A.dirname(r);if(n===r)break;t.push(A.basename(r)),r=n}let i=await $e.realpath(r);return A.resolve(i,...t.reverse())}async function Uo(e){try{return(await $e.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ko(e){let t=A.resolve(e);try{(await $e.stat(t)).isDirectory()||(t=A.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=A.resolve(mw.homedir());for(;;){if(!(t===i&&r!==i)){let o=A.join(t,...vn.split("/")),s=t===r||await gw(o);if(await Go(o)&&s)return t}if(await Go(A.join(t,".git")))return t;let a=A.dirname(t);if(a===t)return r;t=a}}function Yo(e){return Nt(e)}async function ww(e,t){let r=Yo(t),i=A.resolve(e,...r.split("/")),n=await $e.realpath(e),a=await qt(i);if(!Wt(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Oe(e,t){let r=Yo(t),i=await ww(e,r),n=A.join(i,"comet");if(await Uo(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([qt(i),qt(n)]);if(!Wt(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 Uo(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([$e.realpath(s),qt(c)]);if(!Wt(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:A.join(e,...vn.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")}}async function Ju(e){await Promise.all([e.specsDir,e.changesDir,e.archiveDir].map(async t=>{await _(e.nativeRoot,t),await $e.mkdir(t,{recursive:!0})})),await Promise.all([e.changesRuntimeDir,e.locksDir,e.transactionsDir].map(async t=>{await _(e.projectRoot,t),await $e.mkdir(t,{recursive:!0})}))}function Gu(e){if(!vw.test(e))throw new Error(`Invalid Native change name: ${e}`)}function nt(e,t){Gu(t);let r=A.join(e.changesRuntimeDir,t);if(!F(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function yw(e,t){Gu(t);let r=A.join(e.changesDir,t,"runtime");if(!F(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function ae(e,t){let r=nt(e,t);if(zu(r))return r;let i=yw(e,t);return zu(i)?i:r}function we(e,t){let r=A.resolve(t);if(F(e.runtimeDir,r))return e.runtimeDir;if(F(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function F(e,t){return Wt(A.resolve(e),A.resolve(t))}async function _(e,t){let r=A.resolve(e),i=A.resolve(t);if(!Wt(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Uo(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([qt(r),qt(i)]);if(!Wt(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var gn=sn;function Uu(e="docs",t="en"){return cn(e,t)}async function W(e){let t=(await fn(e))?.config??null;return t?.native?t:null}async function wn(e){let t=await W(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Fr(e,t,r={}){let i=await Vr(e,{allowPartialProject:!0}),n=Dr(i.document?.value??{},t),a=Nw.join(e,...vn.split("/"));await ne(a,Hr(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Jo(e,i.identity)}})}var zt="comet.native.v4",qr="comet.native.local-execution.v4";var Ku=["multi-session","single-session"];function Xo(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}function He(e,t,r){return e.language==="zh-CN"?r:t}function bw(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:He(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:He(e,"Reply A or B","回复 A 或 B"),agentInstruction:He(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(He(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return r(He(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return r(He(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function kw(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function Sw(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:He(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:He(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Xu(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Jt(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Ew(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Yu(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function Cw(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function xw(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function at(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Xu({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Jt("summary","--summary"),Ew(e.name,e.flag)]}}function Qo(e){return[at({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),at({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Qu(e,t,r={}){let i=Cw(t)&&e.coordination_mode===void 0,n=bw(e,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[Jt("summary","--summary")],commandAlternatives:[at({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Jt("summary","--summary")],commandAlternatives:[at({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Qo({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Jt("summary","--summary")],commandAlternatives:[at({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),at({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Jt("summary","--summary")],commandAlternatives:[at({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Qo({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Jt("summary","--summary")],commandAlternatives:Qo({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Xu({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:xw({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[Yu("coordination-mode","--coordination-mode",Ku)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.some(({status:l})=>l==="blocked"||l==="needs-reverify"),c=t.children.some(({status:l})=>l==="ready"||l==="active");return{...a,disposition:s&&!c?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:s&&!c?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${He(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?r.archiveBlockers&&r.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Yu("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...Sw(e)],userCommunication:kw(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[at({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import{promises as ft}from"node:fs";import ti from"node:path";import{execFileSync as Pw}from"child_process";import Wr from"path";function ot(e,t){return Pw("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Rw(e,t){let r=Wr.normalize(e),i=Wr.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function K(e){try{let t=Wr.resolve(ot(e,["rev-parse","--show-toplevel"])),i=ot(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?Wr.resolve(i.slice(9)):t,a=null;try{a=ot(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Rw(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function yn(e){try{ot(e,["rev-parse","--is-inside-work-tree"]);let t=ot(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:Wr.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function Gt(e){return yn(e).map(t=>t.root)}function Ut(e,t){try{return ot(e,["check-ref-format","--branch",t]),ot(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function zr(e,t){try{let r=ot(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var Zo={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:"验证预期"}},Aw={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:"结论"}},_w={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:"结论"}},Iw=new Map,Zu=new Map;for(let e of Object.keys(Zo)){for(let[t,r]of Object.entries(Zo[e]))Iw.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Aw[e]))Zu.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(_w[e]))Zu.set(r.toLocaleLowerCase("en-US"),t)}function Tw(e,t){return Zo[e][t]}function Jr(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Tw(e,r)}
|
|
173
171
|
`).join(`
|
|
174
|
-
`)}import{createHash as
|
|
175
|
-
`)}function
|
|
176
|
-
${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function hs(t,e,r){let i=new Set(e),n=[...e];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=t[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function eN(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function Nd(t){let e=hn(t,"Native snapshot pattern"),r=[];for(let i=0;i<e.length;i+=1){let n=e[i];n==="*"&&e[i+1]==="*"?(i+=1,e[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?eN(n):void 0;if(a&&!a())return!1;let o=hs(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=hs(r,c,a),o===null||o.size===0)return!1}return hs(r,o,a)?.has(r.length)??!1}}function tN(t){if(t===void 0)return;let e=[...new Set(t.include.map(n=>hn(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(t.exclude.map(n=>hn(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let i=Zy(e,r);if("hash"in t&&t.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:r,hash:i},includeMatchers:e.map(Nd),excludeMatchers:r.map(Nd),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function ue(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function de(t,e,r){let i=Object.keys(t).find(n=>!e.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Yt(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Re(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Sd(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let r=ms.posix.normalize(t);if(r!==t||ms.posix.isAbsolute(t)||r===".."||r.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function rN(t,e){let r=ue(t,`Native snapshot entry ${e}`);de(r,Wy,`Native snapshot entry ${e}`);let i=Sd(r.path,`Native snapshot entry ${e} path`);if(typeof r.hash!="string"||!An.test(r.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let n={path:i,hash:r.hash,size:Re(r.size,`Native snapshot entry ${e} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!Yy.test(r.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function iN(t,e){let r=ue(t,`Native snapshot omission ${e}`);if(de(r,zy,`Native snapshot omission ${e}`),!Uy.has(r.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!Ky.has(r.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:Sd(r.path,`Native snapshot omission ${e} path`),size:r.size===null?null:Re(r.size,`Native snapshot omission ${e} size`),type:r.type,reason:r.reason}}function nN(t){let e=ue(t,"Native snapshot omission overflow");if(de(e,Jy,"Native snapshot omission overflow"),typeof e.hash!="string"||!An.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:e.hash,count:Yt(e.count,"Native snapshot omission overflow count")}}function Kt(t,e){let r=ue(t,e);if(de(r,Vy,e),typeof r.hash!="string"||!An.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let i=Re(r.recordCount,`${e} recordCount`),n=Re(r.storedRecordCount,`${e} storedRecordCount`),a=Re(r.stdoutBytes,`${e} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function bd(t){let e=ue(t,"Native Git selection evidence");if(de(e,My,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=Kt(e.stageBefore,"Native Git selection stageBefore"),i=Kt(e.combined,"Native Git selection combined"),n=Kt(e.stageAfter,"Native Git selection stageAfter"),a=Kt(e.finalStageBefore,"Native Git selection finalStageBefore"),o=Kt(e.finalCombined,"Native Git selection finalCombined"),s=Kt(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Rn(r,n)||!Rn(n,a)||!Rn(i,o)||!Rn(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function kd(t,e){let r=ue(t,e);if(de(r,qy,e),typeof r.hash!="string"||!An.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${e} flags are invalid`);let i=Re(r.visitedNodeCount,`${e} visitedNodeCount`),n=Re(r.recordCount,`${e} recordCount`),a=Re(r.storedRecordCount,`${e} storedRecordCount`),o=Re(r.encodedBytes,`${e} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function aN(t){let e=ue(t,"Native physical selection evidence");if(de(e,Fy,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=kd(e.before,"Native physical selection before"),i=kd(e.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!Xy(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function Ed(t){let e=ue(t,"Native content snapshot manifest");if(de(e,Oy,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Gy.has(e.origin))throw new Error("Native content snapshot origin is invalid");let r;if(e.capture!==void 0){let g=ue(e.capture,"Native content snapshot capture");if(de(g,Ly,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let P=g.gitSelection===void 0?void 0:bd(g.gitSelection),b=g.physicalSelection===void 0?void 0:aN(g.physicalSelection),I=null;if(g.projection!==void 0){let X=ue(g.projection,"Native content snapshot projection");if(de(X,By,"Native content snapshot projection"),X.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");I={provider:"git",...X.selection===void 0?{}:{selection:bd(X.selection)}}}if(g.provider==="git"){if(b||I)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...P?{gitSelection:P}:{}}}else{if(P)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&I)throw new Error("Native physical-tree capture cannot combine selection and projection");r=I?{provider:"physical-tree",projection:I}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=ue(e.limits,"Native content snapshot limits");de(i,Hy,"Native content snapshot limits");let n={maxFiles:Yt(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Yt(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Yt(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Yt(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Yt(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let g=ue(e.policy,"Native snapshot policy");if(de(g,Dy,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=tN({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(rN),s=e.omitted.map(iN),c=Re(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:nN(e.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>n.maxFileBytes)||o.reduce((g,P)=>g+P.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Ty||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(g=>g.reason==="git-enumeration-limit"),f=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...d,...f])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(g=>g.reason==="physical-enumeration-limit"),y=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...m,...y])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=r?.physicalSelection,k=N?.status==="overflow"||N?.status==="overflow-and-changed",S=N?.status==="changed"||N?.status==="overflow-and-changed";if(k!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:e.origin,...r?{capture:r}:{},createdAt:e.createdAt,complete:e.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Qy(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function oN(t,e){if(!$y.test(e))throw new Error(`Invalid Native change name: ${e}`);return ms.join(ne(t,e),"baseline-manifest.json")}async function Cd(t,e){let r=oN(t,e),i=we(t,r);await _(i,r);try{let n=await yd({root:i,file:r,maxBytes:jy,label:"Native baseline snapshot manifest"});return Ed(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var fN=Zt(Ht(),1);var Ex=4*1024*1024;var pN=null;function hN(t,e){let r=t;for(let i of e)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function xd(t,e){return(...r)=>{let i=pN;if(i===null)return e(...r);let n=hN(`async:${t}`,r),a=i.entries.get(n);if(a)return a.value;let o=e(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var Ax=xd("hookWritePolicy",async t=>(await Fo(t))?.hook??{allow_paths:[]});var kP=256*1024;var OP={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import{createHash as vN}from"node:crypto";import{promises as _n}from"node:fs";import at from"node:path";var Ur=/^[a-f0-9]{64}$/u,Rd=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,gN=16*1024,gs=process.platform;function Id(t,e){let r=at.relative(t,e);return at.isAbsolute(r)||r===".."||r.startsWith(`..${at.sep}`)?null:r.replaceAll("\\","/")||"."}function Td(t){return Array.from(t).some(e=>{let r=e.codePointAt(0)??0;return r<=31||r===127})}function jd(t,e){if(t.length===0||Td(t)||t.includes("\\")||at.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let r=at.posix.normalize(t);if(r!==t||r===".."||r.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return r}function ws(t,e){return vN("sha256").update(`${t}
|
|
177
|
-
|
|
172
|
+
`)}var bs=rr(Dt(),1);import{promises as qn}from"fs";import Y from"path";import{createHash as Hw}from"node:crypto";import{promises as ye}from"node:fs";import oe from"node:path";import{TextDecoder as Dw}from"node:util";var jw=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),$w=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Ow(e){return e.toLowerCase().startsWith(".env")}function Gr(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Ow(i))?"environment-file":r.some(i=>$w.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>jw.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var bn=1024*1024;function es(e,t){let r=oe.relative(e,t);return r===""||!oe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${oe.sep}`)}function Lw(e){let t=oe.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||oe.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Gr(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 Bw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Vw(e,t){return T({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Nn(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ce(r,i)?T(r,i):T(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ed(e){let t=await ye.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ye.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Mw(e,t){let r=oe.resolve(e),i=oe.resolve(t);if(!es(r,i))throw new Error("Native artifact path is outside its root");let n=[await ed(r)],a=r;for(let o of oe.relative(r,i).split(oe.sep).filter(Boolean)){a=oe.join(a,o);let s=await ed(a);if(!es(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function td(e){for(let t of e){let r=await ye.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Vw(t,r)||await ye.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function se(e){let t=Lw(e.ref),r=e.maxBytes===null?null:Bw(e.maxBytes??bn),i=oe.resolve(e.root,...t.split("/")),n=await Mw(e.root,oe.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await ye.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 ye.realpath(i);if(!es(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ye.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),ye.lstat(i),ye.realpath(i)]);if(await td(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Nn(a,c)||!Nn(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 k=r===null?p.length:r+1-f,S=await s.read(p,0,Math.min(p.length,k),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),ye.lstat(i),ye.realpath(i)]);if(await td(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Nn(c,v)||!Nn(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let y=Buffer.concat(d,f),N;try{N=new Dw("utf-8",{fatal:!0}).decode(y)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:f,hash:e.includeHash===!1?null:Hw("sha256").update(y).digest("hex"),text:N}}finally{await s.close()}}import{promises as oN}from"fs";import sN from"path";import{AsyncLocalStorage as Fw}from"async_hooks";import{randomUUID as nd}from"crypto";import{promises as ce}from"fs";import ad from"os";import B from"path";var rd=16*1024,od=".coordinator",qw=5e3,id=new Fw,kn=new Map;function Ww(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function zw(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 sd(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 Sn(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ce(r,i)?T(r,i):T(r,i)&&e.size===t.size}function ts(e,t){return Sn(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function xe(e){let t,r;try{let i=await Vt(e,rd,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof me?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${rd} 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:zw(JSON.parse(t.toString("utf8")),e),identity:sd(r)}}async function Jw(e){return(await xe(e))?.owner??null}function cd(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==ad.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Qw(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Gw(e,t){try{await ce.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await ce.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function rs(e,t){let r=await xe(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!ts(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ce.mkdir(t,{recursive:!0});let i=B.join(t,`${B.basename(e.file)}.${e.owner.id}.${nd()}.removed`);try{await ce.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await xe(i);if(!n||n.owner.id!==e.owner.id||!Sn(n.identity,e.identity))throw await Gw(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ce.rm(i,{force:!0}),"removed"}function ld(e){return{id:nd(),pid:process.pid,hostname:ad.hostname(),createdAt:new Date().toISOString(),operation:e}}async function ud(e,t){let r;try{r=await ce.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await Jw(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)+`
|
|
173
|
+
`,"utf8"),await r.sync(),i=sd(await r.stat({bigint:!0}))}finally{await r.close()}let n=await xe(e);if(!i||!n||n.owner.id!==t.id||!Sn(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function Uw(e,t){let r=await _(e.runtimeDir,e.locksDir);await ce.mkdir(r,{recursive:!0});let i=await _(e.runtimeDir,B.join(r,od));await ce.mkdir(i,{recursive:!0});let n=ld(t),a=B.join(i,`.${n.id}.tmp`),o=B.join(i,`${n.id}.claim`);try{let s=await ud(a,n);await ce.rename(a,o);let c=await xe(o);if(!c||!Sn(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 ce.rm(a,{force:!0})}}async function Kw(e){let t=B.dirname(e.file),r=!1,i=B.basename(e.file);for(let n of await ce.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=B.join(t,n.name);if(B.resolve(a)!==B.resolve(e.file))try{let o=await xe(a),s=cd(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await rs(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function dd(e){let t=await xe(e.file);if(t){if(t.owner.id!==e.owner.id||!ts(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await rs(t,B.dirname(e.file))}}async function Yw(e,t){let r=Date.now()+qw;for(;;){let i=await Uw(e,t);if(!await Kw(i))return i;if(await dd(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 Xw(e){let t=kn.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return kn.set(e,n),await t,()=>{r(),kn.get(e)===n&&kn.delete(e)}}async function is(e,t,r){let i=B.resolve(e.locksDir),n=id.getStore();if(n?.has(i))return r();let a=await Xw(i);try{let o=await Yw(e,t),s=new Map(n??[]);return s.set(i,o),await id.run(s,async()=>{try{return await r()}finally{await dd(o)}})}finally{a()}}async function fd(e,t,r){let i=[...new Map(e.map(a=>[B.resolve(a.locksDir),a])).values()].sort((a,o)=>B.resolve(a.locksDir).localeCompare(B.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?is(o,t,()=>n(a+1)):r()};return n(0)}async function En(e,t,r){return is(e,`acquire ${t}`,async()=>{let i=await _(e.runtimeDir,e.locksDir);await ce.mkdir(i,{recursive:!0});let n=await _(e.runtimeDir,B.join(i,Ww(t))),a=ld(r),o=await ud(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Cn(e){await xe(e.file)&&await is({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${B.basename(e.file)}`,async()=>{let t=await xe(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!ts(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=B.join(e.locksDir,od);await rs(t,r)})}function Qw(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function hd(e){return cd(await xe(e))}import $y from"node:path";import{createHash as Zw}from"crypto";function Ne(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function ey(e,t){t.has(e)&&Ne("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)||Ne("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&Ne("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Ne("symbol properties are not supported"),`[${e.map(i=>ns(i,t)).join(",")}]`}finally{t.delete(e)}}function ty(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Ne("only plain objects are supported"),t.has(e)&&Ne("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Ne("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))&&Ne("accessor properties are not supported"),`${JSON.stringify(o)}:${ns(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function ns(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)||Ne("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?ey(e,t):ty(e,t);case"bigint":case"function":case"symbol":case"undefined":return Ne(`${typeof e} values are not supported`)}return Ne("unsupported value type")}function as(e){return ns(e,new Set)}function ee(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 Zw("sha256").update(`${e}
|
|
174
|
+
${as(t)}`).digest("hex")}var LC=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),pd=Object.freeze({maxCriteria:1024});var xn=rr(Dt(),1);import{promises as ay}from"node:fs";var oy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,cy=/^A[1-9][0-9]*$/u,ly=/^[a-f0-9]{64}$/u,uy=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]);function z(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function J(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 V(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function os(e,t){return e===null?null:V(e,t)}function vd(e,t){let r=V(e,t);if(!ly.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Kt(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function j(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function dy(e,t){return e===null?null:j(e,t,Number.MIN_SAFE_INTEGER)}function O(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Pe(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Pn(e,t){return Pe(e,t,(r,i)=>V(r,`${t}[${i}]`))}function kt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Yt(e,t){let r=V(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function ss(e,t,r=!1){let i=V(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function le(e,t){let r=z(e,t);return J(r,new Set(["text","truncated"]),t),{text:V(r.text,`${t}.text`,{empty:!0}),truncated:Kt(r.truncated,`${t}.truncated`)}}function fy(e,t){let r=`Native spec_changes[${t}]`,i=z(e,r);J(i,new Set(["capability","operation","source"]),r);let n=V(i.capability,`${r}.capability`);if(!sy.test(n))throw new Error(`${r}.capability is invalid`);let a=O(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:ss(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function hy(e){let t="Native workspace",r=z(e,t);J(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=O(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=os(r.change_branch,`${t}.change_branch`),a=os(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:O(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function py(e){let t="Native loop",r=z(e,t);J(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=Pn(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);kt(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:O(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:O(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:j(r.goal_cycle,`${t}.goal_cycle`,1),iteration:j(r.iteration,`${t}.iteration`),attempt:j(r.attempt,`${t}.attempt`),retry_epoch:j(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:j(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:j(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:j(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:os(r.next_action,`${t}.next_action`)}}function my(e,t){let r=`Native acceptance[${t}]`,i=z(e,r);J(i,new Set(["id","source","text","result","reason"]),r);let n=V(i.id,`${r}.id`);if(!cy.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:ss(i.source,`${r}.source`),text:V(i.text,`${r}.text`),result:O(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:le(i.reason,`${r}.reason`)}}function vy(e,t){let r=`Native builder_handoff.checks[${t}]`,i=z(e,r);return J(i,new Set(["name","result","note"]),r),{name:le(i.name,`${r}.name`),result:O(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:le(i.note,`${r}.note`)}}function gy(e){let t="Native builder_handoff",r=z(e,t);J(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=Pn(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);kt(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:z(r.review,`${t}.review`);return n&&J(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:V(r.candidate_id,`${t}.candidate_id`),identity_provider:V(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:V(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:j(r.iteration,`${t}.iteration`,1),summary:le(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Pe(r.checks,`${t}.checks`,vy),checks_truncated:Kt(r.checks_truncated,`${t}.checks_truncated`),known_limits:Pe(r.known_limits,`${t}.known_limits`,(a,o)=>le(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Kt(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:O(n.status,["passed"],`${t}.review.status`),summary:le(n.summary,`${t}.review.summary`),reviewer_execution_ref:V(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Yt(r.submitted_at,`${t}.submitted_at`)}}function wy(e,t){let r=`Native blockers[${t}]`,i=z(e,r);J(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Pn(i.acceptance_ids,`${r}.acceptance_ids`);return kt(n,`${r}.acceptance_ids`),{owner:O(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:le(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:O(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function yy(e,t){let r=`Native verification.checks[${t}]`,i=z(e,r);return J(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:V(i.id,`${r}.id`),name:le(i.name,`${r}.name`),argv_display:Pe(i.argv_display,`${r}.argv_display`,(n,a)=>le(n,`${r}.argv_display[${a}]`)),argv_truncated:Kt(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:ss(i.cwd_ref,`${r}.cwd_ref`,!0),status:O(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:dy(i.exit_code,`${r}.exit_code`),duration_ms:j(i.duration_ms,`${r}.duration_ms`)}}function Ny(e){let t="Native verification",r=z(e,t);J(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Pe(r.checks,`${t}.checks`,yy);kt(i.map(a=>a.id),`${t}.checks IDs`);let n=V(r.identity_provider,`${t}.identity_provider`);return{candidate_id:V(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:V(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:j(r.iteration,`${t}.iteration`,1),attempt:j(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":O(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:O(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:le(r.summary,`${t}.summary`),risks:Pe(r.risks,`${t}.risks`,(a,o)=>le(a,`${t}.risks[${o}]`)),risks_truncated:Kt(r.risks_truncated,`${t}.risks_truncated`),completed_at:Yt(r.completed_at,`${t}.completed_at`)}}function by(e,t){let r=`Native history[${t}]`,i=z(e,r);J(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Pn(i.unresolved_ids,`${r}.unresolved_ids`);return kt(n,`${r}.unresolved_ids`),{goal_cycle:j(i.goal_cycle,`${r}.goal_cycle`,1),iteration:j(i.iteration,`${r}.iteration`),attempt:j(i.attempt,`${r}.attempt`),outcome:O(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:le(i.summary,`${r}.summary`),completed_at:Yt(i.completed_at,`${r}.completed_at`)}}function ky(e){let t="Native history_overflow.outcome_counts",r=z(e,t),i=["pass","fail","blocked","execution-error","recovery"];return J(r,new Set(i),t),{pass:j(r.pass,`${t}.pass`),fail:j(r.fail,`${t}.fail`),blocked:j(r.blocked,`${t}.blocked`),"execution-error":j(r["execution-error"],`${t}.execution-error`),recovery:j(r.recovery,`${t}.recovery`)}}function Sy(e){let t="Native history_overflow",r=z(e,t);J(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=j(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Yt(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Yt(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=ky(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function Ey(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Cy(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function Xt(e){let t=z(e,"Native portable state");if(J(t,uy,"Native portable state"),t.schema!==zt)throw new Error(`Native portable state schema must be ${zt}`);let r=V(t.name,"Native state name");if(!oy.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Pe(t.spec_changes,"Native spec_changes",fy);kt(i.map(s=>s.capability),"Native spec change capabilities");let n=Pe(t.acceptance,"Native acceptance",my);kt(n.map(s=>s.id),"Native acceptance IDs");let a=Pe(t.history,"Native history",by);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:zt,name:r,language:O(t.language,["en","zh-CN"],"Native state language"),phase:O(t.phase,["shape","build","verify","archive"],"Native state phase"),status:O(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:j(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:vd(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:vd(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:O(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:hy(t.workspace),loop:py(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:gy(t.builder_handoff),blockers:Pe(t.blockers,"Native blockers",wy),verification:t.verification===null?null:Ny(t.verification),history:a,history_overflow:Sy(t.history_overflow),verification_result:O(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:O(t.verification_report,["verification.md"],"Native verification_report"),archived:Kt(t.archived,"Native archived"),created_at:Yt(t.created_at,"Native created_at")};return Ey(o),Cy(o),o}function gd(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return Xt({schema:zt,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:Xo(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function xy(e,t){let r=(0,xn.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function cs(e){let t=await ay.readFile(e,"utf8");return Xt(xy(t,"Native portable state"))}async function wd(e,t,r={}){let i=Xt(t);await ne(e,(0,xn.stringify)(i),r)}var De="comet.native.v3",Le="comet.native.v2",Be="comet.native.v1";var yd="comet.native.portable-migration.v1",Py=new Set(["schema","id","change","fromSchema","status","createdAt"]),Ry=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ay=/^[a-z0-9][a-z0-9-]{7,127}$/u,_y=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Iy=new Set([Be,Le,De]);function Ty(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jy(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function bd(e){let t=Ty(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!Py.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==yd)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!Ay.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!Ry.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!Iy.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!_y.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:yd,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:jy(t.createdAt,"Native portable migration transaction createdAt")}}var kd="comet.native.archive-transaction.v4",Sd="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Oy=new RegExp(`^portable-archive-(${Sd})\\.json$`,"u"),Hy=new RegExp(`^portable-migration-(${Sd})\\.json$`,"u"),Dy=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Ly=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,By=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Vy=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),My=new Set(["capability","operation","source","content"]),Ed=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Cd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xd(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(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function Fy(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Cd(e,r);if(xd(i,My,r),typeof i.capability!="string"||!Ed.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function qy(e){let t=Cd(e,"Native portable Archive transaction");if(xd(t,Vy,"Native portable Archive transaction"),t.schema!==kd)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!Dy.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Ed.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!Ly.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!By.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(Fy);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:kd,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function ls(e){let t=Oy.exec(e);if(t)return{kind:"archive",change:t[1]};let r=Hy.exec(e);return r?{kind:"migration",change:r[1]}:null}async function Pd(e,t){let r=ls(t);if(!r)return null;let i=await se({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=$y.join(e.transactionsDir,t);if(r.kind==="archive"){let s=qy(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=bd(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function Rd(e){return e.kind==="archive"||e.journal.status!=="committed"}import Me from"path";import{TextDecoder as Yy}from"util";import{createHash as Wy}from"node:crypto";import{constants as In,promises as te}from"node:fs";import be from"node:path";import{TextDecoder as zy}from"node:util";function jn(e,t){let r=be.relative(e,t);return r===""||!be.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${be.sep}`)}function Ad(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Jy(e,t){return T({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Tn(e,t){return T({...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 us(e,t){let r=await te.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await te.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function _d(e,t,r){let i=be.resolve(e),n=be.resolve(t);if(!jn(i,n))throw new Error(`${r} is outside its managed root`);let a=[await us(i,r)],o=i;for(let s of be.relative(i,n).split(be.sep).filter(Boolean)){await Ve(a,r),o=be.join(o,s);let c=await us(o,r);if(!jn(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ve(a,r),a}async function Ve(e,t){for(let r of e){let i=await te.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Jy(r,i)||await te.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Uy(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 St(e){let t=Ad(e.maxBytes),r=be.resolve(e.file),i=await _d(e.root,be.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>us(be.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Ve(i,e.label);let a=await te.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=Gy(a),s=await te.realpath(r);if(!jn(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>jn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?In.O_RDONLY:In.O_RDONLY|In.O_NOFOLLOW|In.O_NONBLOCK,l=await te.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([te.lstat(r),te.realpath(r)]);if(await Ve(i,e.label),await Ve(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Tn(o,u)||!Tn(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Uy(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),te.lstat(r),te.realpath(r)]);if(await Ve(i,e.label),await Ve(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!Tn(o,v)||!Tn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:Wy("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Id(e){let t=await St(e),r;try{r=new zy("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function Ur(e){let t=await _d(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await te.readdir(e.directory,{withFileTypes:!0});else{let i=Ad(e.maxEntries);r=[];let n=await te.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 Ve(t,e.label),{entries:r,verify:()=>Ve(t,e.label)}}var Xy=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Qy=new Set(["id","type","source","target","staged","backup"]),Zy=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),eN=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var $d=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var tN=256*1024,kx=1024*1024,Sx=16*1024;var Ex=64*1024*1024;var rN=new Yy("utf-8",{fatal:!0});function On(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Hn(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 Od(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function ds(e,t){if(typeof e!="string"||e.length===0||Me.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function $n(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Td(e,t){if(ds(e,t),e.includes("\\")||e!==Me.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 iN(e,t){let r=On(e,`transaction operations[${t}]`);if(Hn(r,Qy,`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`);ds(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&ds(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 Hd(e){let t=On(e,"Native Archive transaction journal");if(Hn(t,Zy,"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"||!$d.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(!Od(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if($n(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=On(s,`Archive transaction operations[${c}]`);if(Hn(l,eN,`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`);Td(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Td(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&$n(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($n(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`);$n(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 nN(e){let t=On(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Hd(t);if(Hn(t,Xy,"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"||!$d.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Me.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Me.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(!Od(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(iN),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 aN(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Me.join(e.transactionsDir,t)}function Dd(e,t){let r=aN(e,t);return{directory:r,journal:Me.join(r,"transaction.json"),events:Me.join(r,"events.jsonl"),staged:Me.join(r,"staged"),backups:Me.join(r,"backups")}}async function fs(e,t){let r=Dd(e,t);return await Promise.all(Object.values(r).map(i=>_(e.runtimeDir,i))),r}async function hs(e,t,r={}){let i=await fs(e,t),n=await St({root:e.runtimeDir,file:i.journal,maxBytes:tN,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(rN.decode(n.bytes)),o=nN(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function cN(e,t,r){let i;try{i=await oN.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await hs(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(ls(n.name))try{let a=await Pd(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Rd(a))return!0}catch{return!0}return!1}async function lN(e,t){let r=Date.now()+5e3,i=sN.join(e.locksDir,"root-move.lock");for(;;)try{return await En(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await hd(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function ue(e,t,r,i){let n=await lN(e,t);try{if(await wn(e.projectRoot),await cN(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Cn(n)}}import ms from"path";import{createHash as uN}from"crypto";function re(e){return uN("sha256").update(e).digest("hex")}var Wx={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},fN=1e3,hN=8*1024*1024,pN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mN=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),vN=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),gN=new Set(["schema","include","exclude","hash"]),wN=new Set(["provider","gitSelection","physicalSelection","projection"]),yN=new Set(["provider","selection"]),NN=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),bN=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),kN=new Set(["schema","status","before","after"]),SN=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),EN=new Set(["path","hash","size","type","gitObjectId"]),CN=new Set(["path","size","type","reason"]),xN=new Set(["ref","hash","count"]),PN=new Set(["change-created","legacy-migration","explicit"]),RN=new Set(["file","directory","other"]),AN=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),Ln=/^[a-f0-9]{64}$/u,_N=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var zx=64*1024,Jx=64*1024;var Gx={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Ux={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Dn(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}var Kx=(1n<<256n)-1n;function IN(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function TN(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
175
|
+
`)}function jN(e,t){return re(`comet.native.snapshot-policy.v1
|
|
176
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function ps(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function $N(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Ld(e){let t=gn(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?$N(n):void 0;if(a&&!a())return!1;let o=ps(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=ps(r,c,a),o===null||o.size===0)return!1}return ps(r,o,a)?.has(r.length)??!1}}function ON(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>gn(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>gn(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=jN(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(Ld),excludeMatchers:r.map(Ld),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function de(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fe(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Zt(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Re(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Md(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=ms.posix.normalize(e);if(r!==e||ms.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function HN(e,t){let r=de(e,`Native snapshot entry ${t}`);fe(r,EN,`Native snapshot entry ${t}`);let i=Md(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!Ln.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Re(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!_N.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function DN(e,t){let r=de(e,`Native snapshot omission ${t}`);if(fe(r,CN,`Native snapshot omission ${t}`),!RN.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!AN.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Md(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Re(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function LN(e){let t=de(e,"Native snapshot omission overflow");if(fe(t,xN,"Native snapshot omission overflow"),typeof t.hash!="string"||!Ln.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:Zt(t.count,"Native snapshot omission overflow count")}}function Qt(e,t){let r=de(e,t);if(fe(r,bN,t),typeof r.hash!="string"||!Ln.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Re(r.recordCount,`${t} recordCount`),n=Re(r.storedRecordCount,`${t} storedRecordCount`),a=Re(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Bd(e){let t=de(e,"Native Git selection evidence");if(fe(t,NN,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=Qt(t.stageBefore,"Native Git selection stageBefore"),i=Qt(t.combined,"Native Git selection combined"),n=Qt(t.stageAfter,"Native Git selection stageAfter"),a=Qt(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Qt(t.finalCombined,"Native Git selection finalCombined"),s=Qt(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Dn(r,n)||!Dn(n,a)||!Dn(i,o)||!Dn(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Vd(e,t){let r=de(e,t);if(fe(r,SN,t),typeof r.hash!="string"||!Ln.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Re(r.visitedNodeCount,`${t} visitedNodeCount`),n=Re(r.recordCount,`${t} recordCount`),a=Re(r.storedRecordCount,`${t} storedRecordCount`),o=Re(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function BN(e){let t=de(e,"Native physical selection evidence");if(fe(t,kN,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=Vd(t.before,"Native physical selection before"),i=Vd(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!IN(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function Fd(e){let t=de(e,"Native content snapshot manifest");if(fe(t,mN,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!PN.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let g=de(t.capture,"Native content snapshot capture");if(fe(g,wN,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let P=g.gitSelection===void 0?void 0:Bd(g.gitSelection),b=g.physicalSelection===void 0?void 0:BN(g.physicalSelection),I=null;if(g.projection!==void 0){let X=de(g.projection,"Native content snapshot projection");if(fe(X,yN,"Native content snapshot projection"),X.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");I={provider:"git",...X.selection===void 0?{}:{selection:Bd(X.selection)}}}if(g.provider==="git"){if(b||I)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...P?{gitSelection:P}:{}}}else{if(P)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&I)throw new Error("Native physical-tree capture cannot combine selection and projection");r=I?{provider:"physical-tree",projection:I}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=de(t.limits,"Native content snapshot limits");fe(i,vN,"Native content snapshot limits");let n={maxFiles:Zt(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Zt(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Zt(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Zt(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Zt(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let g=de(t.policy,"Native snapshot policy");if(fe(g,gN,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=ON({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(HN),s=t.omitted.map(DN),c=Re(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:LN(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>n.maxFileBytes)||o.reduce((g,P)=>g+P.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>fN||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(g=>g.reason==="git-enumeration-limit"),f=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...d,...f])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(g=>g.reason==="physical-enumeration-limit"),y=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...m,...y])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=r?.physicalSelection,k=N?.status==="overflow"||N?.status==="overflow-and-changed",S=N?.status==="changed"||N?.status==="overflow-and-changed";if(k!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(TN(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function VN(e,t){if(!pN.test(t))throw new Error(`Invalid Native change name: ${t}`);return ms.join(ae(e,t),"baseline-manifest.json")}async function qd(e,t){let r=VN(e,t),i=we(e,r);await _(i,r);try{let n=await Id({root:i,file:r,maxBytes:hN,label:"Native baseline snapshot manifest"});return Fd(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var JN=rr(Dt(),1);var dP=4*1024*1024;var GN=null;function UN(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Wd(e,t){return(...r)=>{let i=GN;if(i===null)return t(...r);let n=UN(`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 vP=Wd("hookWritePolicy",async e=>(await zo(e))?.hook??{allow_paths:[]});var dR=256*1024;var ER={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import{createHash as YN}from"node:crypto";import{promises as Bn}from"node:fs";import st from"node:path";var Kr=/^[a-f0-9]{64}$/u,Jd=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,XN=16*1024,gs=process.platform;function Kd(e,t){let r=st.relative(e,t);return st.isAbsolute(r)||r===".."||r.startsWith(`..${st.sep}`)?null:r.replaceAll("\\","/")||"."}function Yd(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Xd(e,t){if(e.length===0||Yd(e)||e.includes("\\")||st.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=st.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function ws(e,t){return YN("sha256").update(`${e}
|
|
177
|
+
${t}`).digest("hex")}async function Gd(e,t){let r=await Bn.realpath(t),i=await Bn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=gs==="win32"?st.normalize(r).toLowerCase():r;return ws(e,`${n}
|
|
178
178
|
${i.dev}
|
|
179
179
|
${i.ino}
|
|
180
|
-
${i.birthtimeMs}`)}async function
|
|
180
|
+
${i.birthtimeMs}`)}async function Ud(e,t){let r=await Bn.realpath(t),i=await Bn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=gs==="win32"?st.normalize(r).toLowerCase():r;return ws(e,n)}function QN(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 vs(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Yd(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Qd(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(vs(e.changeBranch,"Native workspace change branch"),vs(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 ZN(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"||!Jd.test(t.baseCommit)||typeof t.targetCommit!="string"||!Jd.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");vs(t.targetBranch,"Native workspace Git target branch")}function Vn(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"||!Kr.test(String(t.projectRootId))||!Kr.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");QN(t.capturedAt),Xd(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&&!Kr.test(String(t.projectRootPathId))||a&&!Kr.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Kr.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&ZN(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(Qd(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 eb(e,t){return st.join(ae(e,t),"workspace.json")}function tb(e,t){let r=eb(e,t),i=we(e,r),n=Kd(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Xd(n,"Native workspace file ref")}}async function rb(e,t){try{let r=tb(e,t),i=await se({root:r.root,ref:r.ref,maxBytes:XN});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ib(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Kd(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=K(e.paths.projectRoot),i=r.isGitWorktree?zr(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:zr(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([Gd("comet.native.workspace-project-root.v2",e.paths.projectRoot),Gd("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Ud("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Ud("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&&Qd(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:ws("comet.native.workspace-session.v2",`${s}
|
|
181
181
|
${c}
|
|
182
|
-
${t.sessionId}`)}:{}},h=t.binding?{schema:"comet.native.workspace.v3",...f,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...f};return In(h),h}async function Xt(t,e){let r=await kN(t,e);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(In(r),r)}async function Tn(t){In(t.identity);let e=await SN({paths:t.paths,name:"workspace-advisory",revision:t.identity.capturedRevision}),r=[],i=[];return e.nativeRootRef!==t.identity.nativeRootRef&&r.push("native-root-ref"),t.identity.projectRootPathId&&t.identity.nativeRootPathId?(e.projectRootPathId!==t.identity.projectRootPathId&&r.push("project-root-path"),e.nativeRootPathId!==t.identity.nativeRootPathId&&r.push("native-root-path")):(e.projectRootId!==t.identity.projectRootId&&r.push("project-root-legacy-identity"),e.nativeRootId!==t.identity.nativeRootId&&r.push("native-root-legacy-identity")),gs==="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 jn(t){if(In(t.identity),t.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Tn(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=K(t.paths.projectRoot);return t.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!==t.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${t.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:t.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function Od(t,e){let r=await Xt(t,e);if(r===null)return null;let i=await jn({paths:t,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}var De="comet.native.v3",Le="comet.native.v2",Be="comet.native.v1";var Ld=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],CN=new Set(Ld),Bd=new Set([...Ld,"minimum_runtime_version","revision"]),xN=new Set([...Bd,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),PN=new Set(["capability","operation","source","base_hash"]),RN=new Set(["shape","build","verify","archive"]),AN=new Set(["implicit","confirmed"]),_N=new Set(["pending","pass","fail"]),Me="comet-state.yaml",Ns=/^[a-f0-9]{64}$/u,Md=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,IN=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,On=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},St=class extends Error{constructor(r,i){super(r!==De||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Hn=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"},Qt=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"},Dn=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"},bR=Jr("en");function Yr(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Vd(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Ln(t){if(!Md.test(t))throw new Error(`Invalid Native change name: ${t}`)}function TN(t){if(!Md.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function Fd(t,e){if(t.length===0||Y.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function jN(t,e){let r=Yr(t,`spec_changes[${e}]`);if(Vd(r,PN,`spec_changes[${e}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(TN(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&Fd(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Ns.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Ns.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function $N(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function ks(t,e){if(Vd(t,e,Me),typeof t.name!="string")throw new Error("Native change name is required");if(Ln(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!RN.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!AN.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let r=t.spec_changes.map(jN),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof t.verification_result!="string"||!_N.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&Fd(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!$N(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:r,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Bn(t){let e=Yr(t,Me);if(e.schema!==Be)throw new Error(`Expected ${Be}`);return{schema:Be,...ks(e,CN)}}function Kr(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function ys(t,e,r){if(t===null)return null;let i=typeof t=="string"?IN.exec(t):null;if(!i||i[1]!==r)throw new Error(`${e} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return t}function ON(t){if(t==null)return null;if(typeof t!="string"||!Ns.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function HN(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Mn(t){let e=Yr(t,Me);if(e.schema!==Le)throw new Error(`Expected ${Le}`);if(Kr(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Le} minimum_runtime_version must be 2`);return{schema:Le,minimum_runtime_version:2,revision:Kr(e.revision,"Native v2 revision"),...ks(e,Bd)}}function Vn(t){let e=Yr(t,Me);if(e.schema!==De){if(e.schema===Be||e.schema===Le){let o=e.schema===Be?Bn(e):Mn(e);throw new On(o.name,o.schema)}throw new St(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let r=Kr(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new St(e.schema,r);if(r!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let i=Kr(e.revision,"Native revision"),n=ks(e,xN),a=ON(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:De,minimum_runtime_version:3,revision:i,verification_protocol:HN(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:ys(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:ys(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:ys(e.partial_allowance,"Native partial_allowance","allowances")}}function qd(t){let e=Yr(t,Me);if(e.schema===Be){let n=Bn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${De}`}}if(e.schema===Le){let n=Mn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${De}`}}if(e.schema!==De){let n=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new St(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let r=Kr(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:r,state:null,message:new St(e.schema,r).message};let i=Vn(e);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function st(t,e){Ln(e);let r=Y.join(t.changesDir,e);if(!F(t.changesDir,r))throw new Error("Native change path escaped");return r}async function Ss(t,e){let r=ne(t,e),i=Y.join(r,"schema-migration.json");await _(F(t.runtimeDir,i)?t.runtimeDir:t.nativeRoot,i);try{return await $n.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Wd(t,e=Y.dirname(t)){let r=Y.relative(e,t).split(Y.sep).join("/"),i=await oe({root:e,ref:r,maxBytes:null,includeHash:!1}),n=(0,bs.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${n.errors[0].message}`);return n.toJS()}async function DN(t,e){let r=Y.join(st(t,e),Me);await _(t.nativeRoot,r);let i=qd(await Wd(r,t.nativeRoot));if(i.state&&i.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Ss(t,e)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(i.status==="current"&&i.state&&await BN(t,i.state),i)}async function LN(t,e){let r=Y.join(st(t,e),Me);await _(t.nativeRoot,r);let i=qd(await Wd(r,t.nativeRoot));if(i.state&&i.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return i}async function BN(t,e){if(await Cd(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function ct(t,e){let r=await DN(t,e);if(r.status==="migration-required")throw new On(e,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new St(r.schema,r.minimumRuntimeVersion);return await Od(t,e),r.state}async function MN(t){let e;try{let i=await Gr({root:t.nativeRoot,directory:t.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await i.verify(),e=i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}return e.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort()}async function zd(t){let e=[];for(let r of await MN(t)){let i=await LN(t,r);if(!i.state){if(await Dd(t,r))continue;e.push(r);continue}if(i.state.archived)continue;let n=await Xt(t,r);if(!(!n&&await Dd(t,r))){if(n?.schema==="comet.native.workspace.v3"){if((await jn({paths:t,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await Tn({paths:t,identity:n})).state==="drifted")continue;e.push(r)}}return e}function Hd(t,e){let r=Y.resolve(t),i=Y.resolve(e);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function Dd(t,e){for(let r of Wt(t.projectRoot))if(!Hd(r,t.projectRoot))try{let i=await W(r);if(!i)continue;let n=await $e(r,i.native.artifact_root),a=Y.join(n.changesDir,e),o=Y.join(a,"comet-state.yaml");try{let l=await $n.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await $n.readFile(Y.join(it(n,e),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&Hd(d.workspace.projectRoot,r))return!0;continue}}catch(l){l.code}await $n.access(Y.join(a,Me));let s=await Xt(n,e);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await jn({paths:n,identity:s})).state==="aligned")return!0;continue}if((await Tn({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}var CR=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Jd=Object.freeze({maxCriteria:1024});var Gd="comet.native.portable-migration.v1",WN=new Set(["schema","id","change","fromSchema","status","createdAt"]),zN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,JN=/^[a-z0-9][a-z0-9-]{7,127}$/u,GN=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),UN=new Set([Be,Le,De]);function KN(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function YN(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let r=new Date(t);if(Number.isNaN(r.valueOf())||r.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function Kd(t){let e=KN(t,"Native portable migration transaction"),r=Object.keys(e).filter(i=>!WN.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(e.schema!==Gd)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!JN.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!zN.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!UN.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!GN.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Gd,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:YN(e.createdAt,"Native portable migration transaction createdAt")}}var Yd="comet.native.archive-transaction.v4",Xd="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",QN=new RegExp(`^portable-archive-(${Xd})\\.json$`,"u"),ZN=new RegExp(`^portable-migration-(${Xd})\\.json$`,"u"),eb=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,tb=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rb=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),ib=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),nb=new Set(["capability","operation","source","content"]),Qd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Zd(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ef(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(t).length!==e.size)throw new Error(`${r} fields are invalid`)}function ab(t,e){let r=`Native portable Archive spec_changes[${e}]`,i=Zd(t,r);if(ef(i,nb,r),typeof i.capability!="string"||!Qd.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function ob(t){let e=Zd(t,"Native portable Archive transaction");if(ef(e,ib,"Native portable Archive transaction"),e.schema!==Yd)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!eb.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!Qd.test(e.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(e.start_state_version)||Number(e.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof e.archive_ref!="string"||!tb.test(e.archive_ref)||!e.archive_ref.endsWith(`-${e.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof e.status!="string"||!rb.has(e.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=e.spec_changes.map(ab);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(e.next_spec_index)||Number(e.next_spec_index)<0||Number(e.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof e.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(e.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==e.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Yd,id:e.id,change:e.change,start_state_version:Number(e.start_state_version),archive_ref:e.archive_ref,status:e.status,next_spec_index:Number(e.next_spec_index),spec_changes:r,created_at:e.created_at}}function Es(t){let e=QN.exec(t);if(e)return{kind:"archive",change:e[1]};let r=ZN.exec(t);return r?{kind:"migration",change:r[1]}:null}async function tf(t,e){let r=Es(e);if(!r)return null;let i=await oe({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=XN.join(t.transactionsDir,e);if(r.kind==="archive"){let s=ob(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Kd(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function rf(t){return t.kind==="archive"||t.journal.status!=="committed"}import Ve from"path";import{TextDecoder as cb}from"util";var lb=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),ub=new Set(["id","type","source","target","staged","backup"]),db=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),fb=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var of=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var pb=256*1024,YR=1024*1024,XR=16*1024;var QR=64*1024*1024;var hb=new cb("utf-8",{fatal:!0});function qn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Wn(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function sf(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function Cs(t,e){if(typeof t!="string"||t.length===0||Ve.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function Fn(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function nf(t,e){if(Cs(t,e),t.includes("\\")||t!==Ve.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function mb(t,e){let r=qn(t,`transaction operations[${e}]`);if(Wn(r,ub,`transaction operations[${e}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${e}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);Cs(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Cs(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 cf(t){let e=qn(t,"Native Archive transaction journal");if(Wn(e,db,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!of.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!sf(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Fn(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=e.operations.map((s,c)=>{let l=qn(s,`Archive transaction operations[${c}]`);if(Wn(l,fb,`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`);nf(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&nf(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Fn(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(Fn(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`);Fn(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/${e.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.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:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:r}}function vb(t){let e=qn(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return cf(e);if(Wn(e,lb,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!of.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!Ve.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!Ve.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!sf(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let r=e.operations.map(mb),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:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:r}}function gb(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return Ve.join(t.transactionsDir,e)}function lf(t,e){let r=gb(t,e);return{directory:r,journal:Ve.join(r,"transaction.json"),events:Ve.join(r,"events.jsonl"),staged:Ve.join(r,"staged"),backups:Ve.join(r,"backups")}}async function xs(t,e){let r=lf(t,e);return await Promise.all(Object.values(r).map(i=>_(t.runtimeDir,i))),r}async function Ps(t,e,r={}){let i=await xs(t,e),n=await kt({root:t.runtimeDir,file:i.journal,maxBytes:pb,label:`Native transaction journal ${e}`,hooks:r.hooks}),a=JSON.parse(hb.decode(n.bytes)),o=vb(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function Nb(t,e,r){let i;try{i=await wb.readdir(t.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Ps(t,n.name);if(a.id!==e&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Es(n.name))try{let a=await tf(t,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(rf(a))return!0}catch{return!0}return!1}async function bb(t,e){let r=Date.now()+5e3,i=yb.join(t.locksDir,"root-move.lock");for(;;)try{return await Sn(t,"root-move",e)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await md(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function fe(t,e,r,i){let n=await bb(t,e);try{if(await mn(t.projectRoot),await Nb(t,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await En(n)}}import{promises as Xr}from"node:fs";import q from"node:path";var lt=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function Rs(t,e){let r=q.normalize(t),i=q.normalize(e);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ff(t,e){let r=q.relative(t,e);return r===""||!q.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${q.sep}`)}function uf(t){return JSON.stringify(t.native)}async function zn(t,e){let r=await W(t);if(r&&e){if(uf(r)!==uf(e))throw new Error(`Native worktree configuration differs from the source project: ${q.join(t,".comet","config.yaml")}`);return!1}return!r&&e?(await Mr(t,e),!0):!1}async function kb(t,e){if(!ff(t,e))return!1;let i=`/${q.relative(t,e).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=xe(t,["rev-parse","--git-common-dir"]),a=q.resolve(t,n),o=q.join(a,"info","exclude"),s="";try{s=await Xr.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Xr.mkdir(q.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
182
|
+
${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Vn(p),p}async function er(e,t){let r=await rb(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Vn(r),r)}async function Mn(e){Vn(e.identity);let t=await ib({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")),gs==="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 Fn(e){if(Vn(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 Mn(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=K(e.paths.projectRoot);return e.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function Zd(e,t){let r=await er(e,t);if(r===null)return null;let i=await Fn({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}var rf=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],ab=new Set(rf),nf=new Set([...rf,"minimum_runtime_version","revision"]),ob=new Set([...nf,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),sb=new Set(["capability","operation","source","base_hash"]),cb=new Set(["shape","build","verify","archive"]),lb=new Set(["implicit","confirmed"]),ub=new Set(["pending","pass","fail"]),Fe="comet-state.yaml",Ns=/^[a-f0-9]{64}$/u,af=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,db=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Wn=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Et=class extends Error{constructor(r,i){super(r!==De||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},zn=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"},tr=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"},Jn=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"},lA=Jr("en");function Xr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function of(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 Gn(e){if(!af.test(e))throw new Error(`Invalid Native change name: ${e}`)}function fb(e){if(!af.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function sf(e,t){if(e.length===0||Y.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function hb(e,t){let r=Xr(e,`spec_changes[${t}]`);if(of(r,sb,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(fb(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&sf(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Ns.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Ns.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function pb(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function ks(e,t){if(of(e,t,Fe),typeof e.name!="string")throw new Error("Native change name is required");if(Gn(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!cb.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!lb.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(hb),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!ub.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&sf(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!pb(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Rn(e){let t=Xr(e,Fe);if(t.schema!==Be)throw new Error(`Expected ${Be}`);return{schema:Be,...ks(t,ab)}}function Yr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ys(e,t,r){if(e===null)return null;let i=typeof e=="string"?db.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function mb(e){if(e==null)return null;if(typeof e!="string"||!Ns.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function vb(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function An(e){let t=Xr(e,Fe);if(t.schema!==Le)throw new Error(`Expected ${Le}`);if(Yr(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Le} minimum_runtime_version must be 2`);return{schema:Le,minimum_runtime_version:2,revision:Yr(t.revision,"Native v2 revision"),...ks(t,nf)}}function _n(e){let t=Xr(e,Fe);if(t.schema!==De){if(t.schema===Be||t.schema===Le){let o=t.schema===Be?Rn(t):An(t);throw new Wn(o.name,o.schema)}throw new Et(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Yr(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Et(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Yr(t.revision,"Native revision"),n=ks(t,ob),a=mb(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:De,minimum_runtime_version:3,revision:i,verification_protocol:vb(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:ys(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:ys(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:ys(t.partial_allowance,"Native partial_allowance","allowances")}}function cf(e){let t=Xr(e,Fe);if(t.schema===Be){let n=Rn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${De}`}}if(t.schema===Le){let n=An(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${De}`}}if(t.schema!==De){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Et(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Yr(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Et(t.schema,r).message};let i=_n(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function lt(e,t){Gn(t);let r=Y.join(e.changesDir,t);if(!F(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Ss(e,t){let r=ae(e,t),i=Y.join(r,"schema-migration.json");await _(F(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await qn.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function lf(e,t=Y.dirname(e)){let r=Y.relative(t,e).split(Y.sep).join("/"),i=await se({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,bs.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function gb(e,t){let r=Y.join(lt(e,t),Fe);await _(e.nativeRoot,r);let i=cf(await lf(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Ss(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await yb(e,i.state),i)}async function wb(e,t){let r=Y.join(lt(e,t),Fe);await _(e.nativeRoot,r);let i=cf(await lf(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function yb(e,t){if(await qd(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function ut(e,t){let r=await gb(e,t);if(r.status==="migration-required")throw new Wn(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Et(r.schema,r.minimumRuntimeVersion);return await Zd(e,t),r.state}async function Nb(e){let t;try{let i=await Ur({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await i.verify(),t=i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort()}async function uf(e){let t=[];for(let r of await Nb(e)){let i=await wb(e,r);if(!i.state){if(await tf(e,r))continue;t.push(r);continue}if(i.state.archived)continue;let n=await er(e,r);if(!(!n&&await tf(e,r))){if(n?.schema==="comet.native.workspace.v3"){if((await Fn({paths:e,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await Mn({paths:e,identity:n})).state==="drifted")continue;t.push(r)}}return t}function ef(e,t){let r=Y.resolve(e),i=Y.resolve(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function tf(e,t){for(let r of Gt(e.projectRoot))if(!ef(r,e.projectRoot))try{let i=await W(r);if(!i)continue;let n=await Oe(r,i.native.artifact_root),a=Y.join(n.changesDir,t),o=Y.join(a,"comet-state.yaml");try{let l=await qn.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await qn.readFile(Y.join(nt(n,t),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&ef(d.workspace.projectRoot,r))return!0;continue}}catch(l){l.code}await qn.access(Y.join(a,Fe));let s=await er(n,t);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await Fn({paths:n,identity:s})).state==="aligned")return!0;continue}if((await Mn({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}var kb=["outcome","scope","nonGoals","acceptanceExamples"],gA=[...kb,"constraints","decisions","openQuestions","verificationExpectations"];var jb=rr(Dt(),1);import{execFileSync as Sb}from"node:child_process";var Eb=3e4,Cb=8*1024*1024,Es=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function xb(e,t){try{return Sb("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Eb,maxBuffer:Cb,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Es(e,t,i)}}function Ae(e,t){return xb(e,t).trim()}function Cs(e){return Ae(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function xs(e,t){Ae(e,["check-ref-format","--branch",t])}import{promises as Qr}from"node:fs";import q from"node:path";var dt=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function Ps(e,t){let r=q.normalize(e),i=q.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function hf(e,t){let r=q.relative(e,t);return r===""||!q.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${q.sep}`)}function df(e){return JSON.stringify(e.native)}async function Un(e,t){let r=await W(e);if(r&&t){if(df(r)!==df(t))throw new Error(`Native worktree configuration differs from the source project: ${q.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await Fr(e,t),!0):!1}async function Pb(e,t){if(!hf(e,t))return!1;let i=`/${q.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=Ae(e,["rev-parse","--git-common-dir"]),a=q.resolve(e,n),o=q.join(a,"info","exclude"),s="";try{s=await Qr.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Qr.mkdir(q.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
183
183
|
`)?"":`
|
|
184
|
-
`;return await
|
|
185
|
-
`,"utf8"),!0}function Sb(t,e,r){let i=q.resolve(t,r??q.join(".worktrees",e)),n=q.resolve(t,xe(t,["rev-parse","--git-common-dir"]));if(ff(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(Wt(t).some(a=>Rs(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function Eb(t){try{throw await Xr.lstat(t),new Error(`Native worktree path already exists: ${t}`)}catch(e){if(e.code!=="ENOENT")throw e}}async function df(t){try{return await Xr.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function As(t){let e=q.resolve(t.projectRoot);if(t.isolation==="current"){if(t.changeBranch||t.targetBranch||t.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=K(e);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:e,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:e,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await $e(e,t.sourceConfig?.native.artifact_root??"docs");return hd([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${t.isolation} workspace`,async()=>{let i=K(e);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=t.changeBranch??`comet/${t.name}`;rs(e,n);let a=i.currentBranch===n,o=t.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(rs(e,o),!zt(e,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(t.isolation==="branch"){if(t.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let h=!1;if(!a){if(!ts(e))throw new Error("Native branch isolation requires a clean current working directory");if(zt(e,n))throw new Error(`Native change branch already exists: ${n}`);xe(e,["switch","-c",n,o]),h=!0}let v;try{v=await zn(e,t.sourceConfig)}catch(p){throw new lt(`Native branch preparation is incomplete: ${p.message}`,{isolation:"branch",projectRoot:e,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}return{projectRoot:e,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:e,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let h=t.worktreePath?q.resolve(i.primaryWorktreeRoot,t.worktreePath):void 0;if(h&&!Rs(h,i.currentWorktreeRoot))throw new Error(`Native worktree path ${h} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await zn(e,t.sourceConfig)}catch(p){throw new lt(`Native worktree preparation is incomplete: ${p.message}`,{isolation:"worktree",projectRoot:e,changeBranch:n,targetBranch:o,worktreePath:e,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}return{projectRoot:e,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:e,changeBranch:n,targetBranch:o,worktreePath:e,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=gn(i.primaryWorktreeRoot),c=s.find(h=>h.branch===n);if(c&&await df(c.root)){let h=t.worktreePath?q.resolve(i.primaryWorktreeRoot,t.worktreePath):void 0;if(h&&!Rs(h,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await zn(c.root,t.sourceConfig)}catch(p){throw new lt(`Native worktree preparation is incomplete: ${p.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await df(c.root)&&(xe(i.primaryWorktreeRoot,["worktree","prune"]),s=gn(i.primaryWorktreeRoot));let l=zt(e,n);if(s.some(h=>h.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=Sb(i.primaryWorktreeRoot,t.name,t.worktreePath);await Eb(u);let d=await kb(i.primaryWorktreeRoot,u),f={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{xe(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),f.createdBranch=!l,f.createdWorktree=!0,f.configInitialized=await zn(u,t.sourceConfig)}catch(h){throw new lt(`Native worktree preparation is incomplete: ${h.message}`,f,{cause:h})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:f}})}var HA=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as $b}from"node:fs";import Zr from"node:path";function Jn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Gn(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Ae(t,e,r=!1){if(typeof t!="string"||!r&&t.length===0)throw new Error(`${e} must be ${r?"a string":"a non-empty string"}`);return t}function pf(t,e){return t===null?null:Ae(t,e)}function Kn(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function Ob(t,e){if(t===null)return null;if(!Number.isSafeInteger(t))throw new Error(`${e} must be null or a safe integer`);return t}function Hb(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function Un(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function _s(t,e){if(t===null)return null;let r=Ae(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO timestamp`);return r}function Is(t,e){let r=Ae(t,e);if(!Zr.isAbsolute(r))throw new Error(`${e} must be absolute`);return Zr.resolve(r)}function Db(t,e){let r=`Native local checks[${e}]`,i=Jn(t,r);if(Gn(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,u)=>Ae(l,`${r}.argv[${u}]`,!0)),a=Un(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=_s(i.startedAt,`${r}.startedAt`),s=_s(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=Kn(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Ae(i.id,`${r}.id`),name:Ae(i.name,`${r}.name`),operationId:Ae(i.operationId,`${r}.operationId`),status:a,repeatable:Hb(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Kn(i.executionCount,`${r}.executionCount`),argv:n,cwd:Is(i.cwd,`${r}.cwd`),exitCode:Ob(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Ae(i.log,`${r}.log`)}}function hf(t){let e="Native local execution state",r=Jn(t,e);if(Gn(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),e),r.schema!==Vr)throw new Error(`Native local execution schema must be ${Vr}`);let i=Jn(r.workspace,"Native local workspace");Gn(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Jn(r.execution,"Native local execution");Gn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=_s(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ae(o.operationId,"Native local execution.operationId"),stage:Un(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Un(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:pf(o.executionId,"Native local execution.executionId"),status:Un(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Kn(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(Db);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:Vr,change:Ae(r.change,"Native local change"),basedOnStateVersion:Kn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Is(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Is(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:pf(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function mf(t){return hf({schema:Vr,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,workspace:{projectRoot:Zr.resolve(t.projectRoot),worktreeRoot:Zr.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null},execution:null,checks:[]})}async function vf(t,e,r={}){let i=hf(e);await $b.mkdir(Zr.dirname(t),{recursive:!0}),await ge(t,i,r)}var gf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Mb="comet-state.yaml",Vb="state.json",dI=Jr("en");function wf(t,e){if(!gf.test(e))throw new Error(`Invalid Native change name: ${e}`);let r=ei.join(t.changesDir,e);if(!F(t.changesDir,r))throw new Error("Native change path escaped");return r}function Ts(t,e){return ei.join(wf(t,e),Mb)}function Fb(t,e){return ei.join(it(t,e),Vb)}async function yf(t,e){try{let r=await ut.readFile(Ts(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function qb(t){return{isolation:t?.isolation??"current",change_branch:t?.changeBranch??null,target_branch:t?.targetBranch??null,finish:null}}function Wb(t){return K(t).currentBranch}function zb(t,e){if(!e)return;let r=K(t);if(e.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==e.changeBranch))throw new Error(`Native workspace binding ${e.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(e.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Nf(t){return fe(t.paths,`create portable change ${t.name}`,async()=>{if(!gf.test(t.name))throw new Error(`Invalid Native change name: ${t.name}`);t.initialProjectConfig&&await W(t.paths.projectRoot)===null&&await Mr(t.paths.projectRoot,t.initialProjectConfig),zb(t.paths.projectRoot,t.workspaceBinding);let e=(await zd(t.paths)).filter(o=>o!==t.name);if(e.length>0)throw new Qt(t.workspaceBinding?.isolation??"current",e);let r=wf(t.paths,t.name),i=it(t.paths,t.name);await Promise.all([_(t.paths.nativeRoot,r),_(t.paths.runtimeDir,i)]);let n=!1,a=!1;try{await ut.mkdir(t.paths.changesDir,{recursive:!0}),await ut.mkdir(r,{recursive:!1}),n=!0,await ut.mkdir(t.paths.changesRuntimeDir,{recursive:!0}),await ut.mkdir(i,{recursive:!1}),a=!0,await ut.mkdir(ei.join(r,"specs"),{recursive:!0}),await ie(ei.join(r,"brief.md"),Jr(t.language));let o=rd({name:t.name,language:t.language,workspace:qb(t.workspaceBinding),createdAt:t.now,nextAction:"confirm-shape"});return await id(Ts(t.paths,t.name),o,{containedRoot:t.paths.nativeRoot}),await vf(Fb(t.paths,t.name),mf({portableState:o,projectRoot:t.paths.projectRoot,branch:Wb(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),o}catch(o){throw a&&await ut.rm(i,{recursive:!0,force:!0}),n&&await ut.rm(r,{recursive:!0,force:!0}),o}})}async function bf(t,e){return ss(Ts(t,e))}import{randomUUID as Jb}from"crypto";import{promises as Yn}from"fs";import Sf from"path";var js="comet.selection.v2",gI=16*1024;function Ef(t){return Sf.join(t,".comet","current-change.json")}function Gb(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function kf(t){return t===null||typeof t=="string"}function Ub(t){let e;try{e=JSON.parse(t)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!Gb(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!kf(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:js,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==js)throw new Error(`current change selection schema must be ${js}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!kf(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function Cf(t,e){let r=Ub(JSON.stringify(e));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=Ef(t),n=`${i}.${Jb()}.tmp`;await Yn.mkdir(Sf.dirname(i),{recursive:!0});try{await Yn.writeFile(n,`${JSON.stringify(r.selection,null,2)}
|
|
186
|
-
`,"utf8"),await
|
|
184
|
+
`;return await Qr.appendFile(o,`${c}${i}
|
|
185
|
+
`,"utf8"),!0}function Rb(e,t,r){let i=q.resolve(e,r??q.join(".worktrees",t)),n=q.resolve(e,Ae(e,["rev-parse","--git-common-dir"]));if(hf(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(Gt(e).some(a=>Ps(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function Ab(e){try{throw await Qr.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function ff(e){try{return await Qr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Rs(e){let t=q.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=K(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await Oe(t,e.sourceConfig?.native.artifact_root??"docs");return fd([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=K(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;xs(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(xs(t,o),!Ut(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!Cs(t))throw new Error("Native branch isolation requires a clean current working directory");if(Ut(t,n))throw new Error(`Native change branch already exists: ${n}`);Ae(t,["switch","-c",n,o]),p=!0}let v;try{v=await Un(t,e.sourceConfig)}catch(h){throw new dt(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?q.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Ps(p,i.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await Un(t,e.sourceConfig)}catch(h){throw new dt(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=yn(i.primaryWorktreeRoot),c=s.find(p=>p.branch===n);if(c&&await ff(c.root)){let p=e.worktreePath?q.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Ps(p,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await Un(c.root,e.sourceConfig)}catch(h){throw new dt(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await ff(c.root)&&(Ae(i.primaryWorktreeRoot,["worktree","prune"]),s=yn(i.primaryWorktreeRoot));let l=Ut(t,n);if(s.some(p=>p.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=Rb(i.primaryWorktreeRoot,e.name,e.worktreePath);await Ab(u);let d=await Pb(i.primaryWorktreeRoot,u),f={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{Ae(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),f.createdBranch=!l,f.createdWorktree=!0,f.configInitialized=await Un(u,e.sourceConfig)}catch(p){throw new dt(`Native worktree preparation is incomplete: ${p.message}`,f,{cause:p})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:f}})}var YA=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as Bb}from"node:fs";import ei from"node:path";function Kn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Yn(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 _e(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function pf(e,t){return e===null?null:_e(e,t)}function Qn(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function Vb(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function Mb(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Xn(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function As(e,t){if(e===null)return null;let r=_e(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function _s(e,t){let r=_e(e,t);if(!ei.isAbsolute(r))throw new Error(`${t} must be absolute`);return ei.resolve(r)}function Fb(e,t){let r=`Native local checks[${t}]`,i=Kn(e,r);if(Yn(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,u)=>_e(l,`${r}.argv[${u}]`,!0)),a=Xn(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=As(i.startedAt,`${r}.startedAt`),s=As(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=Qn(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:_e(i.id,`${r}.id`),name:_e(i.name,`${r}.name`),operationId:_e(i.operationId,`${r}.operationId`),status:a,repeatable:Mb(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Qn(i.executionCount,`${r}.executionCount`),argv:n,cwd:_s(i.cwd,`${r}.cwd`),exitCode:Vb(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:_e(i.log,`${r}.log`)}}function mf(e){let t="Native local execution state",r=Kn(e,t);if(Yn(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==qr)throw new Error(`Native local execution schema must be ${qr}`);let i=Kn(r.workspace,"Native local workspace");Yn(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Kn(r.execution,"Native local execution");Yn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=As(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:_e(o.operationId,"Native local execution.operationId"),stage:Xn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Xn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:pf(o.executionId,"Native local execution.executionId"),status:Xn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Qn(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(Fb);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:qr,change:_e(r.change,"Native local change"),basedOnStateVersion:Qn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:_s(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:_s(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:pf(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function vf(e){return mf({schema:qr,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:ei.resolve(e.projectRoot),worktreeRoot:ei.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function gf(e,t,r={}){let i=mf(t);await Bb.mkdir(ei.dirname(e),{recursive:!0}),await ge(e,i,r)}var wf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zb="comet-state.yaml",Jb="state.json",jI=Jr("en");function yf(e,t){if(!wf.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ti.join(e.changesDir,t);if(!F(e.changesDir,r))throw new Error("Native change path escaped");return r}function Is(e,t){return ti.join(yf(e,t),zb)}function Gb(e,t){return ti.join(nt(e,t),Jb)}async function Nf(e,t){try{let r=await ft.readFile(Is(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Ub(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function Kb(e){return K(e).currentBranch}function Yb(e,t){if(!t)return;let r=K(e);if(t.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function bf(e){return ue(e.paths,`create portable change ${e.name}`,async()=>{if(!wf.test(e.name))throw new Error(`Invalid Native change name: ${e.name}`);e.initialProjectConfig&&await W(e.paths.projectRoot)===null&&await Fr(e.paths.projectRoot,e.initialProjectConfig),Yb(e.paths.projectRoot,e.workspaceBinding);let t=(await uf(e.paths)).filter(o=>o!==e.name);if(t.length>0)throw new tr(e.workspaceBinding?.isolation??"current",t);let r=yf(e.paths,e.name),i=nt(e.paths,e.name);await Promise.all([_(e.paths.nativeRoot,r),_(e.paths.runtimeDir,i)]);let n=!1,a=!1;try{await ft.mkdir(e.paths.changesDir,{recursive:!0}),await ft.mkdir(r,{recursive:!1}),n=!0,await ft.mkdir(e.paths.changesRuntimeDir,{recursive:!0}),await ft.mkdir(i,{recursive:!1}),a=!0,await ft.mkdir(ti.join(r,"specs"),{recursive:!0}),await ne(ti.join(r,"brief.md"),Jr(e.language));let o=gd({name:e.name,language:e.language,workspace:Ub(e.workspaceBinding),createdAt:e.now,nextAction:"prepare-shape-confirmation"});return await wd(Is(e.paths,e.name),o,{containedRoot:e.paths.nativeRoot}),await gf(Gb(e.paths,e.name),vf({portableState:o,projectRoot:e.paths.projectRoot,branch:Kb(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o}catch(o){throw a&&await ft.rm(i,{recursive:!0,force:!0}),n&&await ft.rm(r,{recursive:!0,force:!0}),o}})}async function kf(e,t){return cs(Is(e,t))}import{randomUUID as Xb}from"crypto";import{promises as Zn}from"fs";import Ef from"path";var Ts="comet.selection.v2",BI=16*1024;function Cf(e){return Ef.join(e,".comet","current-change.json")}function Qb(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Sf(e){return e===null||typeof e=="string"}function Zb(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!Qb(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Sf(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Ts,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Ts)throw new Error(`current change selection schema must be ${Ts}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Sf(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function xf(e,t){let r=Zb(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=Cf(e),n=`${i}.${Xb()}.tmp`;await Zn.mkdir(Ef.dirname(i),{recursive:!0});try{await Zn.writeFile(n,`${JSON.stringify(r.selection,null,2)}
|
|
186
|
+
`,"utf8"),await Zn.rename(n,i)}catch(a){throw await Zn.rm(n,{force:!0}),a}}var KI=16*1024;async function Pf(e,t){return ue(e,`select change ${t}`,async()=>{Gn(t),await Nf(e,t)?await kf(e,t):await ut(e,t),await xf(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}import ii from"path";import{realpathSync as Jk}from"fs";var qe={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Rf(e){return e?e.command?`${qe.next} ${e.command}`:e.ask_user?`${qe.next} ${e.ask_user}`:null:null}function Af(e,t){let r=[e.summary],i=Rf(e.next);return i&&r.push(i),e.user_message&&r.push("",qe.relay,e.user_message),t!==void 0&&r.push("",qe.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
187
187
|
`)}
|
|
188
|
-
`}function
|
|
189
|
-
`)}var
|
|
190
|
-
`)}}let r=
|
|
191
|
-
comet native next <change-name> --
|
|
192
|
-
comet native
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
188
|
+
`}function _f(e,t,r){let i=[e.summary],n=Rf(e.next);return n&&i.push(n),e.user_message&&i.push("",qe.relay,e.user_message),i.push("",`${qe.detail} ${t}`),r!==void 0&&i.push("",qe.details,JSON.stringify(r,null,2)),i.join(`
|
|
189
|
+
`)}var ek=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 If=1024*1024;var jf="scoped-text-safety",tk=1,rk=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var ik="comet.native.checker-policy.v1";var bT=ee(ik,{policy:jf,version:tk,limits:rk,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var nk=["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"],kT=new Set(nk);var sk=If,BT=3*sk;var $f={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:[]},lk=re("comet-native-runtime:v3:scope-reopen"),fj=[{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 Hf=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],Jj=new Set(Hf),mk=new Set([...Hf,"minimum_runtime_version","revision"]),Gj=new Set([...mk,"operation"]),Uj=512*1024,vk=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Kj=new Set([...vk,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var e$={maxAcceptanceCriteria:pd.maxCriteria};var a$={maxSpecs:64,maxFileBytes:bn,maxTotalBytes:4*1024*1024};import{execFile as Ck}from"node:child_process";import{promisify as xk}from"node:util";var m$={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var H$=512*1024;var ri=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var aO=64*1024;var oO=3600*1e3;var sO=xk(Ck);var ea=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 JO={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var r0=16*1024*1024,i0=256*1024,n0=16*1024;var u0=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var eH=16*1024*1024,ta=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"},ra=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 js={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Bf(e,t){return typeof e=="string"&&js[e]?C(t,js[e].en,js[e].zh):typeof e=="string"?e:""}function $s(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 Tk(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 Vf(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 Mf(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 Os(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function jk(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 $k(e,t,r){let i=Os(e),n=[];r&&n.push(r);let a=C(i,`Change ${e.change}`,`需求 ${e.change}`),o=Bf(e.phase,i),s=jk(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Vf(t,i));let c=e.userCommunication,l=Ff(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Ff(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 Ok(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function Hk(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Bf(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=$s(e.acceptance)?`${C(t,", ",",")}${Vf(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function Dk(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 Lk(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 Bk(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=Vk(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 Vk(e){return Mf(e)?Ff(e,Os(e)):void 0}function qf(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(Lk(t))return Bk(t);if(Ok(t)){let i=Dk(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=>Hk(a,i))].join(`
|
|
190
|
+
`)}}let r=t.continuation;if(Mf(r))return $k(r,Mk(t),Fk(t,Os(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 Mk(e){if($s(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if($s(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return Tk(r.acceptance)}return null}function Fk(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 Wf(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 zf=["--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."],Ds=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:zf,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>]
|
|
191
|
+
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>]
|
|
192
|
+
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]
|
|
193
|
+
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 Hs(e,t){return`${e}:
|
|
194
|
+
${t.map(r=>` ${r}`).join(`
|
|
195
|
+
`)}`}function qk(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Ds[r]||t.length>1&&Ds[t[0]]?.subcommands?r:t[0]}function Wk(e=[]){let t=qk(e),r=Ds[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Hs("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...zf];return n&&n.length>0&&i.push("",Hs("Options",n)),i.push("",`Output:
|
|
196
|
+
${r.output}`),r.examples&&i.push("",Hs("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
196
197
|
`)}
|
|
197
|
-
`}}var
|
|
198
|
-
`}function
|
|
199
|
-
`}:
|
|
200
|
-
${
|
|
201
|
-
${JSON.stringify(
|
|
202
|
-
`}:{exitCode:
|
|
203
|
-
`)}async function
|
|
198
|
+
`}}var zk=Wk().usage;var NH=10*1024*1024,ke=class extends Error{};function Bs(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new ke(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function ht(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new ke(`${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 ke(`${t} requires a value`);return e.splice(i,2),n}function Gf(e){if(e.length>0)throw new ke(`Unexpected argument: ${e[0]}`)}function Uf(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new ke(`${t} is required`);return r}function Kf(e,t="en"){let r=ht(e,"--language")??t;if(r!=="en"&&r!=="zh-CN")throw new ke("--language must be en or zh-CN");return r}function Ls(e,t){let r=ii.normalize(Jf(e)),i=ii.normalize(Jf(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Jf(e){let t=ii.resolve(e);try{return Jk.native(t)}catch{return t}}function Gk(e){let t=ii.resolve(e),r=K(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=K(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Ls(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Ls(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Ls(process.cwd(),r.currentWorktreeRoot)?ii.resolve(process.cwd()):r.currentWorktreeRoot}async function Yf(e){return e?Gk(e):Ko(process.cwd())}function Xf(e){return JSON.stringify(e,null,2)+`
|
|
199
|
+
`}function Qf(e,t,r){return{command:e,exitCode:0,data:t,text:r??Xf(t)}}function Uk(e,t){if(t instanceof ke)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof ta)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 ra)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof zn)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 tr)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 dt)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Jn)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 ea)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ri)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 Zf(e,t){let r=Uk(e,t),i=r.error;if(!i)return r;let n=Wf({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function eh(e,t,r=!1){let i=e.envelope??qf(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}})+`
|
|
200
|
+
`}:e.error?{exitCode:e.exitCode,stderr:i?_f(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Af(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Xf(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
201
|
+
${qe.details}
|
|
202
|
+
${JSON.stringify(e.data,null,2)}
|
|
203
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}async function th(e,t){let r=Uf(e,"change name"),i=await W(t),n=Kf(e,i?.native.language??"en"),a=ht(e,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new ke("--isolation must be current, branch, or worktree");let o=ht(e,"--change-branch"),s=ht(e,"--target-branch"),c=ht(e,"--worktree-path");Gf(e);let l=i;if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let u=await Rs({projectRoot:t,name:r,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{},...c?{worktreePath:c}:{},sourceConfig:l});t=u.projectRoot,i=await W(t);let d=i===null?Uu("docs",n):void 0;if(i||(i=d),i.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let f=await Oe(t,i.native.artifact_root);await Ju(f);let p=await bf({paths:f,name:r,language:n,workspaceBinding:u.binding,...d?{initialProjectConfig:d}:{}});return await Pf(f,p.name),Qf("new",{...p,preparation:u.preparation,continuation:Qu(p)},`Created Native change ${p.name}
|
|
204
|
+
`)}async function rh(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{Bs(n,"--json"),Bs(n,"--verbose"),c=ht(n,"--project-root");let d=[...n,...a],f=await Yf(c);l=await t(d,f)}catch(d){l=Zf(e,d)}let u=eh(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
204
205
|
`)?"":`
|
|
205
|
-
`)),u.exitCode}process.exitCode=await
|
|
206
|
+
`)),u.exitCode}process.exitCode=await rh("new",th);
|