@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,77 +1,77 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`)}};
|
|
6
|
-
`)?
|
|
4
|
+
var hy=Object.create;var _d=Object.defineProperty;var my=Object.getOwnPropertyDescriptor;var vy=Object.getOwnPropertyNames;var gy=Object.getPrototypeOf,wy=Object.prototype.hasOwnProperty;var na=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var P=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var yy=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vy(t))!wy.call(e,n)&&n!==i&&_d(e,n,{get:()=>t[n],enumerable:!(r=my(t,n))||r.enumerable});return e};var jr=(e,t,i)=>(i=e!=null?hy(gy(e)):{},yy(t||!e||!e.__esModule?_d(i,"default",{value:e,enumerable:!0}):i,e));var F=P(fe=>{"use strict";var As=Symbol.for("yaml.alias"),Td=Symbol.for("yaml.document"),aa=Symbol.for("yaml.map"),jd=Symbol.for("yaml.pair"),_s=Symbol.for("yaml.scalar"),oa=Symbol.for("yaml.seq"),wt=Symbol.for("yaml.node.type"),Cy=e=>!!e&&typeof e=="object"&&e[wt]===As,xy=e=>!!e&&typeof e=="object"&&e[wt]===Td,Py=e=>!!e&&typeof e=="object"&&e[wt]===aa,Ry=e=>!!e&&typeof e=="object"&&e[wt]===jd,$d=e=>!!e&&typeof e=="object"&&e[wt]===_s,Ay=e=>!!e&&typeof e=="object"&&e[wt]===oa;function Od(e){if(e&&typeof e=="object")switch(e[wt]){case aa:case oa:return!0}return!1}function _y(e){if(e&&typeof e=="object")switch(e[wt]){case As:case aa:case _s:case oa:return!0}return!1}var Iy=e=>($d(e)||Od(e))&&!!e.anchor;fe.ALIAS=As;fe.DOC=Td;fe.MAP=aa;fe.NODE_TYPE=wt;fe.PAIR=jd;fe.SCALAR=_s;fe.SEQ=oa;fe.hasAnchor=Iy;fe.isAlias=Cy;fe.isCollection=Od;fe.isDocument=xy;fe.isMap=Py;fe.isNode=_y;fe.isPair=Ry;fe.isScalar=$d;fe.isSeq=Ay});var Hr=P(Is=>{"use strict";var ce=F(),ke=Symbol("break visit"),Hd=Symbol("skip children"),ot=Symbol("remove node");function sa(e,t){let i=Dd(t);ce.isDocument(e)?Li(null,e.contents,i,Object.freeze([e]))===ot&&(e.contents=null):Li(null,e,i,Object.freeze([]))}sa.BREAK=ke;sa.SKIP=Hd;sa.REMOVE=ot;function Li(e,t,i,r){let n=Ld(e,t,i,r);if(ce.isNode(n)||ce.isPair(n))return Bd(e,r,n),Li(e,n,i,r);if(typeof n!="symbol"){if(ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=Li(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ke)return ke;o===ot&&(t.items.splice(a,1),a-=1)}}}else if(ce.isPair(t)){r=Object.freeze(r.concat(t));let a=Li("key",t.key,i,r);if(a===ke)return ke;a===ot&&(t.key=null);let o=Li("value",t.value,i,r);if(o===ke)return ke;o===ot&&(t.value=null)}}return n}async function ca(e,t){let i=Dd(t);ce.isDocument(e)?await Bi(null,e.contents,i,Object.freeze([e]))===ot&&(e.contents=null):await Bi(null,e,i,Object.freeze([]))}ca.BREAK=ke;ca.SKIP=Hd;ca.REMOVE=ot;async function Bi(e,t,i,r){let n=await Ld(e,t,i,r);if(ce.isNode(n)||ce.isPair(n))return Bd(e,r,n),Bi(e,n,i,r);if(typeof n!="symbol"){if(ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await Bi(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ke)return ke;o===ot&&(t.items.splice(a,1),a-=1)}}}else if(ce.isPair(t)){r=Object.freeze(r.concat(t));let a=await Bi("key",t.key,i,r);if(a===ke)return ke;a===ot&&(t.key=null);let o=await Bi("value",t.value,i,r);if(o===ke)return ke;o===ot&&(t.value=null)}}return n}function Dd(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 Ld(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(ce.isMap(t))return i.Map?.(e,t,r);if(ce.isSeq(t))return i.Seq?.(e,t,r);if(ce.isPair(t))return i.Pair?.(e,t,r);if(ce.isScalar(t))return i.Scalar?.(e,t,r);if(ce.isAlias(t))return i.Alias?.(e,t,r)}function Bd(e,t,i){let r=t[t.length-1];if(ce.isCollection(r))r.items[e]=i;else if(ce.isPair(r))e==="key"?r.key=i:r.value=i;else if(ce.isDocument(r))r.contents=i;else{let n=ce.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Is.visit=sa;Is.visitAsync=ca});var Ts=P(Fd=>{"use strict";var Vd=F(),Ty=Hr(),jy={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},$y=e=>e.replace(/[!,[\]{}]/g,t=>jy[t]),Dr=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+$y(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&Vd.isNode(t.contents)){let a={};Ty.visit(t.contents,(o,s)=>{Vd.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
|
|
5
|
+
`)}};Dr.defaultYaml={explicit:!1,version:"1.2"};Dr.defaultTags={"!!":"tag:yaml.org,2002:"};Fd.Directives=Dr});var la=P(Lr=>{"use strict";var qd=F(),Oy=Hr();function Hy(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function Md(e){let t=new Set;return Oy.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Wd(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function Dy(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Md(e));let o=Wd(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(qd.isScalar(o.node)||qd.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:r}}Lr.anchorIsValid=Hy;Lr.anchorNames=Md;Lr.createNodeAnchors=Dy;Lr.findNewAnchor=Wd});var js=P(zd=>{"use strict";function Br(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=Br(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=Br(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=Br(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=Br(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}zd.applyReviver=Br});var Bt=P(Gd=>{"use strict";var Ly=F();function Jd(e,t,i){if(Array.isArray(e))return e.map((r,n)=>Jd(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!Ly.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}Gd.toJS=Jd});var ua=P(Kd=>{"use strict";var By=js(),Ud=F(),Vy=Bt(),$s=class{constructor(t){Object.defineProperty(this,Ud.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!Ud.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=Vy.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?By.applyReviver(a,{"":s},"",s):s}};Kd.NodeBase=$s});var Vr=P(Yd=>{"use strict";var Fy=la(),qy=Hr(),Vi=F(),My=ua(),Wy=Bt(),Os=class extends My.NodeBase{constructor(t){super(Vi.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],qy.visit(t,{Node:(a,o)=>{(Vi.isAlias(o)||Vi.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(Wy.toJS(o,null,i),s=r.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=da(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if(Fy.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 da(e,t,i){if(Vi.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Vi.isCollection(t)){let r=0;for(let n of t.items){let a=da(e,n,i);a>r&&(r=a)}return r}else if(Vi.isPair(t)){let r=da(e,t.key,i),n=da(e,t.value,i);return Math.max(r,n)}return 1}Yd.Alias=Os});var re=P(Hs=>{"use strict";var zy=F(),Jy=ua(),Gy=Bt(),Uy=e=>!e||typeof e!="function"&&typeof e!="object",Vt=class extends Jy.NodeBase{constructor(t){super(zy.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:Gy.toJS(this.value,t,i)}toString(){return String(this.value)}};Vt.BLOCK_FOLDED="BLOCK_FOLDED";Vt.BLOCK_LITERAL="BLOCK_LITERAL";Vt.PLAIN="PLAIN";Vt.QUOTE_DOUBLE="QUOTE_DOUBLE";Vt.QUOTE_SINGLE="QUOTE_SINGLE";Hs.Scalar=Vt;Hs.isScalarValue=Uy});var Fr=P(Qd=>{"use strict";var Ky=Vr(),Ni=F(),Xd=re(),Yy="tag:yaml.org,2002:";function Xy(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function Qy(e,t,i){if(Ni.isDocument(e)&&(e=e.contents),Ni.isNode(e))return e;if(Ni.isPair(e)){let d=i.schema[Ni.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Ky.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Yy+t.slice(2));let l=Xy(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Xd.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Ni.MAP]:Symbol.iterator in Object(e)?o[Ni.SEQ]:o[Ni.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new Xd.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Qd.createNode=Qy});var pa=P(fa=>{"use strict";var Zy=Fr(),st=F(),eN=ua();function Ds(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return Zy.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Zd=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Ls=class extends eN.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>st.isNode(r)||st.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Zd(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(st.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Ds(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(st.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&st.isScalar(a)?a.value:a:st.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!st.isPair(i))return!1;let r=i.value;return r==null||t&&st.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return st.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(st.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Ds(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};fa.Collection=Ls;fa.collectionFromPath=Ds;fa.isEmptyPath=Zd});var qr=P(ha=>{"use strict";var tN=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Bs(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var iN=(e,t,i)=>e.endsWith(`
|
|
6
|
+
`)?Bs(i,t):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)i===
|
|
10
|
-
`&&p!==" "){let
|
|
11
|
-
`&&
|
|
12
|
-
${t}${e.slice(0,E)}`:(i===
|
|
13
|
-
${t}${e.slice(
|
|
14
|
-
`);r=t,n=t+1,a=e[n]}return r}
|
|
15
|
-
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function
|
|
8
|
+
`+Bs(i,t):(e.endsWith(" ")?"":" ")+i;ha.indentComment=Bs;ha.lineComment=iN;ha.stringifyComment=tN});var tf=P(Mr=>{"use strict";var rN="flow",Vs="block",ma="quoted";function nN(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,p,v=!1,h=-1,m=-1,S=-1;i===Vs&&(h=ef(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(i===ma&&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}S=h}if(k===`
|
|
9
|
+
`)i===Vs&&(h=ef(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(k===" "&&p&&p!==" "&&p!==`
|
|
10
|
+
`&&p!==" "){let N=e[h+1];N&&N!==" "&&N!==`
|
|
11
|
+
`&&N!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===ma){for(;p===" "||p===" ";)p=k,k=e[h+=1],v=!0;let N=h>S+1?h-2:m-1;if(u[N])return e;l.push(N),u[N]=!0,d=N+c,f=void 0}else v=!0}p=k}if(v&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let N=l[k],E=l[k+1]||e.length;N===0?y=`
|
|
12
|
+
${t}${e.slice(0,E)}`:(i===ma&&u[N]&&(y+=`${e[N]}\\`),y+=`
|
|
13
|
+
${t}${e.slice(N+1,E)}`)}return y}function ef(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
+
`);r=t,n=t+1,a=e[n]}return r}Mr.FOLD_BLOCK=Vs;Mr.FOLD_FLOW=rN;Mr.FOLD_QUOTED=ma;Mr.foldFlowLines=nN});var zr=P(rf=>{"use strict";var Je=re(),Ft=tf(),ga=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),wa=e=>/^(%|---|\.\.\.)/m.test(e);function aN(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Wr(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(wa(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
20
|
-
${i}`)+"'";return t.implicitKey?r:
|
|
18
|
+
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:Ft.foldFlowLines(o,a,Ft.FOLD_QUOTED,ga(t,!1))}function Fs(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Wr(e,t);let i=t.indent||(wa(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return t.implicitKey?r:Ft.foldFlowLines(r,i,Ft.FOLD_FLOW,ga(t,!1))}function Fi(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=Wr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=Fs:a&&!n?r=Wr:r=i?Fs:Wr}return r(e,t)}var qs;try{qs=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{qs=/\n+(?!\n|$)/g}function va({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return Fi(i,r);let l=r.indent||(r.forceBlockIndent||wa(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Je.Scalar.BLOCK_FOLDED?!1:t===Je.Scalar.BLOCK_LITERAL?!0:!aN(i,c,l.length);if(!i)return u?`|
|
|
24
24
|
`:`>
|
|
25
25
|
`;let d,f;for(f=i.length;f>0;--f){let E=i[f-1];if(E!==`
|
|
26
26
|
`&&E!==" "&&E!==" ")break}let p=i.substring(f),v=p.indexOf(`
|
|
27
27
|
`);v===-1?d="-":i===p||v!==p.length-1?(d="+",a&&a()):d="",p&&(i=i.slice(0,-p.length),p[p.length-1]===`
|
|
28
|
-
`&&(p=p.slice(0,-1)),p=p.replace(
|
|
29
|
-
`)S=m;else break}let y=i.substring(0,S<m?S+1:m);y&&(i=i.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,x=
|
|
31
|
-
${l}${g}`}return i=i.replace(/\n+/g,`$&${l}`),`|${
|
|
32
|
-
${l}${y}${i}${p}`}function
|
|
33
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
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
|
|
37
|
-
${t.indent}${s}`:s}
|
|
38
|
-
${s}:`):(m=`${m}:`,f&&(m+=
|
|
28
|
+
`&&(p=p.slice(0,-1)),p=p.replace(qs,`$&${l}`));let h=!1,m,S=-1;for(m=0;m<i.length;++m){let E=i[m];if(E===" ")h=!0;else if(E===`
|
|
29
|
+
`)S=m;else break}let y=i.substring(0,S<m?S+1:m);y&&(i=i.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let N=(h?l?"2":"1":"")+d;if(e&&(N+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let E=i.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,x=ga(r,!0);o!=="folded"&&t!==Je.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{b=!0});let g=Ft.foldFlowLines(`${y}${E}${p}`,l,Ft.FOLD_BLOCK,x);if(!b)return`>${N}
|
|
31
|
+
${l}${g}`}return i=i.replace(/\n+/g,`$&${l}`),`|${N}
|
|
32
|
+
${l}${y}${i}${p}`}function oN(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
33
|
+
`)||u&&/[[\]{},]/.test(a))return Fi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
+
`)?Fi(a,t):va(e,t,i,r);if(!s&&!u&&n!==Je.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return va(e,t,i,r);if(wa(a)){if(c==="")return t.forceBlockIndent=!0,va(e,t,i,r);if(s&&c===l)return Fi(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 Fi(a,t)}return s?d:Ft.foldFlowLines(d,c,Ft.FOLD_FLOW,ga(t,!1))}function sN(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Je.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Je.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Je.Scalar.BLOCK_FOLDED:case Je.Scalar.BLOCK_LITERAL:return n||a?Fi(o.value,t):va(o,t,i,r);case Je.Scalar.QUOTE_DOUBLE:return Wr(o.value,t);case Je.Scalar.QUOTE_SINGLE:return Fs(o.value,t);case Je.Scalar.PLAIN:return oN(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}rf.stringifyString=sN});var Jr=P(Ms=>{"use strict";var cN=la(),qt=F(),lN=qr(),uN=zr();function dN(e,t){let i=Object.assign({blockQuote:!0,commentString:lN.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function fN(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(qt.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function pN(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(qt.isScalar(e)||qt.isCollection(e))&&e.anchor;a&&cN.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function hN(e,t,i,r){if(qt.isPair(e))return e.toString(t,i,r);if(qt.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=qt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=fN(t.doc.schema.tags,a));let o=pN(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):qt.isScalar(a)?uN.stringifyString(a,t,i,r):a.toString(t,i,r);return o?qt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}Ms.createStringifyContext=dN;Ms.stringify=hN});var sf=P(of=>{"use strict";var yt=F(),nf=re(),af=Jr(),Gr=qr();function mN({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=yt.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(yt.isCollection(e)||!yt.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!d&&(!e||f&&t==null&&!i.inFlow||yt.isCollection(e)||(yt.isScalar(e)?e.type===nf.Scalar.BLOCK_FOLDED||e.type===nf.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=af.stringify(e,i,()=>v=!0,()=>h=!0);if(!p&&!i.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(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=Gr.lineComment(m,i.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=Gr.lineComment(m,i.indent,l(f))),m=`? ${m}
|
|
38
|
+
${s}:`):(m=`${m}:`,f&&(m+=Gr.lineComment(m,i.indent,l(f))));let S,y,k;yt.isNode(t)?(S=!!t.spaceBefore,y=t.commentBefore,k=t.comment):(S=!1,y=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!f&&yt.isScalar(t)&&(i.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&yt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let N=!1,E=af.stringify(t,i,()=>N=!0,()=>h=!0),b=" ";if(f||S||y){if(b=S?`
|
|
39
39
|
`:"",y){let x=l(y);b+=`
|
|
40
|
-
${
|
|
41
|
-
`&&
|
|
40
|
+
${Gr.indentComment(x,i.indent)}`}E===""&&!i.inFlow?b===`
|
|
41
|
+
`&&k&&(b=`
|
|
42
42
|
|
|
43
43
|
`):b+=`
|
|
44
44
|
${i.indent}`}else if(!p&&yt.isCollection(t)){let x=E[0],g=E.indexOf(`
|
|
45
45
|
`),w=g!==-1,C=i.inFlow??t.flow??t.items.length===0;if(w||!C){let O=!1;if(w&&(x==="&"||x==="!")){let T=E.indexOf(" ");x==="&"&&T!==-1&&T<g&&E[T+1]==="!"&&(T=E.indexOf(" ",T+1)),(T===-1||g<T)&&(O=!0)}O||(b=`
|
|
46
46
|
${i.indent}`)}}else(E===""||E[0]===`
|
|
47
|
-
`)&&(b="");return m+=b+E,i.inFlow?
|
|
47
|
+
`)&&(b="");return m+=b+E,i.inFlow?N&&r&&r():k&&!N?m+=Gr.lineComment(m,i.indent,l(k)):h&&n&&n(),m}of.stringifyPair=mN});var zs=P(Ws=>{"use strict";var cf=na("process");function vN(e,...t){e==="debug"&&console.log(...t)}function gN(e,t){(e==="debug"||e==="warn")&&(typeof cf.emitWarning=="function"?cf.emitWarning(t):console.warn(t))}Ws.debug=vN;Ws.warn=gN});var Sa=P(ka=>{"use strict";var ba=F(),lf=re(),ya="<<",Na={identify:e=>e===ya||typeof e=="symbol"&&e.description===ya,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new lf.Scalar(Symbol(ya)),{addToJSMap:uf}),stringify:()=>ya},wN=(e,t)=>(Na.identify(t)||ba.isScalar(t)&&(!t.type||t.type===lf.Scalar.PLAIN)&&Na.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Na.tag&&i.default);function uf(e,t,i){let r=df(e,i);if(ba.isSeq(r))for(let n of r.items)Js(e,t,n);else if(Array.isArray(r))for(let n of r)Js(e,t,n);else Js(e,t,r)}function Js(e,t,i){let r=df(e,i);if(!ba.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function df(e,t){return e&&ba.isAlias(t)?t.resolve(e.doc,e):t}ka.addMergeToJSMap=uf;ka.isMergeKey=wN;ka.merge=Na});var Us=P(hf=>{"use strict";var yN=zs(),ff=Sa(),NN=Jr(),pf=F(),Gs=Bt();function bN(e,t,{key:i,value:r}){if(pf.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(ff.isMergeKey(e,i))ff.addMergeToJSMap(e,t,r);else{let n=Gs.toJS(i,"",e);if(t instanceof Map)t.set(n,Gs.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=kN(i,n,e),o=Gs.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function kN(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(pf.isNode(e)&&i?.doc){let r=NN.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),yN.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}hf.addPairToJSMap=bN});var Mt=P(Ks=>{"use strict";var mf=Fr(),SN=sf(),EN=Us(),Ea=F();function CN(e,t,i){let r=mf.createNode(e,void 0,i),n=mf.createNode(t,void 0,i);return new Ca(r,n)}var Ca=class e{constructor(t,i=null){Object.defineProperty(this,Ea.NODE_TYPE,{value:Ea.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return Ea.isNode(i)&&(i=i.clone(t)),Ea.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return EN.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?SN.stringifyPair(this,t,i,r):JSON.stringify(this)}};Ks.Pair=Ca;Ks.createPair=CN});var Ys=P(gf=>{"use strict";var bi=F(),vf=Jr(),xa=qr();function xN(e,t,i){return(t.inFlow??e.flow?RN:PN)(e,t,i)}function PN({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(bi.isNode(h))!d&&h.spaceBefore&&f.push(""),Pa(i,f,h.commentBefore,d),h.comment&&(m=h.comment);else if(bi.isPair(h)){let y=bi.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&f.push(""),Pa(i,f,y.commentBefore,d))}d=!1;let S=vf.stringify(h,u,()=>m=null,()=>d=!0);m&&(S+=xa.lineComment(S,a,l(m))),d&&m&&(d=!1),f.push(r+S)}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
48
|
${c}${h}`:`
|
|
49
49
|
`}}return e?(p+=`
|
|
50
|
-
`+
|
|
51
|
-
`)),v<e.length-1?S+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,
|
|
50
|
+
`+xa.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function RN({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(bi.isNode(h))h.spaceBefore&&d.push(""),Pa(t,d,h.commentBefore,!1),h.comment&&(m=h.comment);else if(bi.isPair(h)){let y=bi.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),Pa(t,d,y.commentBefore,!1),y.comment&&(l=!0));let k=bi.isNode(h.value)?h.value:null;k?(k.comment&&(m=k.comment),k.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(m=y.comment)}m&&(l=!0);let S=vf.stringify(h,c,()=>m=null);l||(l=d.length>u||S.includes(`
|
|
51
|
+
`)),v<e.length-1?S+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,k)=>y+k.length+2,2)+(S.length+2)>t.options.lineWidth)),l&&(S+=",")),m&&(S+=xa.lineComment(S,r,s(m))),d.push(S),u=d.length}let{start:f,end:p}=i;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
52
|
${a}${n}${h}`:`
|
|
53
53
|
`;return`${v}
|
|
54
|
-
${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function
|
|
55
|
-
`:" ")}return
|
|
54
|
+
${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Pa({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=xa.indentComment(t(r),e);i.push(a.trimStart())}}gf.stringifyCollection=xN});var zt=P(Qs=>{"use strict";var AN=Ys(),_N=Us(),IN=pa(),Wt=F(),Ra=Mt(),TN=re();function Ur(e,t){let i=Wt.isScalar(t)?t.value:t;for(let r of e)if(Wt.isPair(r)&&(r.key===t||r.key===i||Wt.isScalar(r.key)&&r.key.value===i))return r}var Xs=class extends IN.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Wt.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Ra.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;Wt.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Ra.Pair(t,t?.value):r=new Ra.Pair(t.key,t.value);let n=Ur(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Wt.isScalar(n.value)&&TN.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=Ur(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Ur(this.items,t)?.value;return(!i&&Wt.isScalar(n)?n.value:n)??void 0}has(t){return!!Ur(this.items,t)}set(t,i){this.add(new Ra.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)_N.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Wt.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})),AN.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Qs.YAMLMap=Xs;Qs.findPair=Ur});var qi=P(yf=>{"use strict";var jN=F(),wf=zt(),$N={collection:"map",default:!0,nodeClass:wf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return jN.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>wf.YAMLMap.from(e,t,i)};yf.map=$N});var Jt=P(Nf=>{"use strict";var ON=Fr(),HN=Ys(),DN=pa(),_a=F(),LN=re(),BN=Bt(),Zs=class extends DN.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(_a.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Aa(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Aa(t);if(typeof r!="number")return;let n=this.items[r];return!i&&_a.isScalar(n)?n.value:n}has(t){let i=Aa(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Aa(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];_a.isScalar(n)&&LN.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(BN.toJS(a,String(n++),i));return r}toString(t,i,r){return t?HN.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(ON.createNode(s,void 0,r))}}return a}};function Aa(e){let t=_a.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Nf.YAMLSeq=Zs});var Mi=P(kf=>{"use strict";var VN=F(),bf=Jt(),FN={collection:"seq",default:!0,nodeClass:bf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return VN.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>bf.YAMLSeq.from(e,t,i)};kf.seq=FN});var Kr=P(Sf=>{"use strict";var qN=zr(),MN={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),qN.stringifyString(e,t,i,r)}};Sf.string=MN});var Ia=P(xf=>{"use strict";var Ef=re(),Cf={identify:e=>e==null,createNode:()=>new Ef.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ef.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Cf.test.test(e)?e:t.options.nullStr};xf.nullTag=Cf});var ec=P(Rf=>{"use strict";var WN=re(),Pf={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new WN.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Pf.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};Rf.boolTag=Pf});var Wi=P(Af=>{"use strict";function zN({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Af.stringifyNumber=zN});var ic=P(Ta=>{"use strict";var JN=re(),tc=Wi(),GN={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:tc.stringifyNumber},UN={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():tc.stringifyNumber(e)}},KN={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 JN.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:tc.stringifyNumber};Ta.float=KN;Ta.floatExp=UN;Ta.floatNaN=GN});var nc=P($a=>{"use strict";var _f=Wi(),ja=e=>typeof e=="bigint"||Number.isInteger(e),rc=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function If(e,t,i){let{value:r}=e;return ja(r)&&r>=0?i+r.toString(t):_f.stringifyNumber(e)}var YN={identify:e=>ja(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>rc(e,2,8,i),stringify:e=>If(e,8,"0o")},XN={identify:ja,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>rc(e,0,10,i),stringify:_f.stringifyNumber},QN={identify:e=>ja(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>rc(e,2,16,i),stringify:e=>If(e,16,"0x")};$a.int=XN;$a.intHex=QN;$a.intOct=YN});var jf=P(Tf=>{"use strict";var ZN=qi(),eb=Ia(),tb=Mi(),ib=Kr(),rb=ec(),ac=ic(),oc=nc(),nb=[ZN.map,tb.seq,ib.string,eb.nullTag,rb.boolTag,oc.intOct,oc.int,oc.intHex,ac.floatNaN,ac.floatExp,ac.float];Tf.schema=nb});var Hf=P(Of=>{"use strict";var ab=re(),ob=qi(),sb=Mi();function $f(e){return typeof e=="bigint"||Number.isInteger(e)}var Oa=({value:e})=>JSON.stringify(e),cb=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Oa},{identify:e=>e==null,createNode:()=>new ab.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Oa},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Oa},{identify:$f,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>$f(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:Oa}],lb={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},ub=[ob.map,sb.seq].concat(cb,lb);Of.schema=ub});var cc=P(Df=>{"use strict";var Yr=na("buffer"),sc=re(),db=zr(),fb={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Yr.Buffer=="function")return Yr.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof Yr.Buffer=="function")s=o instanceof Yr.Buffer?o.toString("base64"):Yr.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=sc.Scalar.BLOCK_LITERAL),t!==sc.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===sc.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return db.stringifyString({comment:e,type:t,value:s},r,n,a)}};Df.binary=fb});var La=P(Da=>{"use strict";var Ha=F(),lc=Mt(),pb=re(),hb=Jt();function Lf(e,t){if(Ha.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!Ha.isPair(r)){if(Ha.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new lc.Pair(new pb.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
|
|
56
56
|
${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
|
|
57
|
-
${a.comment}`:r.comment}r=n}e.items[i]=$a.isPair(r)?r:new ic.Pair(r)}}else t("Expected a sequence for this tag");return e}function Of(e,t,i){let{replacer:r}=i,n=new sb.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(ic.createPair(s,c,i))}return n}var cb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:$f,createNode:Of};Oa.createPairs=Of;Oa.pairs=cb;Oa.resolvePairs=$f});var ac=P(nc=>{"use strict";var Hf=F(),rc=Lt(),Jr=Wt(),lb=zt(),Df=Ha(),Ni=class e extends lb.YAMLSeq{constructor(){super(),this.add=Jr.YAMLMap.prototype.add.bind(this),this.delete=Jr.YAMLMap.prototype.delete.bind(this),this.get=Jr.YAMLMap.prototype.get.bind(this),this.has=Jr.YAMLMap.prototype.has.bind(this),this.set=Jr.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(Hf.isPair(n)?(a=rc.toJS(n.key,"",i),o=rc.toJS(n.value,a,i)):a=rc.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=Df.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Ni.tag="tag:yaml.org,2002:omap";var ub={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ni,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Df.resolvePairs(e,t),r=[];for(let{key:n}of i.items)Hf.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Ni,i)},createNode:(e,t,i)=>Ni.from(e,t,i)};nc.YAMLOMap=Ni;nc.omap=ub});var qf=P(oc=>{"use strict";var Lf=re();function Bf({value:e,source:t},i){return t&&(e?Vf:Ff).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Vf={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 Lf.Scalar(!0),stringify:Bf},Ff={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 Lf.Scalar(!1),stringify:Bf};oc.falseTag=Ff;oc.trueTag=Vf});var Mf=P(Da=>{"use strict";var db=re(),sc=Fi(),fb={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:sc.stringifyNumber},pb={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():sc.stringifyNumber(e)}},hb={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 db.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:sc.stringifyNumber};Da.float=hb;Da.floatExp=pb;Da.floatNaN=fb});var zf=P(Ur=>{"use strict";var Wf=Fi(),Gr=e=>typeof e=="bigint"||Number.isInteger(e);function La(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function cc(e,t,i){let{value:r}=e;if(Gr(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Wf.stringifyNumber(e)}var mb={identify:Gr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>La(e,2,2,i),stringify:e=>cc(e,2,"0b")},vb={identify:Gr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>La(e,1,8,i),stringify:e=>cc(e,8,"0")},gb={identify:Gr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>La(e,0,10,i),stringify:Wf.stringifyNumber},wb={identify:Gr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>La(e,2,16,i),stringify:e=>cc(e,16,"0x")};Ur.int=gb;Ur.intBin=mb;Ur.intHex=wb;Ur.intOct=vb});var uc=P(lc=>{"use strict";var Fa=F(),Ba=qt(),Va=Wt(),bi=class e extends Va.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Fa.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Ba.Pair(t.key,null):i=new Ba.Pair(t,null),Va.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Va.findPair(this.items,t);return!i&&Fa.isPair(r)?Fa.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Va.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Ba.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Ba.createPair(o,null,r));return a}};bi.tag="tag:yaml.org,2002:set";var yb={collection:"map",identify:e=>e instanceof Set,nodeClass:bi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>bi.from(e,t,i),resolve(e,t){if(Fa.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new bi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};lc.YAMLSet=bi;lc.set=yb});var fc=P(qa=>{"use strict";var Nb=Fi();function dc(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Jf(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Nb.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var bb={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>dc(e,i),stringify:Jf},kb={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=>dc(e,!1),stringify:Jf},Gf={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(Gf.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=dc(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$/,"")??""};qa.floatTime=kb;qa.intTime=bb;qa.timestamp=Gf});var Yf=P(Kf=>{"use strict";var Sb=Bi(),Eb=Aa(),Cb=Vi(),xb=Wr(),Pb=tc(),Uf=qf(),pc=Mf(),Ma=zf(),Rb=ba(),Ab=ac(),_b=Ha(),Ib=uc(),hc=fc(),Tb=[Sb.map,Cb.seq,xb.string,Eb.nullTag,Uf.trueTag,Uf.falseTag,Ma.intBin,Ma.intOct,Ma.int,Ma.intHex,pc.floatNaN,pc.floatExp,pc.float,Pb.binary,Rb.merge,Ab.omap,_b.pairs,Ib.set,hc.intTime,hc.floatTime,hc.timestamp];Kf.schema=Tb});var op=P(gc=>{"use strict";var ep=Bi(),jb=Aa(),tp=Vi(),$b=Wr(),Ob=Gs(),mc=Ks(),vc=Xs(),Hb=Af(),Db=Tf(),ip=tc(),Kr=ba(),rp=ac(),np=Ha(),Xf=Yf(),ap=uc(),Wa=fc(),Qf=new Map([["core",Hb.schema],["failsafe",[ep.map,tp.seq,$b.string]],["json",Db.schema],["yaml11",Xf.schema],["yaml-1.1",Xf.schema]]),Zf={binary:ip.binary,bool:Ob.boolTag,float:mc.float,floatExp:mc.floatExp,floatNaN:mc.floatNaN,floatTime:Wa.floatTime,int:vc.int,intHex:vc.intHex,intOct:vc.intOct,intTime:Wa.intTime,map:ep.map,merge:Kr.merge,null:jb.nullTag,omap:rp.omap,pairs:np.pairs,seq:tp.seq,set:ap.set,timestamp:Wa.timestamp},Lb={"tag:yaml.org,2002:binary":ip.binary,"tag:yaml.org,2002:merge":Kr.merge,"tag:yaml.org,2002:omap":rp.omap,"tag:yaml.org,2002:pairs":np.pairs,"tag:yaml.org,2002:set":ap.set,"tag:yaml.org,2002:timestamp":Wa.timestamp};function Bb(e,t,i){let r=Qf.get(t);if(r&&!e)return i&&!r.includes(Kr.merge)?r.concat(Kr.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Qf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(Kr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Zf[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Zf).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},[])}gc.coreKnownTags=Lb;gc.getTags=Bb});var Nc=P(sp=>{"use strict";var wc=F(),Vb=Bi(),Fb=Vi(),qb=Wr(),za=op(),Mb=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,yc=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?za.getTags(t,"compat"):t?za.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?za.coreKnownTags:{},this.tags=za.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,wc.MAP,{value:Vb.map}),Object.defineProperty(this,wc.SCALAR,{value:qb.string}),Object.defineProperty(this,wc.SEQ,{value:Fb.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Mb:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};sp.Schema=yc});var lp=P(cp=>{"use strict";var Wb=F(),bc=Fr(),Yr=Dr();function zb(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=bc.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Yr.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Wb.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Yr.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=bc.stringify(e.contents,n,()=>s=null,c);s&&(l+=Yr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(bc.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
-
`)?(i.push("..."),i.push(
|
|
57
|
+
${a.comment}`:r.comment}r=n}e.items[i]=Ha.isPair(r)?r:new lc.Pair(r)}}else t("Expected a sequence for this tag");return e}function Bf(e,t,i){let{replacer:r}=i,n=new hb.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(lc.createPair(s,c,i))}return n}var mb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Lf,createNode:Bf};Da.createPairs=Bf;Da.pairs=mb;Da.resolvePairs=Lf});var fc=P(dc=>{"use strict";var Vf=F(),uc=Bt(),Xr=zt(),vb=Jt(),Ff=La(),ki=class e extends vb.YAMLSeq{constructor(){super(),this.add=Xr.YAMLMap.prototype.add.bind(this),this.delete=Xr.YAMLMap.prototype.delete.bind(this),this.get=Xr.YAMLMap.prototype.get.bind(this),this.has=Xr.YAMLMap.prototype.has.bind(this),this.set=Xr.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(Vf.isPair(n)?(a=uc.toJS(n.key,"",i),o=uc.toJS(n.value,a,i)):a=uc.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=Ff.createPairs(t,i,r),a=new this;return a.items=n.items,a}};ki.tag="tag:yaml.org,2002:omap";var gb={collection:"seq",identify:e=>e instanceof Map,nodeClass:ki,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Ff.resolvePairs(e,t),r=[];for(let{key:n}of i.items)Vf.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new ki,i)},createNode:(e,t,i)=>ki.from(e,t,i)};dc.YAMLOMap=ki;dc.omap=gb});var Jf=P(pc=>{"use strict";var qf=re();function Mf({value:e,source:t},i){return t&&(e?Wf:zf).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Wf={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 qf.Scalar(!0),stringify:Mf},zf={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 qf.Scalar(!1),stringify:Mf};pc.falseTag=zf;pc.trueTag=Wf});var Gf=P(Ba=>{"use strict";var wb=re(),hc=Wi(),yb={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:hc.stringifyNumber},Nb={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():hc.stringifyNumber(e)}},bb={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 wb.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:hc.stringifyNumber};Ba.float=bb;Ba.floatExp=Nb;Ba.floatNaN=yb});var Kf=P(Zr=>{"use strict";var Uf=Wi(),Qr=e=>typeof e=="bigint"||Number.isInteger(e);function Va(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function mc(e,t,i){let{value:r}=e;if(Qr(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Uf.stringifyNumber(e)}var kb={identify:Qr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Va(e,2,2,i),stringify:e=>mc(e,2,"0b")},Sb={identify:Qr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Va(e,1,8,i),stringify:e=>mc(e,8,"0")},Eb={identify:Qr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Va(e,0,10,i),stringify:Uf.stringifyNumber},Cb={identify:Qr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Va(e,2,16,i),stringify:e=>mc(e,16,"0x")};Zr.int=Eb;Zr.intBin=kb;Zr.intHex=Cb;Zr.intOct=Sb});var gc=P(vc=>{"use strict";var Ma=F(),Fa=Mt(),qa=zt(),Si=class e extends qa.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Ma.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Fa.Pair(t.key,null):i=new Fa.Pair(t,null),qa.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=qa.findPair(this.items,t);return!i&&Ma.isPair(r)?Ma.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=qa.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Fa.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Fa.createPair(o,null,r));return a}};Si.tag="tag:yaml.org,2002:set";var xb={collection:"map",identify:e=>e instanceof Set,nodeClass:Si,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Si.from(e,t,i),resolve(e,t){if(Ma.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Si,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};vc.YAMLSet=Si;vc.set=xb});var yc=P(Wa=>{"use strict";var Pb=Wi();function wc(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Yf(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Pb.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Rb={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>wc(e,i),stringify:Yf},Ab={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=>wc(e,!1),stringify:Yf},Xf={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(Xf.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=wc(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$/,"")??""};Wa.floatTime=Ab;Wa.intTime=Rb;Wa.timestamp=Xf});var ep=P(Zf=>{"use strict";var _b=qi(),Ib=Ia(),Tb=Mi(),jb=Kr(),$b=cc(),Qf=Jf(),Nc=Gf(),za=Kf(),Ob=Sa(),Hb=fc(),Db=La(),Lb=gc(),bc=yc(),Bb=[_b.map,Tb.seq,jb.string,Ib.nullTag,Qf.trueTag,Qf.falseTag,za.intBin,za.intOct,za.int,za.intHex,Nc.floatNaN,Nc.floatExp,Nc.float,$b.binary,Ob.merge,Hb.omap,Db.pairs,Lb.set,bc.intTime,bc.floatTime,bc.timestamp];Zf.schema=Bb});var up=P(Ec=>{"use strict";var np=qi(),Vb=Ia(),ap=Mi(),Fb=Kr(),qb=ec(),kc=ic(),Sc=nc(),Mb=jf(),Wb=Hf(),op=cc(),en=Sa(),sp=fc(),cp=La(),tp=ep(),lp=gc(),Ja=yc(),ip=new Map([["core",Mb.schema],["failsafe",[np.map,ap.seq,Fb.string]],["json",Wb.schema],["yaml11",tp.schema],["yaml-1.1",tp.schema]]),rp={binary:op.binary,bool:qb.boolTag,float:kc.float,floatExp:kc.floatExp,floatNaN:kc.floatNaN,floatTime:Ja.floatTime,int:Sc.int,intHex:Sc.intHex,intOct:Sc.intOct,intTime:Ja.intTime,map:np.map,merge:en.merge,null:Vb.nullTag,omap:sp.omap,pairs:cp.pairs,seq:ap.seq,set:lp.set,timestamp:Ja.timestamp},zb={"tag:yaml.org,2002:binary":op.binary,"tag:yaml.org,2002:merge":en.merge,"tag:yaml.org,2002:omap":sp.omap,"tag:yaml.org,2002:pairs":cp.pairs,"tag:yaml.org,2002:set":lp.set,"tag:yaml.org,2002:timestamp":Ja.timestamp};function Jb(e,t,i){let r=ip.get(t);if(r&&!e)return i&&!r.includes(en.merge)?r.concat(en.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(ip.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(en.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?rp[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(rp).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},[])}Ec.coreKnownTags=zb;Ec.getTags=Jb});var Pc=P(dp=>{"use strict";var Cc=F(),Gb=qi(),Ub=Mi(),Kb=Kr(),Ga=up(),Yb=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,xc=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Ga.getTags(t,"compat"):t?Ga.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ga.coreKnownTags:{},this.tags=Ga.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Cc.MAP,{value:Gb.map}),Object.defineProperty(this,Cc.SCALAR,{value:Kb.string}),Object.defineProperty(this,Cc.SEQ,{value:Ub.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Yb:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};dp.Schema=xc});var pp=P(fp=>{"use strict";var Xb=F(),Rc=Jr(),tn=qr();function Qb(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=Rc.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(tn.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Xb.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(tn.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Rc.stringify(e.contents,n,()=>s=null,c);s&&(l+=tn.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Rc.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
+
`)?(i.push("..."),i.push(tn.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(tn.indentComment(a(c),"")))}return i.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}fp.stringifyDocument=Qb});var rn=P(hp=>{"use strict";var Zb=Vr(),zi=pa(),je=F(),ek=Mt(),tk=Bt(),ik=Pc(),rk=pp(),Ac=la(),nk=js(),ak=Fr(),_c=Ts(),Ic=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,je.NODE_TYPE,{value:je.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new _c.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[je.NODE_TYPE]:{value:je.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=je.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ji(this.contents)&&this.contents.add(t)}addIn(t,i){Ji(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=Ac.anchorNames(this);t.anchor=!i||r.has(i)?Ac.findNewAnchor(i||"a",r):i}return new Zb.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,S=i.filter(m).map(String);S.length>0&&(i=i.concat(S)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Ac.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=ak.createNode(t,u,v);return s&&je.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new ek.Pair(n,a)}delete(t){return Ji(this.contents)?this.contents.delete(t):!1}deleteIn(t){return zi.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ji(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return je.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return zi.isEmptyPath(t)?!i&&je.isScalar(this.contents)?this.contents.value:this.contents:je.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return je.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return zi.isEmptyPath(t)?this.contents!==void 0:je.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=zi.collectionFromPath(this.schema,[t],i):Ji(this.contents)&&this.contents.set(t,i)}setIn(t,i){zi.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=zi.collectionFromPath(this.schema,Array.from(t),i):Ji(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new _c.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new _c.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new ik.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=tk.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?nk.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return rk.stringifyDocument(this,t)}};function Ji(e){if(je.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}hp.Document=Ic});var on=P(an=>{"use strict";var nn=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},Tc=class extends nn{constructor(t,i,r){super("YAMLParseError",t,i,r)}},jc=class extends nn{constructor(t,i,r){super("YAMLWarning",t,i,r)}},ok=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};
|
|
66
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(
|
|
67
|
-
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||
|
|
68
|
-
`+
|
|
69
|
-
`+b.comment:l.comment=b.comment),d=b.end;continue}!o&&i.options.strict&&
|
|
70
|
-
`+x:g.comment=x,b.comment=b.comment.substring(x.length+1)}}if(!o&&!
|
|
71
|
-
`+w.comment:g.comment=w.comment);let O=new
|
|
72
|
-
`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}
|
|
65
|
+
`}};an.YAMLError=nn;an.YAMLParseError=Tc;an.YAMLWarning=jc;an.prettifyError=ok});var sn=P(mp=>{"use strict";function sk(e,{flow:t,indicator:i,next:r,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,S=null,y=null,k=null,N=null,E=null;for(let g of e)switch(v&&(g.type!=="space"&&g.type!=="newline"&&g.type!=="comma"&&a(g.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&g.type!=="comment"&&g.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),g.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&g.source.includes(" ")&&(h=g),u=!0;break;case"comment":{u||a(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=g.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=g.source:(!N||i!=="seq-item-ind")&&(c=!0):f+=g.source,l=!0,p=!0,(m||S)&&(y=g),u=!0;break;case"anchor":m&&a(g,"MULTIPLE_ANCHORS","A node can have at most one anchor"),g.source.endsWith(":")&&a(g.offset+g.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=g,E??(E=g.offset),l=!1,u=!1,v=!0;break;case"tag":{S&&a(g,"MULTIPLE_TAGS","A node can have at most one tag"),S=g,E??(E=g.offset),l=!1,u=!1,v=!0;break}case i:(m||S)&&a(g,"BAD_PROP_ORDER",`Anchors and tags must be after the ${g.source} indicator`),N&&a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.source} in ${t??"collection"}`),N=g,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(g,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=g,l=!1,u=!1;break}default:a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.type} token`),l=!1,u=!1}let b=e[e.length-1],x=b?b.offset+b.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:N,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:S,newlineAfterProp:y,end:x,start:E??x}}mp.resolveProps=sk});var Ua=P(vp=>{"use strict";function $c(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if($c(t.key)||$c(t.value))return!0}return!1;default:return!0}}vp.containsNewline=$c});var Oc=P(gp=>{"use strict";var ck=Ua();function lk(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&ck.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}gp.flowIndentCheck=lk});var Hc=P(yp=>{"use strict";var wp=F();function uk(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||wp.isScalar(a)&&wp.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}yp.mapIncludes=uk});var Cp=P(Ep=>{"use strict";var Np=Mt(),dk=zt(),bp=sn(),fk=Ua(),kp=Oc(),pk=Hc(),Sp="All mapping items must start at the same column";function hk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??dk.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:p,value:v}=u,h=bp.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:n,parentIndent:r.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!==r.indent&&n(c,"BAD_INDENT",Sp)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||fk.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",Sp);i.atKey=!0;let S=h.end,y=f?e(i,f,h,n):t(i,S,d,null,h,n);i.schema.compat&&kp.flowIndentCheck(r.indent,f,n),i.atKey=!1,pk.mapIncludes(i,s.items,y)&&n(S,"DUPLICATE_KEY","Map keys must be unique");let k=bp.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.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"),i.options.strict&&h.start<k.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let N=v?e(i,v,k,n):t(i,c,p,null,k,n);i.schema.compat&&kp.flowIndentCheck(r.indent,v,n),c=N.range[2];let E=new Np.Pair(y,N);i.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{m&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(y.comment?y.comment+=`
|
|
68
|
+
`+k.comment:y.comment=k.comment);let N=new Np.Pair(y);i.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}Ep.resolveBlockMap=hk});var Pp=P(xp=>{"use strict";var mk=Jt(),vk=sn(),gk=Oc();function wk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??mk.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=vk.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&gk.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}xp.resolveBlockSeq=wk});var Gi=P(Rp=>{"use strict";function yk(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Rp.resolveEnd=yk});var Tp=P(Ip=>{"use strict";var Nk=F(),bk=Mt(),Ap=zt(),kk=Jt(),Sk=Gi(),_p=sn(),Ek=Ua(),Ck=Hc(),Dc="Block collections are not allowed within flow collections",Lc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function xk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Ap.YAMLMap:kk.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let S=r.items[m],{start:y,key:k,sep:N,value:E}=S,b=_p.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:k??N?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!N&&!E){m===0&&b.comma?n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(b.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),b.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+b.comment:l.comment=b.comment),d=b.end;continue}!o&&i.options.strict&&Ek.containsNewline(k)&&n(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)b.comma&&n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(b.comma||n(b.start,"MISSING_CHAR",`Missing , between ${s} items`),b.comment){let x="";e:for(let g of y)switch(g.type){case"comma":case"space":break;case"comment":x=g.source.substring(1);break e;default:break e}if(x){let g=l.items[l.items.length-1];Nk.isPair(g)&&(g=g.value??g.key),g.comment?g.comment+=`
|
|
70
|
+
`+x:g.comment=x,b.comment=b.comment.substring(x.length+1)}}if(!o&&!N&&!b.found){let x=E?e(i,E,b,n):t(i,b.end,N,null,b,n);l.items.push(x),d=x.range[2],Lc(E)&&n(x.range,"BLOCK_IN_FLOW",Dc)}else{i.atKey=!0;let x=b.end,g=k?e(i,k,b,n):t(i,x,y,null,b,n);Lc(k)&&n(g.range,"BLOCK_IN_FLOW",Dc),i.atKey=!1;let w=_p.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:E,offset:g.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(w.found){if(!o&&!b.found&&i.options.strict){if(N)for(let T of N){if(T===w.found)break;if(T.type==="newline"){n(T,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.start<w.found.offset-1024&&n(w.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(w.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=E?e(i,E,w,n):w.found?t(i,w.end,N,null,w,n):null;C?Lc(E)&&n(C.range,"BLOCK_IN_FLOW",Dc):w.comment&&(g.comment?g.comment+=`
|
|
71
|
+
`+w.comment:g.comment=w.comment);let O=new bk.Pair(g,C);if(i.options.keepSourceTokens&&(O.srcToken=S),o){let T=l;Ck.mapIncludes(i,T.items,g)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),T.items.push(O)}else{let T=new Ap.YAMLMap(i.schema);T.flow=!0,T.items.push(O);let he=(C??g).range;T.range=[g.range[0],he[1],he[2]],l.items.push(T)}d=C?C.range[2]:w.end}}let f=o?"}":"]",[p,...v]=r.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),S=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",S),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=Sk.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}Ip.resolveFlowCollection=xk});var $p=P(jp=>{"use strict";var Pk=F(),Rk=re(),Ak=zt(),_k=Jt(),Ik=Cp(),Tk=Pp(),jk=Tp();function Bc(e,t,i,r,n,a){let o=i.type==="block-map"?Ik.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?Tk.resolveBlockSeq(e,t,i,r,a):jk.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function $k(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,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=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===Ak.YAMLMap.tagName&&s==="map"||o===_k.YAMLSeq.tagName&&s==="seq")return Bc(e,t,i,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Bc(e,t,i,n,o)}let l=Bc(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=Pk.isNode(u)?u:new Rk.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}jp.composeCollection=$k});var Fc=P(Op=>{"use strict";var Vc=re();function Ok(e,t,i){let r=t.offset,n=Hk(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Vc.Scalar.BLOCK_FOLDED:Vc.Scalar.BLOCK_LITERAL,o=t.source?Dk(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
73
|
`.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return t.source&&(m+=t.source.length),{value:h,type:a,comment:n.comment,range:[r,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[m,S]=o[h];if(S===""||S==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&i(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&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+S.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,S]=o[h];l+=m.length+S.length+1;let y=S[S.length-1]==="\r";if(y&&(S=S.slice(0,-1)),S&&m.length<c){let
|
|
74
|
+
`;for(let h=u;h<s;++h){let[m,S]=o[h];l+=m.length+S.length+1;let y=S[S.length-1]==="\r";if(y&&(S=S.slice(0,-1)),S&&m.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-S.length-(y?2:1),"BAD_INDENT",N),m=""}a===Vc.Scalar.BLOCK_LITERAL?(d+=f+m.slice(c)+S,f=`
|
|
75
75
|
`):m.length>c||S[0]===" "?(f===" "?f=`
|
|
76
76
|
`:!p&&f===`
|
|
77
77
|
`&&(f=`
|
|
@@ -84,107 +84,108 @@ ${l}
|
|
|
84
84
|
`+o[h][0].slice(c);d[d.length-1]!==`
|
|
85
85
|
`&&(d+=`
|
|
86
86
|
`);break;default:d+=`
|
|
87
|
-
`}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function
|
|
87
|
+
`}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function Hk({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let 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&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":i&&!l&&r(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":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;r(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 Dk(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Op.resolveBlockScalar=Ok});var Mc=P(Dp=>{"use strict";var qc=re(),Lk=Gi();function Bk(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,p,v)=>i(r+f,p,v);switch(n){case"scalar":s=qc.Scalar.PLAIN,c=Vk(a,l);break;case"single-quoted-scalar":s=qc.Scalar.QUOTE_SINGLE,c=Fk(a,l);break;case"double-quoted-scalar":s=qc.Scalar.QUOTE_DOUBLE,c=qk(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=Lk.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Vk(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),Hp(e)}function Fk(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Hp(e.slice(1,-1)).replace(/''/g,"'")}function Hp(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
89
|
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let n=r[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;r=i.exec(e);)r[1]===""?a===`
|
|
90
90
|
`?n+=a:a=`
|
|
91
|
-
`:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function
|
|
91
|
+
`:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function qk(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
|
|
92
92
|
`))if(n===`
|
|
93
|
-
`){let{fold:a,offset:o}=
|
|
93
|
+
`){let{fold:a,offset:o}=Mk(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=Wk[a];if(o)i+=o;else if(a===`
|
|
94
94
|
`)for(a=e[r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="\r"&&e[r+1]===`
|
|
95
|
-
`)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=
|
|
95
|
+
`)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=zk(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
|
|
96
96
|
`&&!(o==="\r"&&e[r+2]===`
|
|
97
|
-
`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function
|
|
97
|
+
`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function Mk(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
|
|
98
98
|
`||r==="\r")&&!(r==="\r"&&e[t+2]!==`
|
|
99
99
|
`);)r===`
|
|
100
100
|
`&&(i+=`
|
|
101
|
-
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Wk={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function zk(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Dp.resolveFlowScalar=Bk});var Vp=P(Bp=>{"use strict";var Ei=F(),Lp=re(),Jk=Fc(),Gk=Mc();function Uk(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Jk.resolveBlockScalar(e,t,r):Gk.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Ei.SCALAR]:c?l=Kk(e.schema,n,c,i,r):t.type==="scalar"?l=Yk(e,n,t,r):l=e.schema[Ei.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Ei.isScalar(d)?d:new Lp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new Lp.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 Kk(e,t,i,r,n){if(i==="!")return e[Ei.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[Ei.SCALAR])}function Yk({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[Ei.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Ei.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}Bp.composeScalar=Uk});var qp=P(Fp=>{"use strict";function Xk(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}Fp.emptyScalarPosition=Xk});var zp=P(zc=>{"use strict";var Qk=Vr(),Zk=F(),eS=$p(),Mp=Vp(),tS=Gi(),iS=qp(),rS={composeNode:Wp,composeEmptyNode:Wc};function Wp(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=nS(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Mp.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=eS.composeCollection(rS,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Wc(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Zk.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Wc(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:iS.emptyScalarPosition(t,i,r),indent:-1,source:""},d=Mp.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 nS({options:e},{offset:t,source:i,end:r},n){let a=new Qk.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=tS.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}zc.composeEmptyNode=Wc;zc.composeNode=Wp});var Up=P(Gp=>{"use strict";var aS=rn(),Jp=zp(),oS=Gi(),sS=sn();function cS(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new aS.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=sS.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Jp.composeNode(l,n,u,o):Jp.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=oS.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}Gp.composeDoc=cS});var Gc=P(Xp=>{"use strict";var lS=na("process"),uS=Ts(),dS=rn(),cn=on(),Kp=F(),fS=Up(),pS=Gi();function ln(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function Yp(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var
|
|
106
|
-
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(
|
|
105
|
+
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var Jc=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=ln(i);a?this.warnings.push(new cn.YAMLWarning(o,r,n)):this.errors.push(new cn.YAMLParseError(o,r,n))},this.directives=new uS.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Yp(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(Kp.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Kp.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
|
|
107
107
|
${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
|
|
108
|
-
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
109
|
-
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new
|
|
108
|
+
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Yp(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(lS.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=ln(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=fS.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new cn.YAMLParseError(ln(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new cn.YAMLParseError(ln(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=pS.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
|
|
109
|
+
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new cn.YAMLParseError(ln(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new dS.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};Xp.Composer=Jc});var eh=P(Ka=>{"use strict";var hS=Fc(),mS=Mc(),vS=on(),Qp=zr();function gS(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new vS.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return mS.resolveFlowScalar(e,t,r);case"block-scalar":return hS.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function wS(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Qp.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
111
|
`),u=s.substring(0,l),d=s.substring(l+1)+`
|
|
112
|
-
`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function
|
|
112
|
+
`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return Zp(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function yS(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Qp.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">":NS(e,c);break;case'"':Uc(e,c,"double-quoted-scalar");break;case"'":Uc(e,c,"single-quoted-scalar");break;default:Uc(e,c,"scalar")}}function NS(e,t){let i=t.indexOf(`
|
|
114
114
|
`),r=t.substring(0,i),n=t.substring(i+1)+`
|
|
115
|
-
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];
|
|
116
|
-
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function
|
|
117
|
-
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}
|
|
115
|
+
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];Zp(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 Zp(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function Uc(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}Ka.createScalarToken=wS;Ka.resolveAsScalar=gS;Ka.setScalarValue=yS});var ih=P(th=>{"use strict";var bS=e=>"type"in e?Xa(e):Ya(e);function Xa(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Xa(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Ya(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Ya(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Ya(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function Ya({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Xa(t)),i)for(let a of i)n+=a.source;return r&&(n+=Xa(r)),n}th.stringify=bS});var oh=P(ah=>{"use strict";var Kc=Symbol("break visit"),kS=Symbol("skip children"),rh=Symbol("remove item");function Ci(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),nh(Object.freeze([]),e,t)}Ci.BREAK=Kc;Ci.SKIP=kS;Ci.REMOVE=rh;Ci.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};Ci.parentCollection=(e,t)=>{let i=Ci.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function nh(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=nh(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===Kc)return Kc;s===rh&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}ah.visit=Ci});var Qa=P(Se=>{"use strict";var Yc=eh(),SS=ih(),ES=oh(),Xc="\uFEFF",Qc="",Zc="",el="",CS=e=>!!e&&"items"in e,xS=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function PS(e){switch(e){case Xc:return"<BOM>";case Qc:return"<DOC>";case Zc:return"<FLOW_END>";case el:return"<SCALAR>";default:return JSON.stringify(e)}}function RS(e){switch(e){case Xc:return"byte-order-mark";case Qc:return"doc-mode";case Zc:return"flow-error-end";case el:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
118
|
`:case`\r
|
|
119
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Se.createScalarToken=
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
121
|
-
\r `),
|
|
119
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Se.createScalarToken=Yc.createScalarToken;Se.resolveAsScalar=Yc.resolveAsScalar;Se.setScalarValue=Yc.setScalarValue;Se.stringify=SS.stringify;Se.visit=ES.visit;Se.BOM=Xc;Se.DOCUMENT=Qc;Se.FLOW_END=Zc;Se.SCALAR=el;Se.isCollection=CS;Se.isScalar=xS;Se.prettyToken=PS;Se.tokenType=RS});var rl=P(ch=>{"use strict";var un=Qa();function Ge(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var sh=new Set("0123456789ABCDEFabcdef"),AS=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Za=new Set(",[]{}"),_S=new Set(` ,[]{}
|
|
121
|
+
\r `),tl=e=>!e||_S.has(e),il=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
|
|
122
122
|
`?!0:i==="\r"?this.buffer[t+1]===`
|
|
123
123
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
|
|
124
124
|
`||!n&&!this.atEnd)return t+r+1}return i===`
|
|
125
125
|
`||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&Ge(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
126
|
-
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===
|
|
126
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===un.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,r=t.indexOf("#");for(;r!==-1;){let a=t[r-1];if(a===" "||a===" "){i=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield un.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let i=this.peek(3);if((i==="---"||i==="...")&&Ge(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,i==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ge(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Ge(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(tl),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&Ge(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield un.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(tl),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ge(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
|
|
127
127
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=r.indexOf(`
|
|
128
128
|
`,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>Ge(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,r;e:for(let a=this.pos;r=this.buffer[a];++a)switch(r){case" ":i+=1;break;case`
|
|
129
129
|
`:t=a,i=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
130
|
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
131
131
|
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
132
132
|
`;)r=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
-
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield
|
|
133
|
+
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield un.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(Ge(a)||t&&Za.has(a))break;i=r}else if(Ge(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(r+=1,n=`
|
|
135
|
-
`,a=this.buffer[r+1]):i=r),a==="#"||t&&
|
|
136
|
-
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&
|
|
135
|
+
`,a=this.buffer[r+1]):i=r),a==="#"||t&&Za.has(a))break;if(n===`
|
|
136
|
+
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&Za.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield un.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(tl),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ge(r)||i&&Za.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!Ge(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(AS.has(i))i=this.buffer[++t];else if(i==="%"&&sh.has(this.buffer[t+1])&&sh.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
137
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};ch.Lexer=il});var al=P(lh=>{"use strict";var nl=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};lh.LineCounter=nl});var sl=P(hh=>{"use strict";var IS=na("process"),uh=Qa(),TS=rl();function Gt(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function dh(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 ph(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 eo(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 Ui(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 to(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function fh(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Gt(t.start,"explicit-key-ind")&&!Gt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,ph(t.value)?t.value.end?to(t.value.end,t.sep):t.value.end=t.sep:to(t.start,t.sep),delete t.sep)}var ol=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 TS.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,IS.env.LOG_TOKENS&&console.log("|",uh.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=uh.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&fh(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&dh(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{dh(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let i=eo(this.peek(2)),r=Ui(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
140
|
-
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){
|
|
140
|
+
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){to(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Gt(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(ph(i.key)&&!Gt(i.sep,"newline")){let o=Ui(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(Gt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Ui(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Gt(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!Gt(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){to(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||Gt(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=eo(r),a=Ui(n);fh(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
142
|
-
`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=
|
|
143
|
-
${
|
|
144
|
-
`,i)}var
|
|
142
|
+
`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=eo(t),r=Ui(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=eo(t),r=Ui(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};hh.Parser=ol});var yh=P(fn=>{"use strict";var mh=Gc(),jS=rn(),dn=on(),$S=zs(),OS=F(),HS=al(),vh=sl();function gh(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new HS.LineCounter||null,prettyErrors:t}}function DS(e,t={}){let{lineCounter:i,prettyErrors:r}=gh(t),n=new vh.Parser(i?.addNewLine),a=new mh.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(dn.prettifyError(e,i)),s.warnings.forEach(dn.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function wh(e,t={}){let{lineCounter:i,prettyErrors:r}=gh(t),n=new vh.Parser(i?.addNewLine),a=new mh.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 dn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(dn.prettifyError(e,i)),o.warnings.forEach(dn.prettifyError(e,i))),o}function LS(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=wh(e,i);if(!n)return null;if(n.warnings.forEach(a=>$S.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function BS(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return OS.isDocument(e)&&!r?e.toString(i):new jS.Document(e,r,i).toString(i)}fn.parse=LS;fn.parseAllDocuments=DS;fn.parseDocument=wh;fn.stringify=BS});var Ki=P(z=>{"use strict";var VS=Gc(),FS=rn(),qS=Pc(),cl=on(),MS=Vr(),Ut=F(),WS=Mt(),zS=re(),JS=zt(),GS=Jt(),US=Qa(),KS=rl(),YS=al(),XS=sl(),io=yh(),Nh=Hr();z.Composer=VS.Composer;z.Document=FS.Document;z.Schema=qS.Schema;z.YAMLError=cl.YAMLError;z.YAMLParseError=cl.YAMLParseError;z.YAMLWarning=cl.YAMLWarning;z.Alias=MS.Alias;z.isAlias=Ut.isAlias;z.isCollection=Ut.isCollection;z.isDocument=Ut.isDocument;z.isMap=Ut.isMap;z.isNode=Ut.isNode;z.isPair=Ut.isPair;z.isScalar=Ut.isScalar;z.isSeq=Ut.isSeq;z.Pair=WS.Pair;z.Scalar=zS.Scalar;z.YAMLMap=JS.YAMLMap;z.YAMLSeq=GS.YAMLSeq;z.CST=US;z.Lexer=KS.Lexer;z.LineCounter=YS.LineCounter;z.Parser=XS.Parser;z.parse=io.parse;z.parseAllDocuments=io.parseAllDocuments;z.parseDocument=io.parseDocument;z.stringify=io.stringify;z.visit=Nh.visit;z.visitAsync=Nh.visitAsync});import wi from"node:path";import{realpathSync as ET}from"node:fs";import{execFileSync as Ny}from"child_process";import $r from"path";function Di(e,t){return Ny("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function by(e,t){let i=$r.normalize(e),r=$r.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function be(e){try{let t=$r.resolve(Di(e,["rev-parse","--show-toplevel"])),r=Di(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?$r.resolve(r.slice(9)):t,a=null;try{a=Di(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!by(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Id(e){try{Di(e,["rev-parse","--is-inside-work-tree"]);let t=Di(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:$r.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function Lt(e){return Id(e).map(t=>t.root)}function yi(e,t){try{let i=Di(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as ky}from"crypto";function ze(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function Sy(e,t){t.has(e)&&ze("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||ze("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&ze("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ze("symbol properties are not supported"),`[${e.map(r=>Rs(r,t)).join(",")}]`}finally{t.delete(e)}}function Ey(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&ze("only plain objects are supported"),t.has(e)&&ze("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ze("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&ze("accessor properties are not supported"),`${JSON.stringify(o)}:${Rs(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Rs(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)||ze("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?Sy(e,t):Ey(e,t);case"bigint":case"function":case"symbol":case"undefined":return ze(`${typeof e} values are not supported`)}return ze("unsupported value type")}function Or(e){return Rs(e,new Set)}function j(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return ky("sha256").update(`${e}
|
|
143
|
+
${Or(t)}`).digest("hex")}var su=jr(Ki(),1);import{promises as Ym}from"fs";import Rt from"path";import{createHash as tE}from"node:crypto";import{promises as Ue}from"node:fs";import Oe from"node:path";import{TextDecoder as iE}from"node:util";import ll from"path";var QS=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),ZS=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function eE(e){return e.toLowerCase().startsWith(".env")}function ct(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>eE(r))?"environment-file":i.some(r=>ZS.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>QS.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function ul(e,t){let i=ct(t);if(i)return i;let r=ll.resolve(e.projectRoot,...t.split("/")),n=ll.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===ll.resolve(e.configFile)?"native-runtime":null}function Kt(e){return e!==0&&e!==0n&&e!=="0"}function $e(e,t){return Kt(e.dev)&&Kt(t.dev)&&Kt(e.ino)&&Kt(t.ino)}function M(e,t){let i=Kt(e.dev)&&Kt(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Kt(e.ino)&&Kt(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var pn=1024*1024;function dl(e,t){let i=Oe.relative(e,t);return i===""||!Oe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Oe.sep}`)}function rE(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 i=e.toLowerCase(),r=ct(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function nE(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function aE(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ro(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function bh(e){let t=await Ue.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ue.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function oE(e,t){let i=Oe.resolve(e),r=Oe.resolve(t);if(!dl(i,r))throw new Error("Native artifact path is outside its root");let n=[await bh(i)],a=i;for(let o of Oe.relative(i,r).split(Oe.sep).filter(Boolean)){a=Oe.join(a,o);let s=await bh(a);if(!dl(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function kh(e){for(let t of e){let i=await Ue.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!aE(t,i)||await Ue.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ne(e){let t=rE(e.ref),i=e.maxBytes===null?null:nE(e.maxBytes??pn),r=Oe.resolve(e.root,...t.split("/")),n=await oE(e.root,Oe.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Ue.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Ue.realpath(r);if(!dl(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ue.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ue.lstat(r),Ue.realpath(r)]);if(await kh(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!ro(a,c)||!ro(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let k=i===null?p.length:i+1-f,N=await s.read(p,0,Math.min(p.length,k),null);if(N.bytesRead===0)break;if(f+=N.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Ue.lstat(r),Ue.realpath(r)]);if(await kh(n),!h.isFile()||h.isSymbolicLink()||m!==o||!ro(c,v)||!ro(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),y;try{y=new iE("utf-8",{fatal:!0}).decode(S)}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:tE("sha256").update(S).digest("hex"),text:y}}finally{await s.close()}}import{randomUUID as sE}from"crypto";import{promises as le}from"fs";import Ke from"path";function no(e,t){let i=Ke.relative(e,t);return i===""||!Ke.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ke.sep}`)}function cE(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ao(e,t){return M({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function lE(e,t){return ao(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Sh(e){let t=await le.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 le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Yi(e){for(let t of e){let i=await le.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!cE(t,i)||await le.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function uE(e,t,i){let[r,n]=await Promise.all([le.lstat(e),le.realpath(e),i?Yi(i):Promise.resolve()]);if(!r.isFile()||r.isSymbolicLink()||!ao(r,t)||i&&!no(i[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return r}async function dE(e,t){let i=Ke.resolve(e),r=Ke.resolve(t);if(!no(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Sh(i)],a=Ke.relative(i,r).split(Ke.sep).filter(Boolean),o=i;for(let s of a){await Yi(n),o=Ke.join(o,s);try{await le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Sh(o);if(!no(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Yi(n),n}async function fE(e){let t;try{t=await le.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function pE(e,t,i={}){let r=Ke.dirname(e),n=i.containedRoot?await dE(i.containedRoot,r):null;n||await le.mkdir(r,{recursive:!0});let a=Ke.join(r,`.${Ke.basename(e)}.${sE()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await le.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([le.lstat(a),le.realpath(a)]);if(await Yi(n),!l.isFile()||l.isSymbolicLink()||!ao(s,l)||!no(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(),!ao(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await uE(a,c,n),await i.beforeCommit?.(),n){await Yi(n);let l=await le.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!lE(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await le.link(a,e),await le.unlink(a)):await le.rename(a,e),await fE(r)}catch(l){if(await o?.close(),!n)await le.rm(a,{force:!0});else try{await Yi(n),await le.rm(a,{force:!0})}catch{}throw l}}async function Nt(e,t,i={}){await pE(e,t,i)}async function Ye(e,t,i={}){await Nt(e,JSON.stringify(t,null,2)+`
|
|
144
|
+
`,i)}var fl={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:"验证预期"}},hE={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:"结论"}},mE={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:"结论"}},Eh=new Map,pl=new Map;for(let e of Object.keys(fl)){for(let[t,i]of Object.entries(fl[e]))Eh.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(hE[e]))pl.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(mE[e]))pl.set(i.toLocaleLowerCase("en-US"),t)}function vE(e,t){return fl[e][t]}function oo(e){return Eh.get(e.trim().toLocaleLowerCase("en-US"))??null}function Ch(e){return pl.get(e.trim().toLocaleLowerCase("en-US"))??null}function so(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(i=>`# ${vE(e,i)}
|
|
145
145
|
`).join(`
|
|
146
|
-
`)}var dl=Rr(Ji(),1);import Kt from"path";var un=64*1024,no=1024,ao=64,kh=1024,Sh=64,xh=5,ll={learning:!0,retrieval:!0},lE={provider:"local"},uE=12e4,Eh=6e5,dE=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/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/**"],fE=["**/.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"],pE=[...dE,...fE].sort((e,t)=>e.localeCompare(t,"en"));var Xe={include:["**/*"],exclude:[...pE],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function hE(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Kt.posix.isAbsolute(i)||Kt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Gi(e){let t=hE(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Ph(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function oo(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||Kt.posix.isAbsolute(r)||Kt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function bt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Rh(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function so(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>no)throw new Error(`${t} exceeds ${no} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>ao)throw new Error(`${t} contains more than ${ao} wildcard tokens`);return e}function Ch(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>so(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function ul(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function mE(e){if(e===void 0)return{...Xe,include:[...Xe.include],exclude:[...Xe.exclude]};let t=bt(e,"native.snapshot");return{include:Ch(t.include,"native.snapshot.include",Xe.include),exclude:Ch(t.exclude,"native.snapshot.exclude",Xe.exclude),max_files:ul(t.max_files,Xe.max_files,"native.snapshot.max_files"),max_total_bytes:ul(t.max_total_bytes,Xe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ul(t.max_duration_ms,Xe.max_duration_ms,"native.snapshot.max_duration_ms")}}function vE(e){if(e===void 0)return;let t=bt(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=bt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Gi(r),toArtifactRoot:Gi(n),stage:a,...o?{cleanup:o}:{}}}function gE(e){if(e===void 0)return;let t=bt(e,"native.finish");if(t.pull_request===void 0)return{};let i=bt(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Kt.posix.isAbsolute(r[0])||Kt.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??uE;if(!Number.isSafeInteger(n)||n<1||n>Eh)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Eh}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function wE(e,t={}){let i=bt(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??xh;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=vE(i.pending_root_move),c=gE(i.finish);return{artifact_root:Gi(r),language:Rh(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:mE(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function yE(e){let t=bt(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Ph(t.artifact_layout),language:Rh(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function NE(e){let i=bt(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>oo(r,`hook.allow_paths[${n}]`)))]}}function bE(e){if(e===void 0)return{...ll};let t=bt(e,"memory"),i=t.learning??ll.learning,r=t.retrieval??ll.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function fl(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function kE(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||Kt.posix.isAbsolute(i)||Kt.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>kh)throw new Error(`${t} exceeds ${kh} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>Sh)throw new Error(`${t} contains more than ${Sh} wildcard tokens`);return i}function SE(e){let i=fl(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>kE(r,`knowledge.local.include[${n}]`)))]}}function EE(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function CE(e){let t=fl(e,"knowledge.remote"),i=EE(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function xE(e){if(e===void 0)return{...lE};let t=fl(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:SE(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:CE(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function PE(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function RE(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function dn(e,t={}){let i=(0,dl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=PE(n.ambient_resume),o=n.hook===void 0?void 0:NE(n.hook),s=bE(n.memory),c=xE(n.knowledge),l=n.native===void 0?void 0:wE(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:yE(n.classic),d=RE(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}:{}}}import{createHash as _E}from"crypto";import{promises as uo}from"fs";import Yt from"path";import{constants as co,promises as Ei}from"fs";var lt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function pl(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ah(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function fn(e){return{dev:e.dev,ino:e.ino,birthtime:pl(e)}}function lo(e,t){let i=fn(e),r=fn(t);return $e(i,r)?M(i,r):M(i,r)&&pl(e)===pl(t)&&Ah(e)===Ah(t)&&e.size===t.size}async function Ui(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await Ei.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new lt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new lt("too-large",`${r} exceeds ${t} bytes`);let o=await Ei.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:fn(a)});let s=process.platform==="win32"?co.O_RDONLY:co.O_RDONLY|co.O_NOFOLLOW|co.O_NONBLOCK,c;try{c=await Ei.open(e,s)}catch(l){throw l.code==="ELOOP"?new lt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Ei.lstat(e,{bigint:n}),Ei.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!lo(a,l)||!lo(a,u))throw new lt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:fn(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:N}=await c.read(v,0,Math.min(v.length,y),null);if(N===0)break;if(p+=N,p>t)throw new lt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([c.stat({bigint:n}),Ei.lstat(e,{bigint:n}),Ei.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||S!==o||!lo(a,h)||!lo(a,m))throw new lt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:fn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:S}}finally{await c.close()}}function AE(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function hl(e,t){let i=Yt.relative(e,t);return i===""||!Yt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Yt.sep}`)}async function _h(e,t){let i=Yt.resolve(e),r=await uo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return uo.realpath(i)}async function Ih(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Yt.join(n,i[a]);let o;try{o=await uo.lstat(n)}catch(u){if(AE(u))return{exists:!1,kind:"missing"};throw u}let s=Yt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await uo.realpath(n);if(!hl(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Ki(e,t,i){let r=oo(t,i.label),n=Yt.resolve(e),a=await _h(n,i.label),o=r.split("/"),s=Yt.resolve(n,...o);if(!hl(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Ih(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Xt(e,t,i,r){let n=await Ki(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await _h(n.projectRoot,r.label);return Ui(n.target,i,{...r,verify:async(o,s)=>{if(!hl(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Ih(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var pn=".comet/config.yaml";function IE(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function fo(e,t={}){return(await po(e,t)).document}async function TE(e){try{return(await Xt(e,pn,un,{label:pn})).bytes}catch(t){if(IE(t))return null;throw t}}function jE(e){return e?{exists:!0,sha256:_E("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function po(e,t={}){let i=await TE(e);return{document:i?dn(i.toString("utf8"),t):null,identity:jE(i)}}async function ml(e){return(await fo(e))?.config??null}var V$=16*1024;import{existsSync as jh,promises as Qt}from"fs";import W from"path";import LE from"os";var Nl=".comet/config.yaml",BE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function wl(e){try{return await Qt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function VE(e){try{let t=await Qt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Xi(e,t){let i=W.relative(e,t);return i===""||!W.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${W.sep}`)}async function Yi(e){let t=[],i=e;for(;!await wl(i);){let n=W.dirname(i);if(n===i)break;t.push(W.basename(i)),i=n}let r=await Qt.realpath(i);return W.resolve(r,...t.reverse())}async function yl(e){try{return(await Qt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function bl(e){let t=W.resolve(e);try{(await Qt.stat(t)).isDirectory()||(t=W.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=W.resolve(LE.homedir());for(;;){if(!(t===r&&i!==r)){let o=W.join(t,...Nl.split("/")),s=t===i||await VE(o);if(await wl(o)&&s)return t}if(await wl(W.join(t,".git")))return t;let a=W.dirname(t);if(a===t)return i;t=a}}function kl(e){return Gi(e)}async function FE(e,t){let i=kl(t),r=W.resolve(e,...i.split("/")),n=await Qt.realpath(e),a=await Yi(r);if(!Xi(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function kt(e,t){let i=kl(t),r=await FE(e,i),n=W.join(r,"comet");if(await yl(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Yi(r),Yi(n)]);if(!Xi(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=W.resolve(e),c=W.join(s,".comet","runtime","native");if(await yl(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Qt.realpath(s),Yi(c)]);if(!Xi(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:W.join(e,...Nl.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:W.join(n,"specs"),changesDir:W.join(n,"changes"),archiveDir:W.join(n,"archive"),runtimeDir:c,changesRuntimeDir:W.join(c,"changes"),locksDir:W.join(c,"locks"),transactionsDir:W.join(c,"transactions")}}function Oh(e){if(!BE.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Zt(e,t){Oh(t);let i=W.join(e.changesRuntimeDir,t);if(!V(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Hh(e,t){Oh(t);let i=W.join(e.changesDir,t,"runtime");if(!V(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function U(e,t){let i=Zt(e,t);if(jh(i))return i;let r=Hh(e,t);return jh(r)?r:i}async function $h(e){try{let t=await Qt.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Sl(e,t){let i=Zt(e,t),r=Hh(e,t),[n,a]=await Promise.all([$h(i),$h(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function ei(e,t){if(!t.startsWith("runtime/")||W.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=W.resolve(e,...t.slice(8).split("/"));if(!V(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function le(e,t){let i=W.resolve(t);if(V(e.runtimeDir,i))return e.runtimeDir;if(V(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function V(e,t){return Xi(W.resolve(e),W.resolve(t))}async function J(e,t){let i=W.resolve(e),r=W.resolve(t);if(!Xi(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await yl(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Yi(i),Yi(r)]);if(!Xi(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var El=Xe;var ho=so;async function Ee(e){let t=(await fo(e))?.config??null;return t?.native?t:null}import{AsyncLocalStorage as ME}from"async_hooks";var dO=16*1024;var fO=new ME;import Lh from"node:path";var WE="comet.native.acceptance.v1",zE=/^acceptance-[a-f0-9]{64}$/u,JE=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),GE=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,UE=/^[a-f0-9]{64}$/u,KE=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function YE(e,t){return e<t?-1:e>t?1:0}var St=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),mn=Object.freeze({maxCriteria:1024}),Bh="<!-- comet-native:acceptance-evidence:start -->",Vh="<!-- comet-native:acceptance-evidence:end -->";function Fh(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function qh(e,t){let i=t.toString(36),r=j("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function XE(e){if(!UE.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=KE.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==j("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function QE(e,t){let i=Fh(e.text,St.maxTextBytes),r=e.context.slice(0,St.maxContextItems).map(n=>Fh(n,St.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function Wh(e){let t=XE({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(YE),n=r.slice(0,St.maxFailedCheckIds),a=e.criteria.slice(t,t+St.maxItems);for(let c of a){let l=[...i,QE(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?qh(e.acceptanceHash,u):null,limits:{...St}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>St.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?qh(e.acceptanceHash,o):null,limits:{...St}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>St.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function xl(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function Cl(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function Mh(e){return e.includes("-->")||e.includes("--!>")}function*Qi(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
146
|
+
`)}var vl=jr(Ki(),1);import Yt from"path";var hn=64*1024,co=1024,lo=64,xh=1024,Ph=64,_h=5,hl={learning:!0,retrieval:!0},gE={provider:"local"},wE=12e4,Rh=6e5,yE=[".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/**"],NE=["**/.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"],bE=[...yE,...NE].sort((e,t)=>e.localeCompare(t,"en"));var Xe={include:["**/*"],exclude:[...bE],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function kE(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Yt.posix.isAbsolute(i)||Yt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Xi(e){let t=kE(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Ih(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function uo(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||Yt.posix.isAbsolute(r)||Yt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function bt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Th(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function fo(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>co)throw new Error(`${t} exceeds ${co} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>lo)throw new Error(`${t} contains more than ${lo} wildcard tokens`);return e}function Ah(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>fo(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function ml(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function SE(e){if(e===void 0)return{...Xe,include:[...Xe.include],exclude:[...Xe.exclude]};let t=bt(e,"native.snapshot");return{include:Ah(t.include,"native.snapshot.include",Xe.include),exclude:Ah(t.exclude,"native.snapshot.exclude",Xe.exclude),max_files:ml(t.max_files,Xe.max_files,"native.snapshot.max_files"),max_total_bytes:ml(t.max_total_bytes,Xe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ml(t.max_duration_ms,Xe.max_duration_ms,"native.snapshot.max_duration_ms")}}function EE(e){if(e===void 0)return;let t=bt(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=bt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Xi(r),toArtifactRoot:Xi(n),stage:a,...o?{cleanup:o}:{}}}function CE(e){if(e===void 0)return;let t=bt(e,"native.finish");if(t.pull_request===void 0)return{};let i=bt(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Yt.posix.isAbsolute(r[0])||Yt.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??wE;if(!Number.isSafeInteger(n)||n<1||n>Rh)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Rh}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function xE(e,t={}){let i=bt(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??_h;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=EE(i.pending_root_move),c=CE(i.finish);return{artifact_root:Xi(r),language:Th(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:SE(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function PE(e){let t=bt(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Ih(t.artifact_layout),language:Th(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function RE(e){let i=bt(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>uo(r,`hook.allow_paths[${n}]`)))]}}function AE(e){if(e===void 0)return{...hl};let t=bt(e,"memory"),i=t.learning??hl.learning,r=t.retrieval??hl.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function gl(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function _E(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||Yt.posix.isAbsolute(i)||Yt.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>xh)throw new Error(`${t} exceeds ${xh} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>Ph)throw new Error(`${t} contains more than ${Ph} wildcard tokens`);return i}function IE(e){let i=gl(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>_E(r,`knowledge.local.include[${n}]`)))]}}function TE(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function jE(e){let t=gl(e,"knowledge.remote"),i=TE(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function $E(e){if(e===void 0)return{...gE};let t=gl(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:IE(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:jE(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function OE(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function HE(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function mn(e,t={}){let i=(0,vl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=OE(n.ambient_resume),o=n.hook===void 0?void 0:RE(n.hook),s=AE(n.memory),c=$E(n.knowledge),l=n.native===void 0?void 0:xE(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:PE(n.classic),d=HE(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}:{}}}import{createHash as LE}from"crypto";import{promises as mo}from"fs";import Xt from"path";import{constants as po,promises as xi}from"fs";var lt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function wl(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function jh(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function vn(e){return{dev:e.dev,ino:e.ino,birthtime:wl(e)}}function ho(e,t){let i=vn(e),r=vn(t);return $e(i,r)?M(i,r):M(i,r)&&wl(e)===wl(t)&&jh(e)===jh(t)&&e.size===t.size}async function Qi(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await xi.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new lt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new lt("too-large",`${r} exceeds ${t} bytes`);let o=await xi.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:vn(a)});let s=process.platform==="win32"?po.O_RDONLY:po.O_RDONLY|po.O_NOFOLLOW|po.O_NONBLOCK,c;try{c=await xi.open(e,s)}catch(l){throw l.code==="ELOOP"?new lt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),xi.lstat(e,{bigint:n}),xi.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ho(a,l)||!ho(a,u))throw new lt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:vn(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:k}=await c.read(v,0,Math.min(v.length,y),null);if(k===0)break;if(p+=k,p>t)throw new lt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([c.stat({bigint:n}),xi.lstat(e,{bigint:n}),xi.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||S!==o||!ho(a,h)||!ho(a,m))throw new lt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:vn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:S}}finally{await c.close()}}function DE(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function yl(e,t){let i=Xt.relative(e,t);return i===""||!Xt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Xt.sep}`)}async function $h(e,t){let i=Xt.resolve(e),r=await mo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return mo.realpath(i)}async function Oh(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Xt.join(n,i[a]);let o;try{o=await mo.lstat(n)}catch(u){if(DE(u))return{exists:!1,kind:"missing"};throw u}let s=Xt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await mo.realpath(n);if(!yl(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Zi(e,t,i){let r=uo(t,i.label),n=Xt.resolve(e),a=await $h(n,i.label),o=r.split("/"),s=Xt.resolve(n,...o);if(!yl(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Oh(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Qt(e,t,i,r){let n=await Zi(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await $h(n.projectRoot,r.label);return Qi(n.target,i,{...r,verify:async(o,s)=>{if(!yl(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Oh(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var gn=".comet/config.yaml";function BE(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function vo(e,t={}){return(await go(e,t)).document}async function VE(e){try{return(await Qt(e,gn,hn,{label:gn})).bytes}catch(t){if(BE(t))return null;throw t}}function FE(e){return e?{exists:!0,sha256:LE("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function go(e,t={}){let i=await VE(e);return{document:i?mn(i.toString("utf8"),t):null,identity:FE(i)}}async function Nl(e){return(await vo(e))?.config??null}var rO=16*1024;import{existsSync as Dh,promises as Zt}from"fs";import W from"path";import JE from"os";var Cl=".comet/config.yaml",GE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Sl(e){try{return await Zt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function UE(e){try{let t=await Zt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function tr(e,t){let i=W.relative(e,t);return i===""||!W.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${W.sep}`)}async function er(e){let t=[],i=e;for(;!await Sl(i);){let n=W.dirname(i);if(n===i)break;t.push(W.basename(i)),i=n}let r=await Zt.realpath(i);return W.resolve(r,...t.reverse())}async function El(e){try{return(await Zt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function xl(e){let t=W.resolve(e);try{(await Zt.stat(t)).isDirectory()||(t=W.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=W.resolve(JE.homedir());for(;;){if(!(t===r&&i!==r)){let o=W.join(t,...Cl.split("/")),s=t===i||await UE(o);if(await Sl(o)&&s)return t}if(await Sl(W.join(t,".git")))return t;let a=W.dirname(t);if(a===t)return i;t=a}}function Pl(e){return Xi(e)}async function KE(e,t){let i=Pl(t),r=W.resolve(e,...i.split("/")),n=await Zt.realpath(e),a=await er(r);if(!tr(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function kt(e,t){let i=Pl(t),r=await KE(e,i),n=W.join(r,"comet");if(await El(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([er(r),er(n)]);if(!tr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=W.resolve(e),c=W.join(s,".comet","runtime","native");if(await El(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Zt.realpath(s),er(c)]);if(!tr(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:W.join(e,...Cl.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:W.join(n,"specs"),changesDir:W.join(n,"changes"),archiveDir:W.join(n,"archive"),runtimeDir:c,changesRuntimeDir:W.join(c,"changes"),locksDir:W.join(c,"locks"),transactionsDir:W.join(c,"transactions")}}function Bh(e){if(!GE.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ei(e,t){Bh(t);let i=W.join(e.changesRuntimeDir,t);if(!V(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Vh(e,t){Bh(t);let i=W.join(e.changesDir,t,"runtime");if(!V(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function U(e,t){let i=ei(e,t);if(Dh(i))return i;let r=Vh(e,t);return Dh(r)?r:i}async function Lh(e){try{let t=await Zt.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Rl(e,t){let i=ei(e,t),r=Vh(e,t),[n,a]=await Promise.all([Lh(i),Lh(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function ti(e,t){if(!t.startsWith("runtime/")||W.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=W.resolve(e,...t.slice(8).split("/"));if(!V(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function ue(e,t){let i=W.resolve(t);if(V(e.runtimeDir,i))return e.runtimeDir;if(V(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function V(e,t){return tr(W.resolve(e),W.resolve(t))}async function J(e,t){let i=W.resolve(e),r=W.resolve(t);if(!tr(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await El(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([er(i),er(r)]);if(!tr(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var Al=Xe;var wo=fo;async function Ee(e){let t=(await vo(e))?.config??null;return t?.native?t:null}import{AsyncLocalStorage as XE}from"async_hooks";var RO=16*1024;var AO=new XE;import qh from"node:path";var QE="comet.native.acceptance.v1",ZE=/^acceptance-[a-f0-9]{64}$/u,eC=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),tC=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,iC=/^[a-f0-9]{64}$/u,rC=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function nC(e,t){return e<t?-1:e>t?1:0}var St=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),yn=Object.freeze({maxCriteria:1024}),Mh="<!-- comet-native:acceptance-evidence:start -->",Wh="<!-- comet-native:acceptance-evidence:end -->";function zh(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function Jh(e,t){let i=t.toString(36),r=j("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function aC(e){if(!iC.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=rC.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==j("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function oC(e,t){let i=zh(e.text,St.maxTextBytes),r=e.context.slice(0,St.maxContextItems).map(n=>zh(n,St.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function Uh(e){let t=aC({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(nC),n=r.slice(0,St.maxFailedCheckIds),a=e.criteria.slice(t,t+St.maxItems);for(let c of a){let l=[...i,oC(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?Jh(e.acceptanceHash,u):null,limits:{...St}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>St.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?Jh(e.acceptanceHash,o):null,limits:{...St}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>St.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Il(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function _l(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function Gh(e){return e.includes("-->")||e.includes("--!>")}function*ir(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
147
147
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
148
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=
|
|
149
|
-
`),[],r)),"Brief",r)}function
|
|
150
|
-
`),o.context,r)),o=null}};for(let{line:c,body:l}of
|
|
151
|
-
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=Jh(o),c=nC(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function nC(e){let t=Jh([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var Tl=Rr(Ji(),1);import{promises as oC}from"node:fs";var vn="comet.native.v4",vo="comet.native.local-execution.v4";var Uh=["multi-session","single-session"];var sC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,cC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lC=/^A[1-9][0-9]*$/u,uC=/^[a-f0-9]{64}$/u,dC=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 ye(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ne(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function ue(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Il(e,t){return e===null?null:ue(e,t)}function fC(e,t){let i=ue(e,t);if(!uC.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Zi(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ie(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function pC(e,t){return e===null?null:ie(e,t,Number.MIN_SAFE_INTEGER)}function ae(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ut(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function go(e,t){return ut(e,t,(i,r)=>ue(i,`${t}[${r}]`))}function Ci(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function er(e,t){let i=ue(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function jl(e,t,i=!1){let r=ue(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function He(e,t){let i=ye(e,t);return Ne(i,new Set(["text","truncated"]),t),{text:ue(i.text,`${t}.text`,{empty:!0}),truncated:Zi(i.truncated,`${t}.truncated`)}}function hC(e,t){let i=`Native spec_changes[${t}]`,r=ye(e,i);Ne(r,new Set(["capability","operation","source"]),i);let n=ue(r.capability,`${i}.capability`);if(!cC.test(n))throw new Error(`${i}.capability is invalid`);let a=ae(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:jl(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function mC(e){let t="Native workspace",i=ye(e,t);Ne(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=ae(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Il(i.change_branch,`${t}.change_branch`),a=Il(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:ae(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function vC(e){let t="Native loop",i=ye(e,t);Ne(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=go(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Ci(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:ae(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ae(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ie(i.goal_cycle,`${t}.goal_cycle`,1),iteration:ie(i.iteration,`${t}.iteration`),attempt:ie(i.attempt,`${t}.attempt`),retry_epoch:ie(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ie(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ie(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ie(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Il(i.next_action,`${t}.next_action`)}}function gC(e,t){let i=`Native acceptance[${t}]`,r=ye(e,i);Ne(r,new Set(["id","source","text","result","reason"]),i);let n=ue(r.id,`${i}.id`);if(!lC.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:jl(r.source,`${i}.source`),text:ue(r.text,`${i}.text`),result:ae(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:He(r.reason,`${i}.reason`)}}function wC(e,t){let i=`Native builder_handoff.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["name","result","note"]),i),{name:He(r.name,`${i}.name`),result:ae(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:He(r.note,`${i}.note`)}}function yC(e){let t="Native builder_handoff",i=ye(e,t);Ne(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=go(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ci(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:ye(i.review,`${t}.review`);return n&&Ne(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ue(i.candidate_id,`${t}.candidate_id`),identity_provider:ue(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:ue(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),summary:He(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ut(i.checks,`${t}.checks`,wC),checks_truncated:Zi(i.checks_truncated,`${t}.checks_truncated`),known_limits:ut(i.known_limits,`${t}.known_limits`,(a,o)=>He(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Zi(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ae(n.status,["passed"],`${t}.review.status`),summary:He(n.summary,`${t}.review.summary`),reviewer_execution_ref:ue(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:er(i.submitted_at,`${t}.submitted_at`)}}function NC(e,t){let i=`Native blockers[${t}]`,r=ye(e,i);Ne(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=go(r.acceptance_ids,`${i}.acceptance_ids`);return Ci(n,`${i}.acceptance_ids`),{owner:ae(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:He(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:ae(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function bC(e,t){let i=`Native verification.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:ue(r.id,`${i}.id`),name:He(r.name,`${i}.name`),argv_display:ut(r.argv_display,`${i}.argv_display`,(n,a)=>He(n,`${i}.argv_display[${a}]`)),argv_truncated:Zi(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:jl(r.cwd_ref,`${i}.cwd_ref`,!0),status:ae(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:pC(r.exit_code,`${i}.exit_code`),duration_ms:ie(r.duration_ms,`${i}.duration_ms`)}}function kC(e){let t="Native verification",i=ye(e,t);Ne(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ut(i.checks,`${t}.checks`,bC);Ci(r.map(a=>a.id),`${t}.checks IDs`);let n=ue(i.identity_provider,`${t}.identity_provider`);return{candidate_id:ue(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ue(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),attempt:ie(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ae(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ae(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:He(i.summary,`${t}.summary`),risks:ut(i.risks,`${t}.risks`,(a,o)=>He(a,`${t}.risks[${o}]`)),risks_truncated:Zi(i.risks_truncated,`${t}.risks_truncated`),completed_at:er(i.completed_at,`${t}.completed_at`)}}function SC(e,t){let i=`Native history[${t}]`,r=ye(e,i);Ne(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=go(r.unresolved_ids,`${i}.unresolved_ids`);return Ci(n,`${i}.unresolved_ids`),{goal_cycle:ie(r.goal_cycle,`${i}.goal_cycle`,1),iteration:ie(r.iteration,`${i}.iteration`),attempt:ie(r.attempt,`${i}.attempt`),outcome:ae(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:He(r.summary,`${i}.summary`),completed_at:er(r.completed_at,`${i}.completed_at`)}}function EC(e){let t="Native history_overflow.outcome_counts",i=ye(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Ne(i,new Set(r),t),{pass:ie(i.pass,`${t}.pass`),fail:ie(i.fail,`${t}.fail`),blocked:ie(i.blocked,`${t}.blocked`),"execution-error":ie(i["execution-error"],`${t}.execution-error`),recovery:ie(i.recovery,`${t}.recovery`)}}function CC(e){let t="Native history_overflow",i=ye(e,t);Ne(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=ie(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:er(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:er(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=EC(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function xC(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function PC(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function gn(e){let t=ye(e,"Native portable state");if(Ne(t,dC,"Native portable state"),t.schema!==vn)throw new Error(`Native portable state schema must be ${vn}`);let i=ue(t.name,"Native state name");if(!sC.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ut(t.spec_changes,"Native spec_changes",hC);Ci(r.map(s=>s.capability),"Native spec change capabilities");let n=ut(t.acceptance,"Native acceptance",gC);Ci(n.map(s=>s.id),"Native acceptance IDs");let a=ut(t.history,"Native history",SC);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:vn,name:i,language:ae(t.language,["en","zh-CN"],"Native state language"),phase:ae(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ae(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ie(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:fC(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ae(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:mC(t.workspace),loop:vC(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:yC(t.builder_handoff),blockers:ut(t.blockers,"Native blockers",NC),verification:t.verification===null?null:kC(t.verification),history:a,history_overflow:CC(t.history_overflow),verification_result:ae(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ae(t.verification_report,["verification.md"],"Native verification_report"),archived:Zi(t.archived,"Native archived"),created_at:er(t.created_at,"Native created_at")};return xC(o),PC(o),o}function RC(e,t){let i=(0,Tl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function wn(e){let t=await oC.readFile(e,"utf8");return gn(RC(t,"Native portable state"))}var ti="comet.native.v3",ii="comet.native.v2",ri="comet.native.v1",tr="comet.native.transition.v3",ir="comet.native.transition.v2",yn="comet.native.transition.v1";var Xh="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",LO=new RegExp(`^portable-archive-(${Xh})\\.json$`,"u"),BO=new RegExp(`^portable-migration-(${Xh})\\.json$`,"u");import{TextDecoder as OC}from"util";import{createHash as AC}from"node:crypto";import{constants as wo,promises as Ae}from"node:fs";import Qe from"node:path";import{TextDecoder as _C}from"node:util";function No(e,t){let i=Qe.relative(e,t);return i===""||!Qe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qe.sep}`)}function Qh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function IC(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function TC(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function yo(e,t){return M({...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 $l(e,t){let i=await Ae.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ae.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Ol(e,t,i){let r=Qe.resolve(e),n=Qe.resolve(t);if(!No(r,n))throw new Error(`${i} is outside its managed root`);let a=[await $l(r,i)],o=r;for(let s of Qe.relative(r,n).split(Qe.sep).filter(Boolean)){await dt(a,i),o=Qe.join(o,s);let c=await $l(o,i);if(!No(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await dt(a,i),a}async function dt(e,t){for(let i of e){let r=await Ae.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!IC(i,r)||await Ae.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function jC(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Et(e){let t=Qh(e.maxBytes),i=Qe.resolve(e.file),r=await Ol(e.root,Qe.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>$l(Qe.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await dt(r,e.label);let a=await Ae.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=TC(a),s=await Ae.realpath(i);if(!No(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>No(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?wo.O_RDONLY:wo.O_RDONLY|wo.O_NOFOLLOW|wo.O_NONBLOCK,l=await Ae.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Ae.lstat(i),Ae.realpath(i)]);if(await dt(r,e.label),await dt(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!yo(o,u)||!yo(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await jC(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),Ae.lstat(i),Ae.realpath(i)]);if(await dt(r,e.label),await dt(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!yo(o,v)||!yo(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:AC("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Zh(e){let t=await Et(e),i;try{i=new _C("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function Nn(e){let t=await Ol(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await Ae.readdir(e.directory,{withFileTypes:!0});else{let r=Qh(e.maxEntries);i=[];let n=await Ae.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await dt(t,e.label),{entries:i,verify:()=>dt(t,e.label)}}async function Hl(e){let t=await Ol(e.root,e.directory,e.label);return{verify:()=>dt(t,e.label)}}var t0=256*1024,i0=1024*1024,r0=16*1024;var n0=64*1024*1024;var a0=new OC("utf-8",{fatal:!0});import{createHash as Co}from"crypto";import{spawn as pm}from"node:child_process";import{promises as X}from"fs";import D from"path";import{createHash as nm}from"crypto";import{createReadStream as DC}from"fs";async function Dl(e){let t=nm("sha256");for await(let i of DC(e))t.update(i);return t.digest("hex")}function K(e){return nm("sha256").update(e).digest("hex")}var bo={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Ml=1e3,LC=8*1024*1024,BC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VC=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),FC=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),qC=new Set(["schema","include","exclude","hash"]),MC=new Set(["provider","gitSelection","physicalSelection","projection"]),WC=new Set(["provider","selection"]),zC=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),JC=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),GC=new Set(["schema","status","before","after"]),UC=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),KC=new Set(["path","hash","size","type","gitObjectId"]),YC=new Set(["path","size","type","reason"]),XC=new Set(["ref","hash","count"]),QC=new Set(["change-created","legacy-migration","explicit"]),ZC=new Set(["file","directory","other"]),ex=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"]),xo=/^[a-f0-9]{64}$/u,hm=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,tx=new Set(["EACCES","EPERM"]),lr=64*1024,Fl=64*1024,ix=6e4,rx=1e3,nx=2,Wl={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},ax={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function mm(e){let t=e.deadlineMs??ix;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Ze(e){return Math.max(0,e.deadlineAt-Date.now())}function $(e){return Ze(e)>=1}function Ll(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function sr(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function ox(e){let t={...ax,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function sx(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&D.win32.isAbsolute(r)?D.win32.resolve(r):"C:\\Windows",a=D.win32.join(n,"System32","taskkill.exe");if(!D.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=pm(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),rx),u.unref()}catch{d(!1)}});for(let s=0;s<nx;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function zl(e,t,i,r){let n=Ze(e);if(n<1)throw Ll();let a=e.gitProcess,o=pm(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=sx(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?Ll(v.error):Ll()}return{code:p,spawnError:s}});return{child:o,completion:f}}function vm(e){let t={...Wl,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function ko(e,t,i,r=Fl){let{child:n,completion:a}=zl(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>r&&(u=!0)}),n.stderr.on("data",p=>{if(c>=lr)return;let v=lr-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Bl(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function kn(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=zl(e,t,i,r.stdin!==void 0),c=[],l=Co("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,S=!1,y=!1,N=k=>{let E=0;for(;E<k.byteLength;){let b=k.indexOf(0,E),x=b<0?k.byteLength:b,g=k.subarray(E,x);if(!m&&g.byteLength>0&&(h.byteLength+g.byteLength>r.maxRecordBytes?(h=Buffer.alloc(0),m=!0,S=!0):h=Buffer.concat([h,g])),b<0)break;v+=1,h.byteLength===0&&!m&&(y=!0);let w=h.byteLength+1;!m&&v<=r.maxRecords&&p+w<=r.maxBytes?(c.push(h),p+=w):S=!0,h=Buffer.alloc(0),m=!1,E=b+1}};o.stdout.on("data",k=>{l.update(k),f+=k.byteLength,f>r.maxBytes&&(S=!0);let E=r.outputChunkBytes;if(E===void 0){N(k);return}for(let b=0;b<k.byteLength;b+=E)N(k.subarray(b,Math.min(k.byteLength,b+E)))}),o.stderr.on("data",k=>{if(d>=lr)return;let E=lr-d,b=Buffer.from(k).subarray(0,E);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:k,spawnError:E})=>{let b=r.acceptedExitCodes??[0];if(k!==null&&b.includes(k)&&E===null&&!y&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:S,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${E?`: ${E.message}`:y||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function So(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function cx(e,t,i){if(i.length===0)return new Set;let r=await kn(e,t,["check-ignore","--no-index","-z","--stdin"],{...Wl,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=So(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function lx(e,t,i){let{child:r,completion:n}=zl(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=lr)return;let d=lr-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function cr(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||D.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||D.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function ux(e,t){return e.map(i=>{let r=cr(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function dx(e){let t=D.resolve(e);for(;;){try{return await X.lstat(D.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=D.dirname(t);if(i===t)return!1;t=i}}async function gm(e,t,i,r={}){let n=D.resolve(t.projectRoot),a=D.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=D.relative(n,D.resolve(f)).replaceAll("\\","/"),v=cr(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await kn(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await kn(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await kn(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function wm(e){return{stageBefore:Bl(e.stagedBefore),combined:Bl(e.combined),stageAfter:Bl(e.stagedAfter)}}async function ym(e,t,i=Wl,r={}){let n=D.resolve(t.projectRoot);if(!await dx(n))return null;let a;try{a=await ko(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw sr(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await gm(e,t,i,r)}catch(y){throw sr(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=y=>{for(let N of y){let k=So(N),E=k.indexOf(" ");if(E<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(k.slice(0,E))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let x=cr(k.slice(E+1));if(x===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(x),b.stage==="0"&&d.set(x,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(x)}};p(s.records),p(l.records);let v=c.records.map(So),h=ux(v,"combined"),m=new Set(h.filter(y=>!u.has(y))),S=new Set(h.filter((y,N)=>!u.has(y)&&v[N].endsWith("/")));for(let y of f)S.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:wm(o)}}function oi(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function am(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function fx(e,t){return!oi(e.stageBefore,e.stageAfter)||!oi(e.stageAfter,t.stageBefore)||!oi(e.combined,t.combined)||!oi(t.stageBefore,t.stageAfter)}async function Nm(e,t,i,r,n){let a;try{a=await gm(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw sr(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=wm(a),c=am(o)||am(s),l=fx(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:K(`comet.native.git-selection-overflow.v2
|
|
152
|
-
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var
|
|
148
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=_l(l,t);else if(i)Gh(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=_l(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Gh(f))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&n.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function sC(e){return[...ir(e)].map(({line:t,body:i})=>({line:t,body:i}))}function yo(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function cC(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Tl(e,t,i,r=[],n="content-hash"){let a=yo(i),o=t.replaceAll("\\","/").trim(),s=r.map(yo);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${j(QE,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function jl(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function lC(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of ir(e)){n=s+1;let c=o?Il(a):null;c?.level===1&&(oo(c.text)==="acceptanceExamples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function $l(e,t="brief.md",i=yn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=lC(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of ir(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let p=f[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of ir(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),jl(o.map(l=>Tl("brief-example",t,l.join(`
|
|
149
|
+
`),[],r)),"Brief",r)}function Ol(e,t="spec.md",i=yn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Tl("spec-scenario",t,[o.title,...o.body].join(`
|
|
150
|
+
`),o.context,r)),o=null}};for(let{line:c,body:l}of ir(e)){let u=l?Il(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=yo(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),jl(n,"Specification",r)}function Kh(e,t="spec.md",i=yn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Tl("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of ir(e)){let f=d?Il(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let p=u.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||_l(u,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),jl(n,"Specification mandatory requirements",r)}function uC(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||cC(i)||qh.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=qh.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!tC.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function dC(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!eC.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function Yh(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=dC(i,r),a=n.acceptance_id;if(typeof a!="string"||!ZE.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return uC(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function Xh(e){let t=sC(e);if(t.some(({line:l,body:u})=>!u&&(l===Mh||l===Wh)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===Mh?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===Wh?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
|
|
151
|
+
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=Yh(o),c=fC(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function fC(e){let t=Yh([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var Dl=jr(Ki(),1);import{promises as hC}from"node:fs";var Nn="comet.native.v4",No="comet.native.local-execution.v4";var Qh=["multi-session","single-session"];var mC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gC=/^A[1-9][0-9]*$/u,wC=/^[a-f0-9]{64}$/u,yC=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 ye(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ne(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function de(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Hl(e,t){return e===null?null:de(e,t)}function em(e,t){let i=de(e,t);if(!wC.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function rr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ie(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function NC(e,t){return e===null?null:ie(e,t,Number.MIN_SAFE_INTEGER)}function ae(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ut(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function bo(e,t){return ut(e,t,(i,r)=>de(i,`${t}[${r}]`))}function Pi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function nr(e,t){let i=de(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Ll(e,t,i=!1){let r=de(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function He(e,t){let i=ye(e,t);return Ne(i,new Set(["text","truncated"]),t),{text:de(i.text,`${t}.text`,{empty:!0}),truncated:rr(i.truncated,`${t}.truncated`)}}function bC(e,t){let i=`Native spec_changes[${t}]`,r=ye(e,i);Ne(r,new Set(["capability","operation","source"]),i);let n=de(r.capability,`${i}.capability`);if(!vC.test(n))throw new Error(`${i}.capability is invalid`);let a=ae(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Ll(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function kC(e){let t="Native workspace",i=ye(e,t);Ne(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=ae(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Hl(i.change_branch,`${t}.change_branch`),a=Hl(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:ae(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function SC(e){let t="Native loop",i=ye(e,t);Ne(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=bo(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Pi(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:ae(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ae(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ie(i.goal_cycle,`${t}.goal_cycle`,1),iteration:ie(i.iteration,`${t}.iteration`),attempt:ie(i.attempt,`${t}.attempt`),retry_epoch:ie(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ie(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ie(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ie(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Hl(i.next_action,`${t}.next_action`)}}function EC(e,t){let i=`Native acceptance[${t}]`,r=ye(e,i);Ne(r,new Set(["id","source","text","result","reason"]),i);let n=de(r.id,`${i}.id`);if(!gC.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Ll(r.source,`${i}.source`),text:de(r.text,`${i}.text`),result:ae(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:He(r.reason,`${i}.reason`)}}function CC(e,t){let i=`Native builder_handoff.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["name","result","note"]),i),{name:He(r.name,`${i}.name`),result:ae(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:He(r.note,`${i}.note`)}}function xC(e){let t="Native builder_handoff",i=ye(e,t);Ne(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=bo(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Pi(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:ye(i.review,`${t}.review`);return n&&Ne(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:de(i.candidate_id,`${t}.candidate_id`),identity_provider:de(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:de(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),summary:He(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ut(i.checks,`${t}.checks`,CC),checks_truncated:rr(i.checks_truncated,`${t}.checks_truncated`),known_limits:ut(i.known_limits,`${t}.known_limits`,(a,o)=>He(a,`${t}.known_limits[${o}]`)),known_limits_truncated:rr(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ae(n.status,["passed"],`${t}.review.status`),summary:He(n.summary,`${t}.review.summary`),reviewer_execution_ref:de(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:nr(i.submitted_at,`${t}.submitted_at`)}}function PC(e,t){let i=`Native blockers[${t}]`,r=ye(e,i);Ne(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=bo(r.acceptance_ids,`${i}.acceptance_ids`);return Pi(n,`${i}.acceptance_ids`),{owner:ae(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:He(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:ae(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function RC(e,t){let i=`Native verification.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:de(r.id,`${i}.id`),name:He(r.name,`${i}.name`),argv_display:ut(r.argv_display,`${i}.argv_display`,(n,a)=>He(n,`${i}.argv_display[${a}]`)),argv_truncated:rr(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Ll(r.cwd_ref,`${i}.cwd_ref`,!0),status:ae(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:NC(r.exit_code,`${i}.exit_code`),duration_ms:ie(r.duration_ms,`${i}.duration_ms`)}}function AC(e){let t="Native verification",i=ye(e,t);Ne(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ut(i.checks,`${t}.checks`,RC);Pi(r.map(a=>a.id),`${t}.checks IDs`);let n=de(i.identity_provider,`${t}.identity_provider`);return{candidate_id:de(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:de(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),attempt:ie(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ae(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ae(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:He(i.summary,`${t}.summary`),risks:ut(i.risks,`${t}.risks`,(a,o)=>He(a,`${t}.risks[${o}]`)),risks_truncated:rr(i.risks_truncated,`${t}.risks_truncated`),completed_at:nr(i.completed_at,`${t}.completed_at`)}}function _C(e,t){let i=`Native history[${t}]`,r=ye(e,i);Ne(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=bo(r.unresolved_ids,`${i}.unresolved_ids`);return Pi(n,`${i}.unresolved_ids`),{goal_cycle:ie(r.goal_cycle,`${i}.goal_cycle`,1),iteration:ie(r.iteration,`${i}.iteration`),attempt:ie(r.attempt,`${i}.attempt`),outcome:ae(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:He(r.summary,`${i}.summary`),completed_at:nr(r.completed_at,`${i}.completed_at`)}}function IC(e){let t="Native history_overflow.outcome_counts",i=ye(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Ne(i,new Set(r),t),{pass:ie(i.pass,`${t}.pass`),fail:ie(i.fail,`${t}.fail`),blocked:ie(i.blocked,`${t}.blocked`),"execution-error":ie(i["execution-error"],`${t}.execution-error`),recovery:ie(i.recovery,`${t}.recovery`)}}function TC(e){let t="Native history_overflow",i=ye(e,t);Ne(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=ie(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:nr(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:nr(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=IC(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function jC(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function $C(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function bn(e){let t=ye(e,"Native portable state");if(Ne(t,yC,"Native portable state"),t.schema!==Nn)throw new Error(`Native portable state schema must be ${Nn}`);let i=de(t.name,"Native state name");if(!mC.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ut(t.spec_changes,"Native spec_changes",bC);Pi(r.map(s=>s.capability),"Native spec change capabilities");let n=ut(t.acceptance,"Native acceptance",EC);Pi(n.map(s=>s.id),"Native acceptance IDs");let a=ut(t.history,"Native history",_C);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Nn,name:i,language:ae(t.language,["en","zh-CN"],"Native state language"),phase:ae(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ae(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ie(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:em(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:em(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ae(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:kC(t.workspace),loop:SC(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:xC(t.builder_handoff),blockers:ut(t.blockers,"Native blockers",PC),verification:t.verification===null?null:AC(t.verification),history:a,history_overflow:TC(t.history_overflow),verification_result:ae(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ae(t.verification_report,["verification.md"],"Native verification_report"),archived:rr(t.archived,"Native archived"),created_at:nr(t.created_at,"Native created_at")};return jC(o),$C(o),o}function OC(e,t){let i=(0,Dl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function kn(e){let t=await hC.readFile(e,"utf8");return bn(OC(t,"Native portable state"))}var ii="comet.native.v3",ri="comet.native.v2",ni="comet.native.v1",ar="comet.native.transition.v3",or="comet.native.transition.v2",Sn="comet.native.transition.v1";var im="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",t0=new RegExp(`^portable-archive-(${im})\\.json$`,"u"),i0=new RegExp(`^portable-migration-(${im})\\.json$`,"u");import{TextDecoder as qC}from"util";import{createHash as HC}from"node:crypto";import{constants as ko,promises as Ae}from"node:fs";import Qe from"node:path";import{TextDecoder as DC}from"node:util";function Eo(e,t){let i=Qe.relative(e,t);return i===""||!Qe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qe.sep}`)}function rm(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function LC(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function BC(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function So(e,t){return M({...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 Bl(e,t){let i=await Ae.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ae.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Vl(e,t,i){let r=Qe.resolve(e),n=Qe.resolve(t);if(!Eo(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Bl(r,i)],o=r;for(let s of Qe.relative(r,n).split(Qe.sep).filter(Boolean)){await dt(a,i),o=Qe.join(o,s);let c=await Bl(o,i);if(!Eo(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await dt(a,i),a}async function dt(e,t){for(let i of e){let r=await Ae.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!LC(i,r)||await Ae.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function VC(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Et(e){let t=rm(e.maxBytes),i=Qe.resolve(e.file),r=await Vl(e.root,Qe.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Bl(Qe.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await dt(r,e.label);let a=await Ae.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=BC(a),s=await Ae.realpath(i);if(!Eo(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Eo(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ko.O_RDONLY:ko.O_RDONLY|ko.O_NOFOLLOW|ko.O_NONBLOCK,l=await Ae.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Ae.lstat(i),Ae.realpath(i)]);if(await dt(r,e.label),await dt(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!So(o,u)||!So(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await VC(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),Ae.lstat(i),Ae.realpath(i)]);if(await dt(r,e.label),await dt(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!So(o,v)||!So(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:HC("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function nm(e){let t=await Et(e),i;try{i=new DC("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function En(e){let t=await Vl(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await Ae.readdir(e.directory,{withFileTypes:!0});else{let r=rm(e.maxEntries);i=[];let n=await Ae.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await dt(t,e.label),{entries:i,verify:()=>dt(t,e.label)}}async function Fl(e){let t=await Vl(e.root,e.directory,e.label);return{verify:()=>dt(t,e.label)}}var w0=256*1024,y0=1024*1024,N0=16*1024;var b0=64*1024*1024;var k0=new qC("utf-8",{fatal:!0});import{createHash as Ao}from"crypto";import{spawn as wm}from"node:child_process";import{promises as X}from"fs";import D from"path";import{createHash as lm}from"crypto";import{createReadStream as WC}from"fs";async function ql(e){let t=lm("sha256");for await(let i of WC(e))t.update(i);return t.digest("hex")}function K(e){return lm("sha256").update(e).digest("hex")}var Co={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Ul=1e3,zC=8*1024*1024,JC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GC=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),UC=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),KC=new Set(["schema","include","exclude","hash"]),YC=new Set(["provider","gitSelection","physicalSelection","projection"]),XC=new Set(["provider","selection"]),QC=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),ZC=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),ex=new Set(["schema","status","before","after"]),tx=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),ix=new Set(["path","hash","size","type","gitObjectId"]),rx=new Set(["path","size","type","reason"]),nx=new Set(["ref","hash","count"]),ax=new Set(["change-created","legacy-migration","explicit"]),ox=new Set(["file","directory","other"]),sx=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"]),_o=/^[a-f0-9]{64}$/u,ym=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,cx=new Set(["EACCES","EPERM"]),pr=64*1024,Jl=64*1024,lx=6e4,ux=1e3,dx=2,Kl={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},fx={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Nm(e){let t=e.deadlineMs??lx;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Ze(e){return Math.max(0,e.deadlineAt-Date.now())}function $(e){return Ze(e)>=1}function Ml(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function dr(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function px(e){let t={...fx,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function hx(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&D.win32.isAbsolute(r)?D.win32.resolve(r):"C:\\Windows",a=D.win32.join(n,"System32","taskkill.exe");if(!D.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=wm(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),ux),u.unref()}catch{d(!1)}});for(let s=0;s<dx;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function Yl(e,t,i,r){let n=Ze(e);if(n<1)throw Ml();let a=e.gitProcess,o=wm(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=hx(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?Ml(v.error):Ml()}return{code:p,spawnError:s}});return{child:o,completion:f}}function bm(e){let t={...Kl,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function xo(e,t,i,r=Jl){let{child:n,completion:a}=Yl(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>r&&(u=!0)}),n.stderr.on("data",p=>{if(c>=pr)return;let v=pr-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Wl(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function xn(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Yl(e,t,i,r.stdin!==void 0),c=[],l=Ao("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,S=!1,y=!1,k=N=>{let E=0;for(;E<N.byteLength;){let b=N.indexOf(0,E),x=b<0?N.byteLength:b,g=N.subarray(E,x);if(!m&&g.byteLength>0&&(h.byteLength+g.byteLength>r.maxRecordBytes?(h=Buffer.alloc(0),m=!0,S=!0):h=Buffer.concat([h,g])),b<0)break;v+=1,h.byteLength===0&&!m&&(y=!0);let w=h.byteLength+1;!m&&v<=r.maxRecords&&p+w<=r.maxBytes?(c.push(h),p+=w):S=!0,h=Buffer.alloc(0),m=!1,E=b+1}};o.stdout.on("data",N=>{l.update(N),f+=N.byteLength,f>r.maxBytes&&(S=!0);let E=r.outputChunkBytes;if(E===void 0){k(N);return}for(let b=0;b<N.byteLength;b+=E)k(N.subarray(b,Math.min(N.byteLength,b+E)))}),o.stderr.on("data",N=>{if(d>=pr)return;let E=pr-d,b=Buffer.from(N).subarray(0,E);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:E})=>{let b=r.acceptedExitCodes??[0];if(N!==null&&b.includes(N)&&E===null&&!y&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:S,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${E?`: ${E.message}`:y||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function Po(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function mx(e,t,i){if(i.length===0)return new Set;let r=await xn(e,t,["check-ignore","--no-index","-z","--stdin"],{...Kl,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=Po(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function vx(e,t,i){let{child:r,completion:n}=Yl(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=pr)return;let d=pr-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function fr(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||D.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||D.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function gx(e,t){return e.map(i=>{let r=fr(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function wx(e){let t=D.resolve(e);for(;;){try{return await X.lstat(D.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=D.dirname(t);if(i===t)return!1;t=i}}async function km(e,t,i,r={}){let n=D.resolve(t.projectRoot),a=D.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=D.relative(n,D.resolve(f)).replaceAll("\\","/"),v=fr(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await xn(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await xn(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await xn(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Sm(e){return{stageBefore:Wl(e.stagedBefore),combined:Wl(e.combined),stageAfter:Wl(e.stagedAfter)}}async function Em(e,t,i=Kl,r={}){let n=D.resolve(t.projectRoot);if(!await wx(n))return null;let a;try{a=await xo(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw dr(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await km(e,t,i,r)}catch(y){throw dr(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=y=>{for(let k of y){let N=Po(k),E=N.indexOf(" ");if(E<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(N.slice(0,E))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let x=fr(N.slice(E+1));if(x===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(x),b.stage==="0"&&d.set(x,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(x)}};p(s.records),p(l.records);let v=c.records.map(Po),h=gx(v,"combined"),m=new Set(h.filter(y=>!u.has(y))),S=new Set(h.filter((y,k)=>!u.has(y)&&v[k].endsWith("/")));for(let y of f)S.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:Sm(o)}}function si(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function um(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function yx(e,t){return!si(e.stageBefore,e.stageAfter)||!si(e.stageAfter,t.stageBefore)||!si(e.combined,t.combined)||!si(t.stageBefore,t.stageAfter)}async function Cm(e,t,i,r,n){let a;try{a=await km(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw dr(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=Sm(a),c=um(o)||um(s),l=yx(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:K(`comet.native.git-selection-overflow.v2
|
|
152
|
+
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var Nx=(1n<<256n)-1n;function bx(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function dm(e){let t=D.resolve(e.paths.projectRoot),i=D.resolve(e.paths.nativeRoot),r=D.resolve(e.paths.runtimeDir),n=D.resolve(e.paths.configFile),a=D.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>Ze(e.execution)>=1?!0:(p=!0,h=!0,!1),S=N=>{let E=Buffer.from(`${N.type}\0${N.path}`,"utf8"),b=Ao("sha256").update("comet.native.physical-selection-record.v1\0").update(E).digest();for(let x=0;x<c.length;x+=1)c[x]^=b[x];if(l=l+BigInt(`0x${b.toString("hex")}`)&Nx,d+=1,f+=E.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(N)},y=async N=>{if(h||!m())return;let E;try{E=await X.opendir(N)}catch(C){if(!m())return;if(!se(C)&&!oe(C)||N===t&&se(C))throw C;v||=oe(C),p||=se(C),h=!0;return}if(!m()){try{await E.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let b=!1,x;try{for(;!h&&m();){let C;try{C=await E.read()}catch(G){if(!m())break;if(!se(G)&&!oe(G)||N===t&&se(G))throw G;v||=oe(G),p||=se(G),h=!0;break}if(!m()||C===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let O=D.join(N,C.name),T=Sx(t,O);if(O===n||O===a||et(i,O)||et(r,O)||e.denylist.some(G=>et(G,O))||ct(T)!==null)continue;if(!m())break;let he;try{he=await X.lstat(O)}catch(G){if(!m())break;if(!se(G)&&!oe(G))throw G;if(v=!0,S({path:T,type:"other"}),s.push({path:T,size:null,type:"file",reason:se(G)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!m())break;continue}if(!m())break;let Q=bx(he);if(Q==="directory"){if(Px(e.policy,T))continue;if(!m())break;let G;try{G=await X.realpath(O)}catch(at){if(!m())break;if(!se(at)&&!oe(at))throw at;if(v=!0,S({path:T,type:Q}),s.push({path:T,size:null,type:"directory",reason:se(at)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!m())break;continue}if(!m())break;if(!V(e.physicalProjectRoot,G)||et(e.physicalNativeRoot,G))continue;if(S({path:T,type:Q}),await e.hooks?.afterNode?.(T),!m()||(await y(O),h))break;continue}if(S({path:T,type:Q}),await e.hooks?.afterNode?.(T),!m()||h)break}}catch(C){b=!0,x=C}let g;try{await E.close()}catch(C){g=C}let w=m();if(b)throw x;if(w&&g!==void 0&&g.code!=="ERR_DIR_CLOSED")throw g};await y(t),m(),p?(o.length=0,d=0,f=0):(o.sort((N,E)=>N.path.localeCompare(E.path,"en")),s.sort((N,E)=>N.path.localeCompare(E.path,"en")));let k=p?K(`comet.native.physical-selection-incomplete.v1
|
|
153
153
|
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):K(`comet.native.physical-selection.v1
|
|
154
|
-
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:
|
|
155
|
-
`)}function
|
|
156
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function
|
|
154
|
+
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:k,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function xm(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 kx(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!xm(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function Pm(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function fm(e,t){let r=(await xo(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!ym.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return K(`gitlink:${r}`)}async function pm(e,t){let i=await fm(e,t),r=await vx(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await fm(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function Cn(e,t){if(ct(t)!==null)return!1;let i=D.resolve(e.projectRoot,...t.split("/"));return!et(D.resolve(e.nativeRoot),i)&&!et(D.resolve(e.runtimeDir),i)}function Sx(e,t){return D.relative(e,t).split(D.sep).join("/")}function Ex(e,t){return t.map(i=>D.resolve(e,...i.split(/[\\/]/u)))}function et(e,t){let i=D.resolve(e),r=D.resolve(t);return r===i||V(i,r)}function se(e){return cx.has(e.code??"")}function oe(e){return e.code==="ENOENT"}function Xl(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
155
|
+
`)}function Cx(e,t){return K(`comet.native.snapshot-policy.v1
|
|
156
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function zl(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function xx(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function hm(e){let t=wo(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?xx(n):void 0;if(a&&!a())return!1;let o=zl(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=zl(i,c,a),o===null||o.size===0)return!1}return zl(i,o,a)?.has(i.length)??!1}}function Rm(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>wo(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>wo(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=Cx(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(hm),excludeMatchers:i.map(hm),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function Px(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function mm(e,t,i){if(!e)return!0;let r=()=>$(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function Pn(e,t,i){let r=JSON.stringify(i);return K(`${e}
|
|
157
157
|
${Buffer.byteLength(t)}:${t}
|
|
158
|
-
${Buffer.byteLength(r)}:${r}`)}function ql(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Eo(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!ql(i))return e.splice(t,1),i}return null}function ai(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function bx(e,t,i,r){if(!$(r))return{status:"budget-exhausted"};let n;try{n=await X.open(e,"r")}catch(c){if(!$(r))return{status:"budget-exhausted"};throw c}if(!$(r))return await n.close(),{status:"budget-exhausted"};let a=Co("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!$(r))return{status:"budget-exhausted"};let c=await n.stat();if(!$(r))return{status:"budget-exhausted"};if(!c.isFile()||!ai(i,c))return{status:"changed"};for(;;){if(!$(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!$(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!$(r))return{status:"budget-exhausted"};let d=await n.stat();return $(r)?!d.isFile()||!ai(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function De(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Le(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function or(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ft(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Em(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=D.posix.normalize(e);if(i!==e||D.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function kx(e,t){let i=De(e,`Native snapshot entry ${t}`);Le(i,KC,`Native snapshot entry ${t}`);let r=Em(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!xo.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:ft(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!hm.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function Sx(e,t){let i=De(e,`Native snapshot omission ${t}`);if(Le(i,YC,`Native snapshot omission ${t}`),!ZC.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!ex.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Em(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:ft(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function Ex(e){let t=De(e,"Native snapshot omission overflow");if(Le(t,XC,"Native snapshot omission overflow"),typeof t.hash!="string"||!xo.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:or(t.count,"Native snapshot omission overflow count")}}function ar(e,t){let i=De(e,t);if(Le(i,JC,t),typeof i.hash!="string"||!xo.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=ft(i.recordCount,`${t} recordCount`),n=ft(i.storedRecordCount,`${t} storedRecordCount`),a=ft(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function dm(e){let t=De(e,"Native Git selection evidence");if(Le(t,zC,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=ar(t.stageBefore,"Native Git selection stageBefore"),r=ar(t.combined,"Native Git selection combined"),n=ar(t.stageAfter,"Native Git selection stageAfter"),a=ar(t.finalStageBefore,"Native Git selection finalStageBefore"),o=ar(t.finalCombined,"Native Git selection finalCombined"),s=ar(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!oi(i,n)||!oi(n,a)||!oi(r,o)||!oi(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function fm(e,t){let i=De(e,t);if(Le(i,UC,t),typeof i.hash!="string"||!xo.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=ft(i.visitedNodeCount,`${t} visitedNodeCount`),n=ft(i.recordCount,`${t} recordCount`),a=ft(i.storedRecordCount,`${t} storedRecordCount`),o=ft(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function Cx(e){let t=De(e,"Native physical selection evidence");if(Le(t,GC,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=fm(t.before,"Native physical selection before"),r=fm(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!bm(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function xi(e){let t=De(e,"Native content snapshot manifest");if(Le(t,VC,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!QC.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=De(t.capture,"Native content snapshot capture");if(Le(b,MC,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=b.gitSelection===void 0?void 0:dm(b.gitSelection),g=b.physicalSelection===void 0?void 0:Cx(b.physicalSelection),w=null;if(b.projection!==void 0){let C=De(b.projection,"Native content snapshot projection");if(Le(C,WC,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...C.selection===void 0?{}:{selection:dm(C.selection)}}}if(b.provider==="git"){if(g||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...g?{physicalSelection:g}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=De(t.limits,"Native content snapshot limits");Le(r,FC,"Native content snapshot limits");let n={maxFiles:or(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:or(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:or(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:or(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:or(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=De(t.policy,"Native snapshot policy");if(Le(b,qC,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Sm({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(kx),s=t.omitted.map(Sx),c=ft(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:Ex(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,x)=>b+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Ml||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.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(b=>b.reason==="physical-enumeration-limit"),S=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...S])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,N=y?.status==="overflow"||y?.status==="overflow-and-changed",k=y?.status==="changed"||y?.status==="overflow-and-changed";if(N!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(k!==(S.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,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Jl(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}async function Cm(e,t,i={}){let r=xi(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=D.resolve(e.projectRoot),a=mm(i),o=vm(i.gitSelectionLimits),s=await ym(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(km(s).filter(g=>bn(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>bn(e,g)),d=(g,w)=>w.some(C=>g===C||g.startsWith(`${C}/`)),f=g=>d(g,l),p=g=>d(g,u),v=[...r.entries.map(g=>g.path),...r.omitted.flatMap(g=>g.type==="directory"?[g.path,`${g.path}/`]:[g.path])].filter(g=>!c.has(g)&&!f(g)&&!p(g)),h=await cx(a,n,v),m=r.entries.filter(g=>!f(g.path)&&!p(g.path)&&bn(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await Nm(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let S=[...s.omissions];for(let g of l)S.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((g,w)=>g.path.localeCompare(w.path,"en"));let y=r.omitted.filter(g=>f(g.path)||p(g.path)||!bn(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(w=>w.startsWith(`${g.path}/`)):!0);for(let g of S)y.some(w=>w.path===g.path&&w.reason===g.reason)||y.push(g);y.sort((g,w)=>g.path.localeCompare(w.path,"en"));let N=r.omissionOverflow?.count??0,k=r.omissionOverflow?.hash??K("comet.native.snapshot-omission-overflow.v1");s.overflow&&(N+=s.overflow.count,k=Sn(k,"git-selection",{source:"git-selection",...s.overflow}));let E=g=>{N+=1,k=Sn(k,"omission",g)};for(;y.length>Ml;){let g=Eo(y);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");E(g)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+N===0,entries:m,omitted:y,omittedCount:y.length+N,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:N}}:{}}),x=b();for(;Jl(x)>r.limits.maxManifestBytes;){let g=Eo(y);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");E(g),x=b()}return xi(x)}function xx(e,t){if(!BC.test(t))throw new Error(`Invalid Native change name: ${t}`);return D.join(U(e,t),"baseline-manifest.json")}async function xm(e,t={}){let i={maxFiles:t.limits?.maxFiles??bo.maxFiles,maxFileBytes:t.limits?.maxFileBytes??bo.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??bo.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??bo.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=Sm(t.policy),n=mm({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=vm(t.gitSelectionLimits),o=ox(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=D.resolve(e.projectRoot),c=await X.realpath(s),l=D.resolve(e.nativeRoot),u=await X.realpath(l),d=D.resolve(e.runtimeDir),f=D.resolve(e.configFile),p=D.join(s,".comet","current-change.json"),v=gx(s,t.denylist??[]),h=[],m=[],S=new Map,y=new Map,N=0,k=0,E=K("comet.native.snapshot-omission-overflow.v1"),b=0,x=!1,g=null,w=_=>{k+=1,E=Sn(E,"omission",_)},C=_=>{if(N+=1,m.length<Ml){m.push(_);return}if(ql(_)){let A=Eo(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),m.push(_);return}w(_)},O=_=>{N+=_.count,k+=_.count,E=Sn(E,"git-selection",{source:"git-selection",..._})},T=_=>{k+=1,E=Sn(E,"manifest-entry",{reason:"manifest-size",entry:_})},pe=async(_,A)=>{h.push(_),b+=_.size,S.set(_.path,A),x||(x=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Q=(_,A)=>{let I=h.findIndex(Y=>Y.path===_);if(I<0)return;let[L]=h.splice(I,1);b-=L.size,S.delete(_),C(A)},G=async(_,A,I,L)=>{if(!I.isFile()||I.isSymbolicLink()||!$(n))return;let Y;try{Y=await X.realpath(_)}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!$(n)||!V(c,Y)||et(u,Y))return;if(h.length>=i.maxFiles){C({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){C({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){C({path:A,size:I.size,type:"file",reason:"total-size"});return}let q,H,ee;try{if(q=await bx(Y,I.size,I,n),q.status==="budget-exhausted"||!$(n))return;if(q.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!$(n)||(ee=await X.realpath(_),!$(n)))return;H=await X.lstat(_)}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if($(n)){if(q.bytes!==I.size||ee!==Y||!ai(I,q.finalStat)||!ai(q.finalStat,H)||!H.isFile()||H.isSymbolicLink()||H.size!==I.size||H.mtimeMs!==I.mtimeMs||H.ctimeMs!==I.ctimeMs){C({path:A,size:H.isFile()?H.size:null,type:H.isFile()?"file":"other",reason:"changed-during-read"});return}$(n)&&await pe({path:A,hash:q.hash,size:H.size,type:"file",...L===void 0?{}:{gitObjectId:L}},{kind:"file",target:_,realTarget:Y,stat:H})}},at=async(_,A,I)=>{if(!$(n))return;let L,Y,q;try{if(L=await X.readlink(_,{encoding:"buffer"}),!$(n)||(q=await X.lstat(_),!$(n)))return;Y=await X.readlink(_,{encoding:"buffer"})}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:null,type:"other",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!$(n))return;if(!q.isSymbolicLink()||!ai(I,q)||q.mtimeMs!==I.mtimeMs||q.ctimeMs!==I.ctimeMs||!L.equals(Y)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let H=L.byteLength;if(h.length>=i.maxFiles){C({path:A,size:H,type:"other",reason:"file-count"});return}if(H>i.maxFileBytes){C({path:A,size:H,type:"other",reason:"file-size"});return}if(b+H>i.maxTotalBytes){C({path:A,size:H,type:"other",reason:"total-size"});return}let ee=Co("sha256").update("symlink\0").update(L).digest("hex");$(n)&&await pe({path:A,hash:ee,size:H,type:"file"},{kind:"symlink",target:_,rawTarget:L,stat:q})},We=async()=>{for(let[_,A]of[...S]){if(!$(n))return;if(A.kind==="file"){let H,ee;try{if(H=await X.realpath(A.target),!$(n))return;ee=await X.lstat(A.target)}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"file",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!$(n))return;(H!==A.realTarget||!ee.isFile()||ee.isSymbolicLink()||!ai(A.stat,ee)||ee.size!==A.stat.size||ee.mtimeMs!==A.stat.mtimeMs||ee.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:ee.isFile()?ee.size:null,type:ee.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let H,ee;try{if(H=await X.lstat(A.target),!$(n))return;ee=await X.readlink(A.target,{encoding:"buffer"})}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"other",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!$(n))return;(!H.isSymbolicLink()||!ai(A.stat,H)||H.mtimeMs!==A.stat.mtimeMs||H.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ee))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,L;try{if(I=await X.realpath(A.target),!$(n))return;L=await X.lstat(A.target)}catch{if(!$(n))return;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!$(n))return;if(!(I===A.realTarget&&L.isDirectory()&&!L.isSymbolicLink()&&ai(A.stat,L)&&V(c,I)&&!et(u,I))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let q;try{if(!$(n))return;q=await cm(n,I)}catch(H){if(sr(H))throw H;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!$(n))return;q.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):q.hash!==A.hash&&Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!$(n))return;try{let I=await X.lstat(A);if(!$(n))return;C({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!$(n))return;if(oe(I))continue;if(!se(I))throw I;C({path:_,size:null,type:"file",reason:"unreadable"})}}},Pe=await ym(n,e,a,t.gitSelectionHooks);if(Pe===null){let _=await om({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let L of _.records){if(L.type!=="file"&&L.type!=="symlink"||S.has(L.path))continue;if(Ze(n)<1)break;if(!um(r,L.path,n))continue;if(Ze(n)<1)break;let Y=D.resolve(s,...L.path.split("/")),q;try{q=await X.lstat(Y)}catch(H){if(!$(n))break;if(!se(H)&&!oe(H))throw H;C({path:L.path,size:null,type:"file",reason:oe(H)?"changed-during-read":"unreadable"});continue}if(Ze(n)<1)break;if(L.type==="symlink"&&q.isSymbolicLink()){if(await at(Y,L.path,q),Ze(n)<1)break;continue}if(L.type!=="file"||!q.isFile()||q.isSymbolicLink()){C({path:L.path,size:q.isFile()?q.size:null,type:q.isDirectory()?"directory":q.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await G(Y,L.path,q),Ze(n)<1)break}Ze(n)>=1&&await We();let A=await om({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=mx(_.evidence,A.evidence);g=I.evidence;for(let L of[..._.omissions,...A.omissions,...I.omissions])m.some(Y=>Y.path===L.path&&Y.reason===L.reason)||C(L)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let R=xi(_);for(let Z of R.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);I=A.size>0}let L=new Set,Y=!0;try{let R=await kn(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)I=!1,Y=!1,A.clear();else for(let Z of R.records){let te=So(Z),we=te.indexOf(" "),he=we<0?null:cr(te.slice(we+1));if(we!==1||he===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");te[0]!=="H"&&L.add(he)}}catch(R){if(sr(R))throw R;I=!1,Y=!1,A.clear()}let q=new Set;try{let R=await ko(n,s,["ls-files","--modified","-z"],Fl);for(let Z of R.toString("utf8").split("\0")){let te=cr(Z);te!==null&&q.add(te)}}catch{I=!1,Y=!1,A.clear()}let H=new Set,ee=new Set;for(let R of km(Pe)){if(S.has(R)||!bn(e,R))continue;if(Ze(n)<1)break;if(!um(r,R,n))continue;if(Ze(n)<1)break;let Z=D.resolve(s,...R.split("/"));if(Z===f||Z===p||et(d,Z)||v.some(Re=>et(Re,Z)))continue;if(Pe.gitlinks.has(R)){if(h.length>=i.maxFiles){C({path:R,size:0,type:"file",reason:"file-count"});continue}let Re,ta;try{[Re,ta]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(ta.isSymbolicLink()||!ta.isDirectory()||!V(c,Re)||et(u,Re)){C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let ji=await cm(n,Re);if(ji.dirty){C({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await pe({path:R,hash:ji.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:Re,stat:ta,hash:ji.hash})}catch(ji){if(sr(ji))throw ji;C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let te;try{te=await X.lstat(Z)}catch(Re){if(oe(Re)&&Pe.tracked.has(R)){y.set(R,Z);continue}if(!se(Re)&&!oe(Re))throw Re;C({path:R,size:null,type:"file",reason:oe(Re)?"changed-during-read":"unreadable"});continue}if(te.isSymbolicLink()){await at(Z,R,te);continue}if(!te.isFile()){Pe.nestedRepositories.has(R)||C({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let we=Pe.trackedObjectIds.get(R),he=we?A.get(R):void 0;if(I&&he?.gitObjectId!==void 0&&he.gitObjectId===we&&!L.has(R)&&!q.has(R)){if(h.length>=i.maxFiles){C({path:R,size:he.size,type:"file",reason:"file-count"});continue}if(he.size>i.maxFileBytes){C({path:R,size:he.size,type:"file",reason:"file-size"});continue}if(b+he.size>i.maxTotalBytes){C({path:R,size:he.size,type:"file",reason:"total-size"});continue}h.push({...he}),b+=he.size,H.add(R);continue}let Cd=Y&&!L.has(R)&&!q.has(R)?we:void 0;await G(Z,R,te,Cd),Cd!==void 0&&ee.add(R)}if(await We(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Nm(n,e,a,Pe,t.gitSelectionHooks?.outputChunkBytes),H.size>0||I&&ee.size>0){let R=await ko(n,s,["ls-files","--modified","-z"],Fl),Z=new Set;for(let te of R.toString("utf8").split("\0")){let we=cr(te);we!==null&&Z.add(we)}for(let te of H){if(!Z.has(te))continue;let we=h.find(he=>he.path===te);Q(te,{path:te,size:we?.size??null,type:"file",reason:"changed-during-read"})}for(let te of ee){if(!Z.has(te))continue;let we=h.find(he=>he.path===te);we&&delete we.gitObjectId}}for(let R of Pe.omissions)C(R);Pe.overflow&&O(Pe.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let oy=Pe===null?{provider:"physical-tree",...g?{physicalSelection:g}:{}}:{provider:"git",...Pe.evidence?{gitSelection:Pe.evidence}:{}},Ed=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:oy,createdAt:(t.now??new Date).toISOString(),complete:N===0,limits:i,...r?{policy:r.manifest}:{},entries:h,omitted:m,omittedCount:N,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:k}}:{}}),Ns=Ed();for(;Jl(Ns)>i.maxManifestBytes;){if(m.filter(A=>!ql(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I<A;I+=1){let L=Eo(m);if(L===null)break;w(L)}}else if(h.length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let I of h.splice(-A))N+=1,T(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Ns=Ed()}return Ns}async function Gl(e,t,i={}){let n=(await Ee(e.projectRoot))?.native.snapshot??El;return xm(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Po(e,t){let i=xx(e,t),r=le(e,i);await J(r,i);try{let n=await Zh({root:r,file:i,maxBytes:LC,label:"Native baseline snapshot manifest"});return xi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as zx}from"crypto";import Jx from"path";var Be=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{constants as Ro,promises as tt}from"node:fs";import it from"node:path";import{TextDecoder as Vx}from"node:util";import Hx from"path";var Tx=Rr(Ji(),1);var J0=4*1024*1024;var jx=null;function $x(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Pm(e,t){return(...i)=>{let r=jx;if(r===null)return t(...i);let n=$x(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var X0=Pm("hookWritePolicy",async e=>(await ml(e))?.hook??{allow_paths:[]});var Rm=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Cn(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function En(e,t){let i=Cn(e,t);if(Hx.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function Dx(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Am(e){if(!e.run_id)return null;let t=Cn(e,"run_id"),i=Cn(e,"skill"),r=Cn(e,"skill_version"),n=Cn(e,"skill_hash"),a=En(e,"pending_ref"),o=En(e,"trajectory_ref"),s=En(e,"context_ref"),c=En(e,"artifacts_ref"),l=En(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:Rm(e,"current_step"),iteration:u,pending:Rm(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:Dx(e)}}var GH=256*1024;var Lx=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function Bx(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=Am(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Ul(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!Lx.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return Bx(t)}var ur={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function _o(e,t){let i=it.relative(e,t);return i===""||!it.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${it.sep}`)}function Fx(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ao(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function qx(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Io(e,t,i){let r=Be[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=it.resolve(e),a=it.resolve(n,...r.slice(8).split("/"));if(!_o(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function _m(e){let t=await tt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await tt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Mx(e,t){let i=it.resolve(e),r=it.resolve(t);if(!_o(i,r))throw new Error("Native Run path is outside its change");let n=[await _m(i)],a=i;for(let o of it.relative(i,r).split(it.sep).filter(Boolean)){a=it.join(a,o);let s;try{s=await _m(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!_o(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Im(e){for(let t of e){let i=await tt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!qx(t,i)||await tt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function Wx(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function To(e,t,i,r,n){let a=await Mx(e,it.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await tt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=Fx(o),c=await tt.realpath(t);if(!_o(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Ro.O_RDONLY:Ro.O_RDONLY|Ro.O_NOFOLLOW|Ro.O_NONBLOCK,u;try{u=await tt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Im(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Ao(s,d)||!Ao(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await Wx(u,i,r);await n?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Im(a),!m.isFile()||m.isSymbolicLink()||S!==c||!Ao(s,h)||!Ao(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new Vx("utf-8",{fatal:!0}).decode(v)}catch(N){throw new Error(`${r} is not valid UTF-8`,{cause:N})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function Tm(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Kl(e){return Ul(e)}async function dr(e,t){let i=Io(e,"stateRef"),r=await To(e,i,ur.runStateBytes,"Native Run state",t);return r?Ul(Tm(r.text,"Native Run state")):null}async function Pi(e,t,i){let r=Io(e,"trajectoryRef",t),n=await To(e,r,ur.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>ur.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ur.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function jm(e,t,i){return(await To(e,Io(e,"trajectoryRef",t),ur.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function jo(e,t,i){let r=await To(e,Io(e,"checkpointRef",t),ur.checkpointBytes,"Native Run checkpoint",i);return r?Tm(r.text,"Native Run checkpoint"):null}var Gx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Yl(e){return zx("sha256").update(e).digest("hex")}function Ux(e,t){if(!Gx.test(t))throw new Error(`Invalid Native change name: ${t}`);return Jx.join(U(e,t),"trajectory.jsonl")}function Kx(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function Yx(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function Xx(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=Kx(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
|
|
159
|
-
`)])}catch(d){if(!
|
|
160
|
-
${t}`).digest("hex")}async function
|
|
158
|
+
${Buffer.byteLength(r)}:${r}`)}function Gl(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Ro(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Gl(i))return e.splice(t,1),i}return null}function oi(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Rx(e,t,i,r){if(!$(r))return{status:"budget-exhausted"};let n;try{n=await X.open(e,"r")}catch(c){if(!$(r))return{status:"budget-exhausted"};throw c}if(!$(r))return await n.close(),{status:"budget-exhausted"};let a=Ao("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!$(r))return{status:"budget-exhausted"};let c=await n.stat();if(!$(r))return{status:"budget-exhausted"};if(!c.isFile()||!oi(i,c))return{status:"changed"};for(;;){if(!$(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!$(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!$(r))return{status:"budget-exhausted"};let d=await n.stat();return $(r)?!d.isFile()||!oi(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function De(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Le(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function ur(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ft(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Am(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=D.posix.normalize(e);if(i!==e||D.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function Ax(e,t){let i=De(e,`Native snapshot entry ${t}`);Le(i,ix,`Native snapshot entry ${t}`);let r=Am(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!_o.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:ft(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!ym.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function _x(e,t){let i=De(e,`Native snapshot omission ${t}`);if(Le(i,rx,`Native snapshot omission ${t}`),!ox.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!sx.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Am(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:ft(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function Ix(e){let t=De(e,"Native snapshot omission overflow");if(Le(t,nx,"Native snapshot omission overflow"),typeof t.hash!="string"||!_o.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:ur(t.count,"Native snapshot omission overflow count")}}function lr(e,t){let i=De(e,t);if(Le(i,ZC,t),typeof i.hash!="string"||!_o.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=ft(i.recordCount,`${t} recordCount`),n=ft(i.storedRecordCount,`${t} storedRecordCount`),a=ft(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function vm(e){let t=De(e,"Native Git selection evidence");if(Le(t,QC,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=lr(t.stageBefore,"Native Git selection stageBefore"),r=lr(t.combined,"Native Git selection combined"),n=lr(t.stageAfter,"Native Git selection stageAfter"),a=lr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=lr(t.finalCombined,"Native Git selection finalCombined"),s=lr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!si(i,n)||!si(n,a)||!si(r,o)||!si(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function gm(e,t){let i=De(e,t);if(Le(i,tx,t),typeof i.hash!="string"||!_o.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=ft(i.visitedNodeCount,`${t} visitedNodeCount`),n=ft(i.recordCount,`${t} recordCount`),a=ft(i.storedRecordCount,`${t} storedRecordCount`),o=ft(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function Tx(e){let t=De(e,"Native physical selection evidence");if(Le(t,ex,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=gm(t.before,"Native physical selection before"),r=gm(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!xm(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function Ri(e){let t=De(e,"Native content snapshot manifest");if(Le(t,GC,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!ax.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=De(t.capture,"Native content snapshot capture");if(Le(b,YC,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=b.gitSelection===void 0?void 0:vm(b.gitSelection),g=b.physicalSelection===void 0?void 0:Tx(b.physicalSelection),w=null;if(b.projection!==void 0){let C=De(b.projection,"Native content snapshot projection");if(Le(C,XC,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...C.selection===void 0?{}:{selection:vm(C.selection)}}}if(b.provider==="git"){if(g||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...g?{physicalSelection:g}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=De(t.limits,"Native content snapshot limits");Le(r,UC,"Native content snapshot limits");let n={maxFiles:ur(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:ur(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:ur(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:ur(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:ur(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=De(t.policy,"Native snapshot policy");if(Le(b,KC,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Rm({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(Ax),s=t.omitted.map(_x),c=ft(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:Ix(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,x)=>b+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Ul||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.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(b=>b.reason==="physical-enumeration-limit"),S=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...S])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,k=y?.status==="overflow"||y?.status==="overflow-and-changed",N=y?.status==="changed"||y?.status==="overflow-and-changed";if(k!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(S.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,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Xl(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}async function _m(e,t,i={}){let r=Ri(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=D.resolve(e.projectRoot),a=Nm(i),o=bm(i.gitSelectionLimits),s=await Em(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(Pm(s).filter(g=>Cn(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>Cn(e,g)),d=(g,w)=>w.some(C=>g===C||g.startsWith(`${C}/`)),f=g=>d(g,l),p=g=>d(g,u),v=[...r.entries.map(g=>g.path),...r.omitted.flatMap(g=>g.type==="directory"?[g.path,`${g.path}/`]:[g.path])].filter(g=>!c.has(g)&&!f(g)&&!p(g)),h=await mx(a,n,v),m=r.entries.filter(g=>!f(g.path)&&!p(g.path)&&Cn(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await Cm(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let S=[...s.omissions];for(let g of l)S.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((g,w)=>g.path.localeCompare(w.path,"en"));let y=r.omitted.filter(g=>f(g.path)||p(g.path)||!Cn(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(w=>w.startsWith(`${g.path}/`)):!0);for(let g of S)y.some(w=>w.path===g.path&&w.reason===g.reason)||y.push(g);y.sort((g,w)=>g.path.localeCompare(w.path,"en"));let k=r.omissionOverflow?.count??0,N=r.omissionOverflow?.hash??K("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,N=Pn(N,"git-selection",{source:"git-selection",...s.overflow}));let E=g=>{k+=1,N=Pn(N,"omission",g)};for(;y.length>Ul;){let g=Ro(y);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");E(g)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+k===0,entries:m,omitted:y,omittedCount:y.length+k,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:k}}:{}}),x=b();for(;Xl(x)>r.limits.maxManifestBytes;){let g=Ro(y);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");E(g),x=b()}return Ri(x)}function jx(e,t){if(!JC.test(t))throw new Error(`Invalid Native change name: ${t}`);return D.join(U(e,t),"baseline-manifest.json")}async function Im(e,t={}){let i={maxFiles:t.limits?.maxFiles??Co.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Co.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Co.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Co.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=Rm(t.policy),n=Nm({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=bm(t.gitSelectionLimits),o=px(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=D.resolve(e.projectRoot),c=await X.realpath(s),l=D.resolve(e.nativeRoot),u=await X.realpath(l),d=D.resolve(e.runtimeDir),f=D.resolve(e.configFile),p=D.join(s,".comet","current-change.json"),v=Ex(s,t.denylist??[]),h=[],m=[],S=new Map,y=new Map,k=0,N=0,E=K("comet.native.snapshot-omission-overflow.v1"),b=0,x=!1,g=null,w=_=>{N+=1,E=Pn(E,"omission",_)},C=_=>{if(k+=1,m.length<Ul){m.push(_);return}if(Gl(_)){let A=Ro(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),m.push(_);return}w(_)},O=_=>{k+=_.count,N+=_.count,E=Pn(E,"git-selection",{source:"git-selection",..._})},T=_=>{N+=1,E=Pn(E,"manifest-entry",{reason:"manifest-size",entry:_})},he=async(_,A)=>{h.push(_),b+=_.size,S.set(_.path,A),x||(x=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Q=(_,A)=>{let I=h.findIndex(Y=>Y.path===_);if(I<0)return;let[L]=h.splice(I,1);b-=L.size,S.delete(_),C(A)},G=async(_,A,I,L)=>{if(!I.isFile()||I.isSymbolicLink()||!$(n))return;let Y;try{Y=await X.realpath(_)}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!$(n)||!V(c,Y)||et(u,Y))return;if(h.length>=i.maxFiles){C({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){C({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){C({path:A,size:I.size,type:"file",reason:"total-size"});return}let q,H,ee;try{if(q=await Rx(Y,I.size,I,n),q.status==="budget-exhausted"||!$(n))return;if(q.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!$(n)||(ee=await X.realpath(_),!$(n)))return;H=await X.lstat(_)}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if($(n)){if(q.bytes!==I.size||ee!==Y||!oi(I,q.finalStat)||!oi(q.finalStat,H)||!H.isFile()||H.isSymbolicLink()||H.size!==I.size||H.mtimeMs!==I.mtimeMs||H.ctimeMs!==I.ctimeMs){C({path:A,size:H.isFile()?H.size:null,type:H.isFile()?"file":"other",reason:"changed-during-read"});return}$(n)&&await he({path:A,hash:q.hash,size:H.size,type:"file",...L===void 0?{}:{gitObjectId:L}},{kind:"file",target:_,realTarget:Y,stat:H})}},at=async(_,A,I)=>{if(!$(n))return;let L,Y,q;try{if(L=await X.readlink(_,{encoding:"buffer"}),!$(n)||(q=await X.lstat(_),!$(n)))return;Y=await X.readlink(_,{encoding:"buffer"})}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:null,type:"other",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!$(n))return;if(!q.isSymbolicLink()||!oi(I,q)||q.mtimeMs!==I.mtimeMs||q.ctimeMs!==I.ctimeMs||!L.equals(Y)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let H=L.byteLength;if(h.length>=i.maxFiles){C({path:A,size:H,type:"other",reason:"file-count"});return}if(H>i.maxFileBytes){C({path:A,size:H,type:"other",reason:"file-size"});return}if(b+H>i.maxTotalBytes){C({path:A,size:H,type:"other",reason:"total-size"});return}let ee=Ao("sha256").update("symlink\0").update(L).digest("hex");$(n)&&await he({path:A,hash:ee,size:H,type:"file"},{kind:"symlink",target:_,rawTarget:L,stat:q})},We=async()=>{for(let[_,A]of[...S]){if(!$(n))return;if(A.kind==="file"){let H,ee;try{if(H=await X.realpath(A.target),!$(n))return;ee=await X.lstat(A.target)}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"file",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!$(n))return;(H!==A.realTarget||!ee.isFile()||ee.isSymbolicLink()||!oi(A.stat,ee)||ee.size!==A.stat.size||ee.mtimeMs!==A.stat.mtimeMs||ee.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:ee.isFile()?ee.size:null,type:ee.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let H,ee;try{if(H=await X.lstat(A.target),!$(n))return;ee=await X.readlink(A.target,{encoding:"buffer"})}catch(R){if(!$(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"other",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!$(n))return;(!H.isSymbolicLink()||!oi(A.stat,H)||H.mtimeMs!==A.stat.mtimeMs||H.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ee))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,L;try{if(I=await X.realpath(A.target),!$(n))return;L=await X.lstat(A.target)}catch{if(!$(n))return;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!$(n))return;if(!(I===A.realTarget&&L.isDirectory()&&!L.isSymbolicLink()&&oi(A.stat,L)&&V(c,I)&&!et(u,I))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let q;try{if(!$(n))return;q=await pm(n,I)}catch(H){if(dr(H))throw H;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!$(n))return;q.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):q.hash!==A.hash&&Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!$(n))return;try{let I=await X.lstat(A);if(!$(n))return;C({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!$(n))return;if(oe(I))continue;if(!se(I))throw I;C({path:_,size:null,type:"file",reason:"unreadable"})}}},Pe=await Em(n,e,a,t.gitSelectionHooks);if(Pe===null){let _=await dm({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let L of _.records){if(L.type!=="file"&&L.type!=="symlink"||S.has(L.path))continue;if(Ze(n)<1)break;if(!mm(r,L.path,n))continue;if(Ze(n)<1)break;let Y=D.resolve(s,...L.path.split("/")),q;try{q=await X.lstat(Y)}catch(H){if(!$(n))break;if(!se(H)&&!oe(H))throw H;C({path:L.path,size:null,type:"file",reason:oe(H)?"changed-during-read":"unreadable"});continue}if(Ze(n)<1)break;if(L.type==="symlink"&&q.isSymbolicLink()){if(await at(Y,L.path,q),Ze(n)<1)break;continue}if(L.type!=="file"||!q.isFile()||q.isSymbolicLink()){C({path:L.path,size:q.isFile()?q.size:null,type:q.isDirectory()?"directory":q.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await G(Y,L.path,q),Ze(n)<1)break}Ze(n)>=1&&await We();let A=await dm({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=kx(_.evidence,A.evidence);g=I.evidence;for(let L of[..._.omissions,...A.omissions,...I.omissions])m.some(Y=>Y.path===L.path&&Y.reason===L.reason)||C(L)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let R=Ri(_);for(let Z of R.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);I=A.size>0}let L=new Set,Y=!0;try{let R=await xn(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)I=!1,Y=!1,A.clear();else for(let Z of R.records){let te=Po(Z),we=te.indexOf(" "),me=we<0?null:fr(te.slice(we+1));if(we!==1||me===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");te[0]!=="H"&&L.add(me)}}catch(R){if(dr(R))throw R;I=!1,Y=!1,A.clear()}let q=new Set;try{let R=await xo(n,s,["ls-files","--modified","-z"],Jl);for(let Z of R.toString("utf8").split("\0")){let te=fr(Z);te!==null&&q.add(te)}}catch{I=!1,Y=!1,A.clear()}let H=new Set,ee=new Set;for(let R of Pm(Pe)){if(S.has(R)||!Cn(e,R))continue;if(Ze(n)<1)break;if(!mm(r,R,n))continue;if(Ze(n)<1)break;let Z=D.resolve(s,...R.split("/"));if(Z===f||Z===p||et(d,Z)||v.some(Re=>et(Re,Z)))continue;if(Pe.gitlinks.has(R)){if(h.length>=i.maxFiles){C({path:R,size:0,type:"file",reason:"file-count"});continue}let Re,ra;try{[Re,ra]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(ra.isSymbolicLink()||!ra.isDirectory()||!V(c,Re)||et(u,Re)){C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Hi=await pm(n,Re);if(Hi.dirty){C({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await he({path:R,hash:Hi.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:Re,stat:ra,hash:Hi.hash})}catch(Hi){if(dr(Hi))throw Hi;C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let te;try{te=await X.lstat(Z)}catch(Re){if(oe(Re)&&Pe.tracked.has(R)){y.set(R,Z);continue}if(!se(Re)&&!oe(Re))throw Re;C({path:R,size:null,type:"file",reason:oe(Re)?"changed-during-read":"unreadable"});continue}if(te.isSymbolicLink()){await at(Z,R,te);continue}if(!te.isFile()){Pe.nestedRepositories.has(R)||C({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let we=Pe.trackedObjectIds.get(R),me=we?A.get(R):void 0;if(I&&me?.gitObjectId!==void 0&&me.gitObjectId===we&&!L.has(R)&&!q.has(R)){if(h.length>=i.maxFiles){C({path:R,size:me.size,type:"file",reason:"file-count"});continue}if(me.size>i.maxFileBytes){C({path:R,size:me.size,type:"file",reason:"file-size"});continue}if(b+me.size>i.maxTotalBytes){C({path:R,size:me.size,type:"file",reason:"total-size"});continue}h.push({...me}),b+=me.size,H.add(R);continue}let Ad=Y&&!L.has(R)&&!q.has(R)?we:void 0;await G(Z,R,te,Ad),Ad!==void 0&&ee.add(R)}if(await We(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Cm(n,e,a,Pe,t.gitSelectionHooks?.outputChunkBytes),H.size>0||I&&ee.size>0){let R=await xo(n,s,["ls-files","--modified","-z"],Jl),Z=new Set;for(let te of R.toString("utf8").split("\0")){let we=fr(te);we!==null&&Z.add(we)}for(let te of H){if(!Z.has(te))continue;let we=h.find(me=>me.path===te);Q(te,{path:te,size:we?.size??null,type:"file",reason:"changed-during-read"})}for(let te of ee){if(!Z.has(te))continue;let we=h.find(me=>me.path===te);we&&delete we.gitObjectId}}for(let R of Pe.omissions)C(R);Pe.overflow&&O(Pe.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let py=Pe===null?{provider:"physical-tree",...g?{physicalSelection:g}:{}}:{provider:"git",...Pe.evidence?{gitSelection:Pe.evidence}:{}},Rd=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:py,createdAt:(t.now??new Date).toISOString(),complete:k===0,limits:i,...r?{policy:r.manifest}:{},entries:h,omitted:m,omittedCount:k,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:N}}:{}}),Ps=Rd();for(;Xl(Ps)>i.maxManifestBytes;){if(m.filter(A=>!Gl(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I<A;I+=1){let L=Ro(m);if(L===null)break;w(L)}}else if(h.length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let I of h.splice(-A))k+=1,T(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Ps=Rd()}return Ps}async function Ql(e,t,i={}){let n=(await Ee(e.projectRoot))?.native.snapshot??Al;return Im(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Io(e,t){let i=jx(e,t),r=ue(e,i);await J(r,i);try{let n=await nm({root:r,file:i,maxBytes:zC,label:"Native baseline snapshot manifest"});return Ri(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as Qx}from"crypto";import Zx from"path";var Be=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{constants as To,promises as tt}from"node:fs";import it from"node:path";import{TextDecoder as Gx}from"node:util";import Mx from"path";var Bx=jr(Ki(),1);var lH=4*1024*1024;var Vx=null;function Fx(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Tm(e,t){return(...i)=>{let r=Vx;if(r===null)return t(...i);let n=Fx(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var hH=Tm("hookWritePolicy",async e=>(await Nl(e))?.hook??{allow_paths:[]});var jm=(e,t)=>{let i=e[t];return i==null?null:String(i)};function An(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Rn(e,t){let i=An(e,t);if(Mx.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function Wx(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function $m(e){if(!e.run_id)return null;let t=An(e,"run_id"),i=An(e,"skill"),r=An(e,"skill_version"),n=An(e,"skill_hash"),a=Rn(e,"pending_ref"),o=Rn(e,"trajectory_ref"),s=Rn(e,"context_ref"),c=Rn(e,"artifacts_ref"),l=Rn(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:jm(e,"current_step"),iteration:u,pending:jm(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:Wx(e)}}var fD=256*1024;var zx=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function Jx(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=$m(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Zl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!zx.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return Jx(t)}var hr={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function $o(e,t){let i=it.relative(e,t);return i===""||!it.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${it.sep}`)}function Ux(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function jo(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Kx(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Oo(e,t,i){let r=Be[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=it.resolve(e),a=it.resolve(n,...r.slice(8).split("/"));if(!$o(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function Om(e){let t=await tt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await tt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Yx(e,t){let i=it.resolve(e),r=it.resolve(t);if(!$o(i,r))throw new Error("Native Run path is outside its change");let n=[await Om(i)],a=i;for(let o of it.relative(i,r).split(it.sep).filter(Boolean)){a=it.join(a,o);let s;try{s=await Om(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!$o(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Hm(e){for(let t of e){let i=await tt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Kx(t,i)||await tt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function Xx(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Ho(e,t,i,r,n){let a=await Yx(e,it.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await tt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=Ux(o),c=await tt.realpath(t);if(!$o(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?To.O_RDONLY:To.O_RDONLY|To.O_NOFOLLOW|To.O_NONBLOCK,u;try{u=await tt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Hm(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!jo(s,d)||!jo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await Xx(u,i,r);await n?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Hm(a),!m.isFile()||m.isSymbolicLink()||S!==c||!jo(s,h)||!jo(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new Gx("utf-8",{fatal:!0}).decode(v)}catch(k){throw new Error(`${r} is not valid UTF-8`,{cause:k})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function Dm(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function eu(e){return Zl(e)}async function mr(e,t){let i=Oo(e,"stateRef"),r=await Ho(e,i,hr.runStateBytes,"Native Run state",t);return r?Zl(Dm(r.text,"Native Run state")):null}async function Ai(e,t,i){let r=Oo(e,"trajectoryRef",t),n=await Ho(e,r,hr.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>hr.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${hr.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function Lm(e,t,i){return(await Ho(e,Oo(e,"trajectoryRef",t),hr.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Do(e,t,i){let r=await Ho(e,Oo(e,"checkpointRef",t),hr.checkpointBytes,"Native Run checkpoint",i);return r?Dm(r.text,"Native Run checkpoint"):null}var eP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function tu(e){return Qx("sha256").update(e).digest("hex")}function tP(e,t){if(!eP.test(t))throw new Error(`Invalid Native change name: ${t}`);return Zx.join(U(e,t),"trajectory.jsonl")}function iP(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function rP(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function nP(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=iP(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
|
|
159
|
+
`)])}catch(d){if(!rP(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:tu(t),targetHash:tu(l),tailHash:tu(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function aP(e,t){let i=tP(e,t);await J(ue(e,i),i);let r=U(e,t),n=await Lm(r,Be.trajectoryRef);return n===null?{status:"clean",file:i}:nP(i,Buffer.from(n))}async function Bm(e,t){let i=await aP(e,t);return"inspection"in i?i.inspection:i}import{createHash as oP}from"node:crypto";import{promises as Lo}from"node:fs";import xt from"node:path";var _n=/^[a-f0-9]{64}$/u,Vm=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,sP=16*1024,ru=process.platform,cP=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function vr(e){return cP.has(e)}function Wm(e,t){let i=xt.relative(e,t);return xt.isAbsolute(i)||i===".."||i.startsWith(`..${xt.sep}`)?null:i.replaceAll("\\","/")||"."}function zm(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Jm(e,t){if(e.length===0||zm(e)||e.includes("\\")||xt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=xt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function nu(e,t){return oP("sha256").update(`${e}
|
|
160
|
+
${t}`).digest("hex")}async function Fm(e,t){let i=await Lo.realpath(t),r=await Lo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=ru==="win32"?xt.normalize(i).toLowerCase():i;return nu(e,`${n}
|
|
161
161
|
${r.dev}
|
|
162
162
|
${r.ino}
|
|
163
|
-
${r.birthtimeMs}`)}async function
|
|
163
|
+
${r.birthtimeMs}`)}async function qm(e,t){let i=await Lo.realpath(t),r=await Lo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=ru==="win32"?xt.normalize(i).toLowerCase():i;return nu(e,n)}function lP(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 iu(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||zm(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Gm(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(iu(e.changeBranch,"Native workspace change branch"),iu(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 uP(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Vm.test(t.baseCommit)||typeof t.targetCommit!="string"||!Vm.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");iu(t.targetBranch,"Native workspace Git target branch")}function Bo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!_n.test(String(t.projectRootId))||!_n.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");lP(t.capturedAt),Jm(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&&!_n.test(String(t.projectRootPathId))||a&&!_n.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!_n.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&uP(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(Gm(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 dP(e,t){return xt.join(U(e,t),"workspace.json")}function fP(e,t){let i=dP(e,t),r=ue(e,i),n=Wm(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Jm(n,"Native workspace file ref")}}async function pP(e,t){try{let i=fP(e,t),r=await ne({root:i.root,ref:i.ref,maxBytes:sP});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function In(e,t){let i=be(e.projectRoot),r={projectRoot:xt.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await Pt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await Tn({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function hP(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Wm(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=be(e.paths.projectRoot),r=i.isGitWorktree?yi(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:yi(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([Fm("comet.native.workspace-project-root.v2",e.paths.projectRoot),Fm("comet.native.workspace-native-root.v2",e.paths.nativeRoot),qm("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),qm("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&&Gm(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:nu("comet.native.workspace-session.v2",`${s}
|
|
164
164
|
${c}
|
|
165
|
-
${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Oo(p),p}async function Pt(e,t){let i=await oP(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Oo(i),i)}async function Ho(e){Oo(e.identity);let t=await sP({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Ql==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function Rn(e){if(Oo(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 Ho(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=be(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function Mm(e,t){let i=await Pt(e,t);if(i===null)return null;let r=await Rn({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var Jm=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],lP=new Set(Jm),Gm=new Set([...Jm,"minimum_runtime_version","revision"]),uP=new Set([...Gm,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),dP=new Set(["capability","operation","source","base_hash"]),fP=new Set(["shape","build","verify","archive"]),pP=new Set(["implicit","confirmed"]),hP=new Set(["pending","pass","fail"]),si="comet-state.yaml",tu=/^[a-f0-9]{64}$/u,Um=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mP=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Do=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Ri=class extends Error{constructor(i,r){super(i!==ti||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Lo=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},An=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Bo=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},zD=ro("en");function In(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Km(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Vo(e){if(!Um.test(e))throw new Error(`Invalid Native change name: ${e}`)}function vP(e){if(!Um.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Ym(e,t){if(e.length===0||Rt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function gP(e,t){let i=In(e,`spec_changes[${t}]`);if(Km(i,dP,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(vP(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&Ym(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!tu.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!tu.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function wP(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 ru(e,t){if(Km(e,t,si),typeof e.name!="string")throw new Error("Native change name is required");if(Vo(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"||!fP.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&&!pP.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(gP),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!hP.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"&&Ym(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!wP(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function rr(e){let t=In(e,si);if(t.schema!==ri)throw new Error(`Expected ${ri}`);return{schema:ri,...ru(t,lP)}}function _n(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function eu(e,t,i){if(e===null)return null;let r=typeof e=="string"?mP.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function yP(e){if(e==null)return null;if(typeof e!="string"||!tu.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function NP(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 nr(e){let t=In(e,si);if(t.schema!==ii)throw new Error(`Expected ${ii}`);if(_n(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ii} minimum_runtime_version must be 2`);return{schema:ii,minimum_runtime_version:2,revision:_n(t.revision,"Native v2 revision"),...ru(t,Gm)}}function ni(e){let t=In(e,si);if(t.schema!==ti){if(t.schema===ri||t.schema===ii){let o=t.schema===ri?rr(t):nr(t);throw new Do(o.name,o.schema)}throw new Ri(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=_n(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Ri(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=_n(t.revision,"Native revision"),n=ru(t,uP),a=yP(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ti,minimum_runtime_version:3,revision:r,verification_protocol:NP(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:eu(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:eu(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:eu(t.partial_allowance,"Native partial_allowance","allowances")}}function Xm(e){let t=In(e,si);if(t.schema===ri){let n=rr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ti}`}}if(t.schema===ii){let n=nr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ti}`}}if(t.schema!==ti){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 Ri(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=_n(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Ri(t.schema,i).message};let r=ni(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function fe(e,t){Vo(t);let i=Rt.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Fo(e,t){let i=U(e,t),r=Rt.join(i,"schema-migration.json");await J(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await zm.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Qm(e,t){let i=U(e,t),r=Rt.join(i,"checkpoint-journal.json");await J(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await zm.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Zm(e,t=Rt.dirname(e)){let i=Rt.relative(t,e).split(Rt.sep).join("/"),r=await ne({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,iu.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function nu(e,t){let i=Rt.join(fe(e,t),si);await J(e.nativeRoot,i);let r=Xm(await Zm(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Fo(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await bP(e,r.state),r)}async function ev(e,t){let i=Rt.join(fe(e,t),si);await J(e.nativeRoot,i);let r=Xm(await Zm(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function bP(e,t){if(await Po(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function At(e,t){let i=await nu(e,t);if(i.status==="migration-required")throw new Do(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Ri(i.schema,i.minimumRuntimeVersion);return await Mm(e,t),i.state}import{promises as WI}from"fs";import{promises as au}from"fs";import tv from"path";var iv=["outcome","scope","nonGoals","acceptanceExamples"],kP=[...iv,"constraints","decisions","openQuestions","verificationExpectations"],SP=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],rv={maxFileBytes:cn};function nv(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
|
|
166
|
-
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function
|
|
167
|
-
`))}function PP(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(sv))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(sv))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=cv(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:lv(e.markdown)},markdown:e.markdown}}function RP(e,t){return uv(e.id,t.id)}function uv(e,t){return e<t?-1:e>t?1:0}function dv(e){let t=cv(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(PP).sort((d,f)=>uv(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Al(e.briefMarkdown,t,jn.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(..._l(f,d.source,jn.maxAcceptanceCriteria-a.length)),a.push(...zh(f,d.source,jn.maxAcceptanceCriteria-a.length)));if(a.sort(RP),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>jn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${jn.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:lv(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=j(xP,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(CP,u)}}var Mo={maxSpecs:64,maxFileBytes:cn,maxTotalBytes:4*1024*1024};async function pr(e){if(e.specChanges.length>Mo.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ne({root:e.changeDir,ref:e.briefRef,maxBytes:Mo.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ne({root:e.changeDir,ref:n.source,maxBytes:Mo.maxFileBytes});if(i+=a.size,i>Mo.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:dv({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import AP from"path";var cu="comet.selection.v2",_P=16*1024;function pv(e){return AP.join(e,".comet","current-change.json")}function IP(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function fv(e){return e===null||typeof e=="string"}function TP(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!IP(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&&!fv(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:cu,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==cu)throw new Error(`current change selection schema must be ${cu}`);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(!fv(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 hv(e){let t;try{let r=pv(e),{bytes:n}=await Ui(r,_P,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...TP(t)}}import{promises as ER}from"node:fs";import yu from"node:path";var mu=Rr(Ji(),1);import{promises as Pv}from"node:fs";import Ve from"node:path";import{execFileSync as jP}from"node:child_process";var $P=3e4,OP=8*1024*1024,lu=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function HP(e,t){try{return jP("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:$P,maxBuffer:OP,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new lu(e,t,r)}}function Wo(e,t){return HP(e,t).trim()}import du from"node:path";import{promises as mv}from"node:fs";var zo=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var uu="comet.native.supervisor.v2",LP=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function BP(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function VP(e,t){return du.join(Zt(e,t),"supervisor")}function vv(e,t){return du.join(VP(e,t),"state.json")}function gv(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==uu)throw new Error(`Native Supervisor state schema must be ${uu}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if($n(t.integration.targetCommit,"Native Supervisor target commit"),$n(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&$n(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if($n(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function On(e,t){try{let i=await mv.readFile(vv(e,t),"utf8"),r=JSON.parse(i);return gv(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function fu(e,t){gv(t),await mv.mkdir(e.changesRuntimeDir,{recursive:!0}),await Ye(vv(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function $n(e,t){if(!LP.test(e))throw new Error(`${t} must be a Git commit`)}function FP(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function wv(e){$n(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:uu,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function pu(e){let t=BP(e.parent),i=gi(e.paths.projectRoot,t);if(!i)return null;let r=gi(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Dt(e.paths.projectRoot).map(o=>du.resolve(o)).find(o=>be(o).currentBranch===t);if(!n)return null;let a=wv({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return FP(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function yv(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var Nv="children.yaml",Hn="comet.native.children.v1",hr="comet.native.children.v2",Rv=hr,qP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bv=new Set(["schema","children"]),MP=new Set(["schema","acceptance_index","children"]),WP=new Set(["name","depends_on","covers"]),zP=new Set(["name","summary","depends_on"]),JP=new Set(["name","depends_on","covers"]);function Go(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function Jo(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function kv(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function hu(e,t){let i=Ve.normalize(Ve.resolve(e)),r=Ve.normalize(Ve.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function GP(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function Sv(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function UP(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Rv&&e.acceptance_index){let n=i.requiredAcceptanceIds??t??[],a=Object.keys(e.acceptance_index);r.missing=n.filter(c=>!(c in e.acceptance_index)),r.extra=a.filter(c=>!n.includes(c));let o=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of n){let l=o.get(c),u=e.acceptance_index[c];l&&u&&(u.source!==l.source||u.text!==l.text)&&r.mismatched.push(c)}let s=new Set(a);for(let c of e.children)r.unknownCovers.push(...c.covers.filter(l=>!s.has(l)));return r.uncovered=a.filter(c=>!Ev(e.children,c)),Cv(r)?r:null}if(e.schema===Hn&&t){let n=new Set(t);for(let a of e.children)r.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return r.uncovered=t.filter(a=>!Ev(e.children,a)),Cv(r)?r:null}return null}function Ev(e,t){return e.some(i=>i.covers.includes(t))}function Cv(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Av(e){let t=new Set(e.acceptance.filter(({source:i})=>i===e.brief).map(({id:i})=>i));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let i=[...e.history].reverse().find(({outcome:r})=>r==="fail");for(let r of i?.unresolved_ids??[])t.add(r)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function KP(e){let t=Go(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=Go(n,`Native children acceptance_index.${r}`);if(Jo(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function YP(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=Object.keys(e),a=r.filter(c=>!(c in e)),o=n.filter(c=>!r.includes(c));if(a.length>0||o.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${o.join(", ")||"none"}`);let s=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of r){let l=s.get(c);if(!l)continue;let u=e[c];if(u.source!==l.source||u.text!==l.text){let d=["source","text"].filter(f=>u[f]!==l[f]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function XP(e,t,i={}){let r=(0,mu.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=Go(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Hn&&a!==hr)throw Jo(n,bv,"Native children contract"),new Error(`Native children schema must be ${Hn} or ${hr}`);let o=a===Hn?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Jo(n,o==="indexed-v2"?MP:bv,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,p)=>{let v=Go(f,`Native child ${p}`);if(Jo(v,o==="indexed-v2"?JP:o==="summary-v2"?zP:WP,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!qP.test(v.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:h?v.summary:null,depends_on:kv(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?kv(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let p=f.depends_on.filter(v=>!u.has(v));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}GP(c);let d=i.policy==="advisory";if(a===Rv){if(o==="indexed-v2"){let f=KP(n.acceptance_index);d||YP(f,t,i);let p=Object.keys(f);return d||Sv(c,p,p),{schema:hr,acceptance_index:f,children:c}}return{schema:hr,children:c}}return t&&!d&&Sv(c,t),{schema:Hn,children:c}}async function _v(e){let t=Ve.join(e.changeDir,Nv);try{await Pv.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await ne({root:e.changeDir,ref:Nv}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=XP(i.text,e.acceptanceIds,n);return{contract:a,size:i.size,drift:r?UP(a,e.acceptanceIds,e.validation??{}):null}}function QP(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function ZP(e){let t=QP(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function Iv(e){try{let t=await ne({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return ZP(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Tv(e){return j("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function eR(e){let t=Dt(e.projectRoot);t.some(r=>hu(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Ve.resolve(n)))]){let n=await Ee(r);n&&i.push({projectRoot:r,paths:await kt(r,n.native.artifact_root),parent:hu(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function tR(e,t){let i=Ve.join(e.paths.changesDir,t,"comet-state.yaml");try{return await wn(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function iR(e,t){let i;try{i=await Pv.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Ve.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await wn(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function rR(e,t,i){let r=Ve.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Ve.sep}`))return null;let n=r.split(Ve.sep).join("/");try{let a=(0,mu.parseDocument)(Wo(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:gn(a.toJS({mapAsMap:!1}))}catch{return null}}function nR(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function xv(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function vu(e){let t=Ve.join(e.paths.changesDir,e.state.name),i=await Iv(t),r=await _v({changeDir:t,validation:Av(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:m})=>m)}:{},policy:"advisory"});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=Tv({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!r.drift;if(r.contract.schema===hr){let m=await On(e.paths,e.state.name);if(!m){let N=e.state.workspace.target_branch??e.state.workspace.change_branch;if(N){let k=await pu({paths:e.paths,parent:e.state.name,targetBranch:N,contract:r.contract});k&&(m=k,await fu(e.paths,k))}}if(m){let N=yv(m);return e.state.children_contract_hash!==n||r.drift?{...N,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(k=>({...k,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let S=new Map(r.contract.children.map(N=>[N.name,N])),y=r.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:o&&N.depends_on.every(k=>r.contract.children.filter(({name:E})=>E!==N.name).every(({name:E})=>E!==k))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let N of y){if(N.status!=="ready")continue;S.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:y,readyChildren:y.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let s=await eR(e.paths),c=new Set(r.contract.children.map(({name:m})=>m)),l=new Map,u=new Map;for(let m of s){let S=m.parent&&a?`refs/heads/${a}`:"HEAD";for(let y of await iR(m,c)){let N={...y,source:m,committedState:rR(m,y.file,S)};l.set(y.state.name,[...l.get(y.state.name)??[],N])}for(let y of c){let N=await tR(m,y);N&&u.set(y,[...u.get(y)??[],{source:m,state:N}])}}let d=new Map;for(let m of r.contract.children){let S=(l.get(m.name)??[]).find(({source:k,committedState:E})=>k.parent&&E?.name===m.name&&xv(E,a));if(S){d.set(m.name,{kind:"done",phase:S.state.phase,projectRoot:S.source.projectRoot,message:null});continue}let y=l.get(m.name)?.[0];if(y){d.set(m.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${m.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let N=u.get(m.name)??[];N.length>1?d.set(m.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${m.name} has multiple active workspace owners`}):N[0]&&d.set(m.name,nR(N[0].state,N[0].source,a))}let f=new Map(r.contract.children.map(m=>[m.name,m])),p=new Map,v=m=>{let S=p.get(m);if(S)return S;let y=f.get(m),k=y.depends_on.map(v).every(({status:C})=>C==="done"),E=d.get(m),b=E?.kind==="active"&&k?y.depends_on.filter(C=>!(l.get(C)??[]).some(({source:O,committedState:T})=>hu(O.projectRoot,E.projectRoot)&&T?.name===C&&xv(T,a))):[],x,g=E?.message??null;E?.kind==="done"?(x=k?"done":"blocked",k||(g=`Native child ${m} was merged before its dependencies`)):E?.kind==="active"?(x=k&&b.length===0?"active":"blocked",k?b.length>0&&(g=`Native child ${m} does not include merged dependencies: ${b.join(", ")}`):g=`Native child ${m} started before its dependencies merged`):E?.kind==="blocked"?x="blocked":(x=o&&k?"ready":"pending",o||(g="Parent Shape confirmation is required"));let w={name:m,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:x,phase:E?.phase??null,projectRoot:E?.projectRoot??null,message:g};return p.set(m,w),w},h=r.contract.children.map(({name:m})=>v(m));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:h,readyChildren:h.filter(({status:m})=>m==="ready").map(({name:m})=>m),allDone:h.every(({status:m})=>m==="done")}}var JL=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var aR=/\b(Bearer|Basic)\s+[^\s"']+/giu,oR=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,sR=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,cR=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,lR=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,uR=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,dR=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function Fe(e){return e.replace(aR,"$1 [REDACTED]").replace(oR,"[REDACTED PRIVATE KEY]").replace(sR,"$1[REDACTED]@").replace(cR,"[REDACTED TOKEN]").replace(lR,'$1"[REDACTED]"').replace(uR,"$1$2$1$3$4[REDACTED]$4").replace(dR,"$1$2[REDACTED]")}import{promises as gR}from"node:fs";import jv from"node:path";function Uo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ko(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function pt(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function $v(e,t){return e===null?null:pt(e,t)}function Xo(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function wR(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 yR(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Yo(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function gu(e,t){if(e===null)return null;let i=pt(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function wu(e,t){let i=pt(e,t);if(!jv.isAbsolute(i))throw new Error(`${t} must be absolute`);return jv.resolve(i)}function NR(e,t){let i=`Native local checks[${t}]`,r=Uo(e,i);if(Ko(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>pt(l,`${i}.argv[${u}]`,!0)),a=Yo(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=gu(r.startedAt,`${i}.startedAt`),s=gu(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=Xo(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:pt(r.id,`${i}.id`),name:pt(r.name,`${i}.name`),operationId:pt(r.operationId,`${i}.operationId`),status:a,repeatable:yR(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Xo(r.executionCount,`${i}.executionCount`),argv:n,cwd:wu(r.cwd,`${i}.cwd`),exitCode:wR(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:pt(r.log,`${i}.log`)}}function bR(e){let t="Native local execution state",i=Uo(e,t);if(Ko(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==vo)throw new Error(`Native local execution schema must be ${vo}`);let r=Uo(i.workspace,"Native local workspace");Ko(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Uo(i.execution,"Native local execution");Ko(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=gu(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:pt(o.operationId,"Native local execution.operationId"),stage:Yo(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Yo(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:$v(o.executionId,"Native local execution.executionId"),status:Yo(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Xo(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(NR);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:vo,change:pt(i.change,"Native local change"),basedOnStateVersion:Xo(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:wu(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:wu(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:$v(r.branch,"Native local workspace.branch")},execution:n,checks:a}}async function Ov(e){let t;try{t=await gR.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return bR(i)}var CR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xR="comet-state.yaml",PR="state.json",y1=ro("en");function Hv(e,t){if(!CR.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=yu.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}function Dv(e,t){return yu.join(Hv(e,t),xR)}function RR(e,t){return yu.join(Zt(e,t),PR)}async function Nu(e,t){try{let i=await ER.readFile(Dv(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function Lv(e,t){return wn(Dv(e,t))}async function Bv(e){let t=await Lv(e.paths,e.name),i=RR(e.paths,e.name);try{let r=await Ov(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var A1=16*1024;async function Vv(e){let t=await hv(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Vo(t.selection.change),t.selection)}async function Fv(e,t){let i=[],r=U(e,t.name),n=ei(r,Be.stateRef),a;try{a=await dr(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=ei(r,a.trajectoryRef),s=await $m(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await Pi(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=ei(r,a.checkpointRef);try{let u=await jo(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import NA from"path";import{isDeepStrictEqual as Vu}from"util";var mr={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var AR=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function _R(e,t){return e<t?-1:e>t?1:0}function IR(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!AR.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(_R)}function bu(e=[]){return IR(e,"Native repair failed check IDs",mr.maxFailedCheckIds,!0)}function qv(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function TR(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:qv(e.failedAcceptanceIds,t.failedAcceptanceIds)&&qv(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function ku(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(TR(r,a))break;i+=1,r=a}return i}import cg from"node:path";import{createHash as Yv}from"node:crypto";import Mv from"path";var Su="comet.native.implementation-scope.v2",Xv="comet.native.content-snapshot-projection.v1",Dn="comet.native.content-snapshot-projection.v1",Qv="comet.native.implementation-scope.v2",jR="comet.native.unresolved-scope-id.v1",$R="comet.native.scope-detail-overflow.v1",OR="comet.native.snapshot-projection-overflow.v2",Pu=/^[a-f0-9]{64}$/u,_i=1024*1024,HR=128,DR=128;function ve(e,t){return e<t?-1:e>t?1:0}function Eu(e){if(!Pu.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function LR(e,t){return e===t?0:e===null?-1:t===null?1:ve(e,t)}function li(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=Mv.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Mv.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Zv(e,t){return e==="."?e:li(e,t)}function vr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function BR(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:li(e.path,`${t} path`),hash:e.hash,size:vr(e.size,`${t} size`),type:"file"}}function VR(e,t){return{path:Zv(e.path,`${t} path`),size:e.size===null?null:vr(e.size,`${t} size`),type:e.type,reason:e.reason}}function FR(e,t){return ve(e.path,t.path)||ve(e.hash,t.hash)||e.size-t.size}function qR(e,t){return ve(e.path,t.path)||ve(e.reason,t.reason)||ve(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Bn(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
168
|
-
`,"utf8")}function
|
|
169
|
-
${
|
|
170
|
-
`),e.omissionOverflow&&
|
|
171
|
-
`);let i=0;Ru(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){ci(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Fn(o,n.path)&&(a+=1,ci(t,"change-attribution",o));ci(t,"change-end",{attributionCount:a}),a===0&&ci(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&ci(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function ag(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=GR(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let x=new Set(i.externalDrift.paths),g=new Set(o.changePaths),w=i.externalDrift.paths.filter(C=>!g.has(C)||n.some(O=>Fn(O,C)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(x.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=j(Dn,e),c=j(Dn,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[x,g]of[["baseline",e],["current",t]])for(let w of g.omitted){if(l.length>=DR)break;l.push(_t({kind:"snapshot-omission",source:x,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${x} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...zv("baseline",e),...zv("current",t),...o.totalChanges===0&&a===null?[_t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(i.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(g=>x.has(g)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(g=>!x.has(g))}},v=x=>{let g=o.candidates.slice(0,x.detailedChangeCount),w=g.filter(We=>We.attributedTo.length===0&&!u.has(We.path)),C=o.totalChanges-g.length,O=o.totalUnattributed-w.length,T=d-x.detailedOmissionCount,pe=O+T,Q=[...w.map(We=>_t({kind:"unattributed-change",source:"implementation-scope",path:We.path,evidence:{after:We.after,before:We.before,changeKind:We.kind}},`Changed path is not covered by a declared artifact: ${We.path}`)),...l.slice(0,x.detailedOmissionCount),...f,...pe>0?[ng(x.overflowHash,{changes:C,unattributed:O,unresolved:pe})]:[]],G=zR(Q),at=x.includeGitAdvisory?p():void 0;return{schema:Su,contractHash:r,baselineProjectionRef:Eu(s),baselineProjectionHash:s,currentProjectionRef:Eu(c),currentProjectionHash:c,complete:G.length===0,declaredArtifacts:n,changes:g,unattributed:w,unresolvedScopes:G,noCodeReason:a,...at?{gitAdvisory:at}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},h=o.candidates.length,m=l.length,S=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let x=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:y});if(Bn({...x,scopeHash:y})<=_i)break;if(S){S=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let k=o.totalChanges>h||d>m?KR({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):y,E=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:k}),b={...E,scopeHash:j(Qv,E)};if(Bn(b)>_i)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function _u(e){let t=Cu(e.baseline),i=Cu(e.current),r=rg(e);return{authority:r,baseline:t,current:i,scope:ag(t,i,r)}}var YR=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function ht(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mt(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function Ai(e,t){if(typeof e!="string"||!Pu.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Gv(e,t,i){let r=Eu(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function Qo(e,t){let i=ht(e,"Native snapshot projection");if(mt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Xv)throw new Error("Native snapshot projection schema is invalid");let r=xi({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=Cu(r);if(j(Dn,i)!==j(Dn,n))throw new Error("Native snapshot projection is not canonical");let a=j(Dn,n);if(t!==void 0&&Ai(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Iu(e,t){let i=ht(e,`Declared artifact ${t}`);if(mt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:li(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Uv(e,t){if(e===null)return null;let i=ht(e,t);return mt(i,["hash","size"],[],t),{hash:Ai(i.hash,`${t} hash`),size:vr(i.size,`${t} size`)}}function Kv(e,t){let i=ht(e,`Implementation change ${t}`);if(mt(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Iu),n=Vn(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Uv(i.before,`Implementation change ${t} before`),o=Uv(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:li(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function XR(e,t){let i=ht(e,`Unresolved scope ${t}`);mt(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Zv(i.path,`Unresolved scope ${t} path`):li(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Ln(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>li(n,`${t} ${a}`)),r=[...new Set(i)].sort(ve);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function og(e){let t=ht(e,"Native implementation external drift");if(mt(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=Ln(t.paths,"Native external drift paths");return ig({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function Zo(e){let t=ht(e,"Native implementation scope"),i=[...YR].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(mt(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Su)throw new Error("Native implementation scope schema is invalid");let r=Ai(t.contractHash,"Implementation scope contractHash"),n=Ai(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Gv(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Ai(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Gv(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Iu);if(JSON.stringify(c)!==JSON.stringify(Vn(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Kv),u=[...l].sort((w,C)=>ve(w.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(C=>Fn(C,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Kv),p=t.externalDrift===void 0?void 0:og(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(XR),S=m.filter(w=>w.kind==="scope-detail-overflow");if(S.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=S[0]===void 0?null:UR(S[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let N=t.noCodeReason,k=[...h.map(w=>_t({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(y?.changes??0)===0&&N===null?[_t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(xu))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(E)!==JSON.stringify(k.sort(xu))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=ht(t.gitAdvisory,"Implementation scope Git advisory");if(mt(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Ln(w.changedPaths,"Git changed paths"),O=Ln(w.pathsPresentInSnapshotChanges,"Git present paths"),T=Ln(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),pe=[...O,...T].sort(ve);if(JSON.stringify(pe)!==JSON.stringify(C)||T.some(Q=>l.some(G=>G.path===Q)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:T}}let x={schema:Su,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:N,...b?{gitAdvisory:b}:{},...p?{externalDrift:p}:{}},g=Ai(t.scopeHash,"Implementation scope scopeHash");if(j(Qv,x)!==g)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:g}}function QR(e){let t=ht(e,"Native implementation scope authority");if(mt(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Iu);if(JSON.stringify(i)!==JSON.stringify(Vn(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=Ln(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:og(t.externalDrift),a=rg({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function qn(e){let t=ht(e,"Native implementation scope bundle");mt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=QR(t.authority),r=Qo(t.baseline),n=Qo(t.current),a=Zo(t.scope),o=ag(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function sg(e){let t=Zo(e.scope);return qn({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var ug=/^[a-f0-9]{64}$/u;var ZR="comet.native.acceptance-trace.v2",eA="comet.native.partial-allowance.v1",tA="comet.native.verification-evidence.v2";function It(e,t){if(!ug.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function dg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function fg(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Tu(e,t,i=2e3){let r=Fe(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Mn(e,t){let i=cg.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||cg.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function iA(e,t,i){let r=Mn(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ct(r),a=r.toLowerCase(),o=i?Mn(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function ju(e){let t=Mn(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function gr(e,t){return e<t?-1:e>t?1:0}function es(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ts(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function pg(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function lg(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function rA(e){let t=es(e,"Native acceptance trace");if(ts(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!ug.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=Mn(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=es(o,`Native acceptance trace entry ${s}`);if(ts(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>ju(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(gr))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Mn(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Tu(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>gr(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=It(t.traceHash,"Native acceptance trace hash");if(j(ZR,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function hg(e){let t=es(e,"Native partial allowance");if(ts(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(gr))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:fg(t.change),scopeHash:It(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Tu(t.reason,"Partial allowance reason"),confirmedSummary:Tu(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:dg(t.sourceRevision),confirmedAt:pg(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=It(t.allowanceHash,"Native partial allowance hash");if(j(eA,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function $u(e){let t=es(e,"Native verification evidence");if(ts(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=It(t.implementationScopeHash,"Native verification implementation scope hash"),r=rA(t.acceptanceTrace),n=It(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:It(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>ju(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(gr)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(gr);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>ju(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(gr)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:fg(t.change),sourceRevision:dg(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:It(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:lg(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:iA(t.reportRef,"Native verification report ref"),reportHash:It(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:lg(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:pg(t.createdAt,"Native verification timestamp")},d=It(t.envelopeHash,"Native verification envelope hash");if(j(tA,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function Ou(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var mg="repairStagnation",Ie={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},aA=/^[a-f0-9]{64}$/u;var oA=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),sA=["data","runId","sequence","timestamp","type"],vg=["disposition","overrideSummaryHash","signatureHash"],cA=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],gg=12;function Du(e,t){return e<t?-1:e>t?1:0}function wg(e,t,i){let r=Object.keys(e).sort(Du);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function is(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Wn(e,t){if(typeof e!="string"||!aA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function lA(e){if(!Array.isArray(e)||e.length>mr.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Du)}function yg(e){if(typeof e!="string"||e.length===0||e.length>Ie.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Hu(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Ie.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Ie.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Ie.maxTextCharacters&&(!n||e.length>Ie.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Ie.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Ie.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Hu(s,t+1,i,`${r}[${c}]`));return}let a=is(e,r),o=Object.keys(a);if(o.length>Ie.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Ie.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Ie.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Hu(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function uA(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function dA(e,t,i){let r=is(e,`Native repair trajectory event ${t+1}`);if(wg(r,sA,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(uA(r.timestamp),typeof r.type!="string"||!oA.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(yg(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Hu(r.data,0,n,"Native trajectory event data"),is(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Lu(e){let t=is(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Du),r=i.length===vg.length&&i.every((l,u)=>l===vg[u]);r||wg(t,cA,"Native repair trajectory projection");let n=Wn(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Wn(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Wn(t.contractHash,"Native repair trajectory contract hash"),s=lA(t.failedAcceptanceIds),c=bu(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function fA(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function pA(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??gg;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=ku({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<mr.warningAtConsecutiveFailures?"continue":a<mr.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function hA(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??gg;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Ng(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Ie.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=yg(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=dA(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Ie.maxTotalDataNodes||c>Ie.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Wn(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Wn(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,mg)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Lu(f[mg]);if(fA(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(i.length=0,o=0),p!==null&&(n=p),pA(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");hA(v,i,r);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>mr.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function bg(e){return Ng(e).history}function kg(e){let t=Ng(e).latestProjection;return t?{...t}:null}var wr={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:[]},Bu=K("comet-native-runtime:v3:scope-reopen"),mA=[{skillVersion:"3",skillHash:K("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:K("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:K("comet-native-runtime:v1")}];function Sg(e){return e.skillVersion===wr.definition.metadata.version&&e.skillHash===Bu||mA.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function Eg(e){return K(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var Ag=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],bA=new Set(Ag),_g=new Set([...Ag,"minimum_runtime_version","revision"]),kA=new Set([..._g,"operation"]),SA=512*1024,Fu=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),EA=new Set([...Fu,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),qu=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Wu(e,t){return NA.join(U(e,t),"transition.json")}function ns(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function zu(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function rs(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Mu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!EA.has(u)),a=[...Fu].find(u=>!Object.hasOwn(i,u)),o=Fu.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Ou(i.summary,"Native transition journal event summary"),Fe(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Ou(i.noCodeReason,"Native transition journal event no-code reason"),Fe(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Lu(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function CA(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return Mu({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Mu(e,t)}function Ju(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?CA(e.eventData,e.evidenceHash):Mu(e.eventData,e.evidenceHash),n=Kl(e.nextRun),a=e.previousRun===null?null:Kl(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Cg(e,t,i=!1){if(e.skill!==wr.definition.metadata.name||(i?!Sg(e):e.skillVersion!==wr.definition.metadata.version||e.skillHash!==Bu)||e.orchestration!==wr.definition.orchestration.mode||e.pendingRef!==Be.pendingRef||e.trajectoryRef!==Be.trajectoryRef||e.contextRef!==Be.contextRef||e.artifactsRef!==Be.artifactsRef||e.checkpointRef!==Be.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function xg(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Pg(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function Gu(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Cg(o,"next Run",r||a!==null),Pg(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Cg(a,"previous Run",!0),Pg(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!Vu(xg(a),xg(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function xA(e,t,i){return K(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Ig(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Rg(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Uu(e,t,i,r,n=!1){let a=i.eventData,o=Rg(e),s=Rg(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&Vu(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&Vu(e.spec_changes,t.spec_changes),l=Eg({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=xA(e.name,a.summary,t.spec_changes),l=K(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function PA(e,t){let i=ns(e);if(zu(i,kA),i.schema!==tr)throw new Error(`Expected Native transition schema ${tr}`);let r=rs(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${tr} minimum_runtime_version must be ${3}`);let n=rs(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Ju(i,t),o=ni(i.previousState),s=ni(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Uu(o,s,a,i.operation),Gu(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:tr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function RA(e,t){let i=ns(e);if(zu(i,bA),i.schema!==yn)throw new Error(`Expected Native transition schema ${yn}`);let r=Ju(i,t,!0),n=rr(i.previousState),a=rr(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Uu(n,a,r,Ig(n,a,r.eventData),!0),Gu(n,a,r,!0),{schema:yn,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function AA(e,t){let i=ns(e);if(zu(i,_g),i.schema!==ir)throw new Error(`Expected Native transition schema ${ir}`);if(rs(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${ir} minimum_runtime_version must be 2`);let n=rs(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Ju(i,t,!0),o=nr(i.previousState),s=nr(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Uu(o,s,a,Ig(o,s,a.eventData),!0),Gu(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:ir,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function _A(e,t){let i=ns(e);if(i.schema===tr)return{status:"current",journal:PA(i,t)};if(i.schema===yn)return{status:"migration-required",journal:RA(i,t)};if(i.schema===ir)return{status:"migration-required",journal:AA(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function IA(e,t){let i=Wu(e,t),r=le(e,i);await J(r,i);try{let n=await Et({root:r,file:i,maxBytes:SA,label:`Native transition journal ${t}`});return _A(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Tg(e,t){let i=await IA(e,t);if(!i)return null;if(i.status==="migration-required")throw new qu(t);return i.journal}var TA=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function jA(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function $A(e){return e?e.map(jA).join(" "):null}function OA(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function qe(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function HA(e){return e.map(t=>qe(t,[],null))}function DA(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[qe("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(qe("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(qe("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),qe("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(qe("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(qe("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),qe("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function ge(e,t){let i=t.commandArgs===void 0?OA(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?$A(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??HA(t.requiredInputs??[])}}function as(e){let i=(e.findings??[]).filter(d=>!fr(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||TA.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return ge(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[qe("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return ge(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[qe("summary",["--summary"],"<summary>")]});if(n)return ge(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[qe("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),ge(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[qe("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):ge(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return ge(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=DA(e.state);return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import zn from"path";var jg=8,LA={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function BA(e){let t=LA[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:fr(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function VA(e,t,i){if(!i.path)return null;let r;if(zn.isAbsolute(i.path)?r=zn.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=zn.resolve(fe(e,t.name),...i.path.split(/[\\/]/u)):r=zn.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!V(e.projectRoot,r))return null;let n=zn.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function FA(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Ku(e){return e.findings.map(t=>{let i=BA(t.code);return{code:t.code,message:t.message,severity:i.severity,path:VA(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:FA(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Yu(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,jg),truncated:t.length>jg}}import yr from"path";var di={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Nr=/^[a-f0-9]{64}$/u;function os(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ss(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function ui(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function $g(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Xu(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function qA(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||yr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=yr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Og(e,t){return yr.join(U(e,t),"checkpoints","progress.json")}function Jn(e,t){return yr.join(U(e,t),"checkpoint-journal.json")}function Hg(e,t,i){if(!Nr.test(i))throw new Error("Native checkpoint manifest hash is invalid");return yr.join(U(e,t),"checkpoints","manifests",`${i}.json`)}function MA(e){if(!Nr.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Qu(e,t,i){let r=await Et({root:e,file:t,maxBytes:di.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function WA(e,t){let i=os(e,`checkpoint manifest artifact ${t}`);ss(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=qA(ui(i.path,`checkpoint artifact ${t} path`,4096)),n=ct(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!Nr.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:Xu(i.size,`checkpoint artifact ${t} size`)}}function Zu(e,t){let i=os(e,"Native checkpoint manifest");if(ss(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>di.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(WA),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Xu(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>di.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Dg(e){return K(JSON.stringify(Zu(e,e.change)))}function Lg(e,t){let i=os(e,"Native progress checkpoint");if(ss(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=$g(i.previousRevision,"Native checkpoint previousRevision"),a=$g(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ui(i.manifestHash,"Native checkpoint manifestHash",64);if(!Nr.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=MA(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ui(i.inputHash,"Native checkpoint inputHash",64);if(!Nr.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ui(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Xu(i.artifactCount,"Native checkpoint artifactCount");if(u>di.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ui(i.summary,"Native checkpoint summary"),f=ui(i.nextAction,"Native checkpoint nextAction");if(Fe(d)!==d||Fe(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ui(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function zA(e,t){let i=os(e,"Native checkpoint journal");if(ss(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=ni(i.previousState),n=ni(i.nextState),a=Lg(i.checkpoint,t),o=Zu(i.manifest,t),s=ui(i.inputHash,"Native checkpoint journal inputHash",64),c=K(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Nr.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Dg(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function JA(e,t,i){let r=yr.resolve(e.projectRoot,...t.split("/"));if(!V(e.projectRoot,r)||V(e.nativeRoot,r)||V(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=rl(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await Et({root:e.projectRoot,file:r,maxBytes:di.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function GA(e,t){let i=Og(e,t),r=le(e,i);await J(r,i);try{return Lg(await Qu(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function UA(e,t,i){let r=Hg(e,t,i),n=le(e,r);await J(n,r);let a=await Qu(n,r,"Native checkpoint manifest"),o=Zu(a,t);if(Bg(e,o),Dg(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function ed(e,t){let i=Jn(e,t),r=le(e,i);await J(r,i);try{let n=zA(await Qu(r,i,"Native checkpoint journal"),t);return Bg(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Bg(e,t){for(let i of t.artifacts){let r=rl(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Vg(e){let t;try{t=await GA(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Og(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await UA(e.paths,e.name,t.manifestHash);let a=K(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await JA(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Hg(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}var Fg=240,qg=8,cs=50;function Mg(e){let t=Array.from(e);return t.length<=Fg?e:`${t.slice(0,Fg-1).join("")}…`}function KA(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function YA(e){let t=[...new Set(e.map(KA))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,qg),reasonCount:e.length,codesTruncated:t.length>qg};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,cs),reasonsTruncated:e.length>cs}}}async function Wg(e){let t=null;try{let s=await ed(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Jn(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Jn(e.paths,e.state.name)}}let i=await Vg({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=YA(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:di.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Mg(i.checkpoint.summary),nextAction:Mg(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:di.maxArtifacts}}import{promises as DI}from"node:fs";import Ew from"node:path";import zg from"node:path";var XA="comet.native.archive-preflight.v1",QA="comet.native.archive-preflight.v1",ZA="comet.native.archive-operation.v1",e_=/^[a-f0-9]{64}$/u,Jg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,t_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function ls(e,t){return e<t?-1:e>t?1:0}function i_(e,t){if(typeof e!="string"||!e_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Tt(e,t){return e===null?null:i_(e,t)}function r_(e,t){let i=zg.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||zg.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function n_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function a_(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function o_(e,t){if(!Jg.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Tt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Tt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Tt(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function s_(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Tt(e.contractHash,"Native archive contract hash"),acceptanceHash:Tt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Tt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Tt(e.reportHash,"Native archive report hash"),envelopeHash:Tt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Tt(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function c_(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!t_.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(ls);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function l_(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(ls)}function Gg(e){if(!Jg.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(o_).sort((l,u)=>ls(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:j(ZA,l)})),r=s_(e.evidence),n=a_(e.workspace),a=[...new Set([...c_(e.findingCodes??[]),...l_({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(ls),o=n_(e.revision),s=r_(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:XA,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:j(QA,c)}}import{createHash as u_}from"node:crypto";import Ug from"node:path";var d_="comet.native.conflict-radar.v1",Ce=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}),f_="comet.native.conflict-radar.v1",p_="comet.native.conflict-radar-signals.v1",h_=/^[a-f0-9]{64}$/u,Xg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,m_=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),v_=new Set(["capability","operation","baseHash"]),g_=new Set(["path","kind"]);function br(e,t){return e<t?-1:e>t?1:0}function td(e){return Buffer.byteLength(e,"utf8")}function id(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function rd(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(td(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function w_(e,t){let i=rd(e,t,Ce.maxArtifactPathBytes),r=Ug.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||Ug.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Qg(e,t){if(typeof e!="string"||!h_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function y_(e,t){let i=id(e,v_,t),r=rd(i.capability,`${t} capability`,Ce.maxCapabilityBytes);if(!Xg.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:Qg(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function N_(e,t){let i=id(e,g_,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:w_(i.path,`${t} path`),kind:i.kind}}function b_(e,t){let i=id(e,m_,`Conflict radar change ${t}`),r=rd(i.name,`Conflict radar change ${t} name`,Ce.maxNameBytes);if(!Xg.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>Ce.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>Ce.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>y_(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>br(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>N_(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>br(c.path,l.path)||br(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:Qg(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function k_(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Ce.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(b_).sort((n,a)=>br(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>Ce.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Ce.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function S_(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function E_(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function C_(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function x_(e,t){let i=[],r=u_("sha256").update(`${p_}
|
|
172
|
-
[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(_r(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Ce.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(S_(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=E_(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:C_(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function Kg(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function P_(e,t){return Kg(e.classification)-Kg(t.classification)||br(e.left,t.left)||br(e.right,t.right)}function Yg(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:d_,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function Zg(e){let t=k_(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(x_(t[s],t[c]));i.sort(P_);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(f_,{changes:t,relationships:r}),a=i.slice(0,Ce.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Yg(t,i,a,n);for(;a.length>0&&td(JSON.stringify(o))>Ce.maxSerializedBytes;)a=a.slice(0,-1),o=Yg(t,i,a,n);if(td(JSON.stringify(o))>Ce.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as oI}from"node:crypto";import{promises as nt}from"node:fs";import vt from"node:path";import ew from"node:path";var tw="comet.native.check-receipt.v1",R_="comet.native.check-receipt.v1",kr="scoped-text-safety",nd=1,xe=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),A_=/^[a-f0-9]{64}$/u,__=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,I_="comet.native.checker-policy.v1",T_="comet.native.check-input.v1",j_=2048,iw=j(I_,{policy:kr,version:nd,limits:xe,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),$_=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),rw=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],aw=["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"],O_=new Set(aw);function fi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pi(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function jt(e,t){if(typeof e!="string"||!A_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Te(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function ow(e,t){let i=Te(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function nw(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function H_(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>j_||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=ew.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||ew.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function D_(e){let t=fi(e,"Native check receipt checker");pi(t,["policy","version","hash","limits"],"Native check receipt checker");let i=fi(t.limits,"Native check receipt limits");if(pi(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==kr||t.version!==nd||t.hash!==iw||i.maxFiles!==xe.maxFiles||i.maxFileBytes!==xe.maxFileBytes||i.maxTotalBytes!==xe.maxTotalBytes||i.maxIssues!==xe.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:kr,version:nd,hash:iw,limits:{...xe}}}function L_(e){let t=fi(e,"Native check receipt contract");return pi(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:jt(t.expectedHash,"Native check expected contract hash"),beforeHash:jt(t.beforeHash,"Native check before contract hash"),afterHash:jt(t.afterHash,"Native check after contract hash")}}function B_(e){let t=fi(e,"Native check receipt implementation");return pi(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:jt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:jt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:jt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:jt(t.afterSnapshotHash,"Native check after snapshot hash")}}function V_(e,t){let i=fi(e,`Native check batch ${t}`);pi(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Te(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Te(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Te(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Te(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Te(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Te(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>xe.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>xe.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function F_(e){let t=fi(e,"Native check receipt counts");pi(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Te(t.filesSelected,"Native check filesSelected"),filesScanned:Te(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Te(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Te(t.bytesScanned,"Native check bytesScanned"),issueCount:Te(t.issueCount,"Native check issueCount"),recordedIssueCount:Te(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(V_):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>xe.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>xe.maxFiles||i.bytesScanned>xe.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function q_(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||rw.indexOf(e.kind)-rw.indexOf(t.kind)}function M_(e){if(!Array.isArray(e)||e.length>xe.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=fi(r,`Native check issue ${n}`);if(pi(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!$_.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:H_(a.path,`Native check issue ${n} path`),line:ow(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(q_);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function W_(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!O_.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=aw.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function z_(e){return j(T_,e)}function sw(e){let t=fi(e,"Native check receipt");if(pi(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==tw)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!__.test(t.change))throw new Error("Native check receipt change name is invalid");let i=ow(t.sourceRevision,"Native check source revision"),r=D_(t.checker),n=L_(t.contract),a=B_(t.implementation),o=z_({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(jt(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=nw(t.startedAt,"Native check receipt startedAt"),c=nw(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=F_(t.counts),u=M_(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=W_(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>xe.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>xe.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:tw,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=jt(t.receiptHash,"Native check receipt content hash");if(j(R_,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var od="comet.native.verification-receipt.v3",J_=od,G_="comet.native.declared-artifacts.v1",U_=/^[a-f0-9]{64}$/u,K_=/^acceptance-[a-f0-9]{64}$/u,Y_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,X_=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Q_=4096,Z_=256,eI=1024;function Sr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function hi(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function $t(e,t){if(typeof e!="string"||!U_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function rt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=Fe(e).trim();if(!i||i.length>Q_||i!==e.trim())throw new Error(`${t} is invalid`);return i}function ad(e,t){let i=rt(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function Gn(e,t,i=rt,r=!1,n=Z_){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function tI(e,t){if(typeof e!="string"||!K_.test(e))throw new Error(`${t} is invalid`);return e}function iI(e){let t=Sr(e,"Native verification receipt bindings");if(hi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!Y_.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:$t(t.contractHash,"Native verification receipt contract hash"),scopeHash:$t(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:$t(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:$t(t.artifactHash,"Native verification receipt artifact hash")}}function rI(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=X_.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function nI(e,t,i,r){let n=Sr(t,`Native ${e} evidence`);if(e==="automated-check"){if(hi(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=ad(n.startedAt,"Native automated-check start time"),o=ad(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Sr(n.worktree,"Native automated-check worktree");if(hi(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=Sr(n.afterFence,"Native automated-check after fence");if(hi(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:rt(n.executable,"Native automated-check executable"),args:Gn(n.args,"Native automated-check arguments",rt,!0),cwd:rt(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:rt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:$t(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:$t(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:$t(n.outputHash,"Native automated-check output hash"),outputSummary:rt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){hi(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=rI(n.checkReceiptRef);if($t(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Gn(n.subjects,"Native static inspection subjects",rt,r==="required-check"),rule:rt(n.rule,"Native static inspection rule"),resultSummary:rt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return hi(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Gn(n.steps,"Native manual evidence steps"),observations:Gn(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function aI(e){let t=Sr(e,"Native verification receipt");if(hi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=rt(t.actor,"Native verification receipt actor"),o=Gn(t.acceptanceIds,"Native receipt acceptance IDs",tI,r==="required-check",eI).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:od,kind:i,role:r,status:n,bindings:iI(t.bindings),acceptanceIds:o,actor:a,issuedAt:ad(t.issuedAt,"Native verification receipt issue time"),evidence:nI(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==kr||s.actor!==`native-runtime:${kr}`))throw new Error("Native required check policy identity is invalid");return s}function cw(e){let t=Sr(e,"Native verification receipt");if(hi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==od)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=aI(r),a=$t(t.receiptHash,"Native verification receipt hash");if(j(J_,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function sd(e){return j(G_,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var fw=/^[a-f0-9]{64}$/u,Er=_i,kF=3*Er;function cd(e,t){let i=vt.relative(e,t);return i===""||!vt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${vt.sep}`)}function sI(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function us(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function lw(e){let t=await nt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await nt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function cI(e,t){let i=vt.resolve(e),r=vt.resolve(t);if(!cd(i,r))throw new Error("Native evidence path is outside its change");let n=[await lw(i)],a=i;for(let o of vt.relative(i,r).split(vt.sep).filter(Boolean)){a=vt.join(a,o);let s=await lw(a);if(!cd(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function uw(e){for(let t of e){let i=await nt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!sI(t,i)||await nt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function lI(e,t,i={}){let r=await cI(t,vt.dirname(e));await i.afterParentChainCaptured?.();let n=await nt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await nt.realpath(e);if(!cd(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await nt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),nt.lstat(e),nt.realpath(e)]);if(await uw(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!us(s,n)||!us(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Er)throw new Error(`Native evidence document exceeds ${Er} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=Er+1-d,S=await o.read(f,0,Math.min(f.length,m),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>Er)throw new Error(`Native evidence document exceeds ${Er} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),nt.lstat(e),nt.realpath(e)]);if(await uw(r),!v.isFile()||v.isSymbolicLink()||h!==a||!us(s,p)||!us(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function pw(e,t){if(!fw.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function uI(e,t,i,r,n){if(!fw.test(i))throw new Error("Native report evidence hash is invalid");let a=await Ii({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||oI("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function Cr(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function dI(e,t,i,r,n){let a=pw(i,r);return n?vt.join(n,...a.split("/")):ei(U(e,t),a)}async function Ii(e){let t=dI(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??le(e.paths,t);return await J(i,t),lI(t,i,e.hooks)}function dw(e,t){return Qo(e,t)}function fI(e,t){let i=Zo(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function pI(e,t,i){let r=hg(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function hI(e,t,i){let r=$u(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function mI(e,t,i,r=!1,n){let a=await ds(e,t,i.implementationScopeRef,void 0,n);if(r&&await uI(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await hw(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Un(e,t,i,r,n){let a=Cr(i,"scopes"),o=fI(await Ii({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Cr(o.baselineProjectionRef,"snapshots"),c=Cr(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Ii({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>dw(d,s)),Ii({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>dw(d,c))]);return sg({baseline:l,current:u,scope:o})}async function ds(e,t,i,r,n){return(await Un(e,t,i,r,n)).scope}async function hw(e,t,i,r,n){let a=Cr(i,"allowances");return pI(await Ii({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function Kn(e,t,i,r,n){let a=Cr(i,"receipts"),o=cw(await Ii({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function xr(e,t,i,r,n){let a=Cr(i,"verifications"),o=hI(await Ii({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await mI(e,t,o,!1,n),o}var vI=4096;async function gI(e,t=Ce.maxChanges){try{let i=await Nn({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function mw(e,t){let i=await At(e,t),[r,n]=await Promise.all([i.implementation_scope?ds(e,t,i.implementation_scope):null,Pt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function fs(e,t,i={}){let n=(await gI(e,vI)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await mw(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await mw(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Zg([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{execFile as RI}from"node:child_process";import{promisify as AI}from"node:util";import{constants as ld,promises as Me}from"node:fs";import Pr from"node:path";var yI=/^[a-f0-9]{64}$/u,NI=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Yn=512*1024;function bI(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ps(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kI(e,t){let i=Pr.resolve(e),r=Pr.resolve(t);if(!V(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...Pr.relative(i,r).split(Pr.sep).filter(Boolean)]){o&&(a=Pr.join(a,o));let s=await Me.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Me.realpath(a);if(n.length>0&&!V(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function gw(e){for(let t of e){let i=await Me.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!bI(t,i)||await Me.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function SI(e){if(!yI.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function EI(e){let t=NI.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function CI(e,t,i){return ei(U(e,t),SI(i))}async function xI(e,t,i){let r=await kI(i,Pr.dirname(e)),n=await Me.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Yn)throw new Error(`Native check receipt exceeds ${Yn} bytes`);let[a,o]=await Promise.all([Me.realpath(t),Me.realpath(e)]);if(!V(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":ld.O_RDONLY|ld.O_NOFOLLOW|ld.O_NONBLOCK,c=await Me.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Me.lstat(e),Me.realpath(e)]);if(await gw(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ps(n,l)||!ps(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=Yn+1-p,N=await c.read(v,0,Math.min(v.length,y),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,p>Yn)throw new Error(`Native check receipt exceeds ${Yn} bytes`);f.push(Buffer.from(v.subarray(0,N.bytesRead)))}let[h,m,S]=await Promise.all([c.stat(),Me.lstat(e),Me.realpath(e)]);if(await gw(r),!m.isFile()||m.isSymbolicLink()||S!==o||!V(a,S)||!ps(l,h)||!ps(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function ww(e,t,i){let r=EI(i),n=U(e,t),a=CI(e,t,r),o=le(e,a);await J(o,a);let s=sw(await xI(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var Xn=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var mq=64*1024;var vq=3600*1e3;var gq=AI(RI);var _I=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function yw(e,t){let i=[];for(let r of _I){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function Nw(e){if(e.receipt.kind!=="static-inspection")return null;let t=await ww(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var mi=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function II(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function TI(e){let t=II(e.bundle.baseline),i=await Gl(e.paths,t,{origin:"explicit",now:e.now});return _u({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function kw(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Un(e.paths,e.state.name,e.state.implementation_scope),i=await pr({changeDir:fe(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await TI({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function Sw(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await kw(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function jI(e){let t=await ne({root:fe(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Gh(t.text)}}function $I(e){let{receipt:t,implementationScope:i}=e,r=[],n=Au({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function OI(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:sd(e.implementationScope.scope.declaredArtifacts)}}async function bw(e){let t=await Kn(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=yw(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new mi([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await Nw({paths:e.paths,state:e.state,receipt:t});if(n){let a=$I({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function HI(e){let t=OI({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await bw({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof mi)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await bw({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof mi)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new mi(i)}function ud(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function dd(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:ud(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([kw(e),xr(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:ud(e.state.verification_result,"stale"),envelope:null};let r=await jI({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await HI({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:ud(e.state.verification_result,"invalid"),envelope:null}}}function LI(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function Cw(e){try{return await DI.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function BI(e,t){try{return(await ne({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function VI(e,t,i){let r=qo(e,i.capability);if(!V(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=Ew.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await BI(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ne({root:fe(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function FI(e,t){return Cw(Wu(e,t))}async function fd(e){let t=e.now??new Date,i=await At(e.paths,e.name),r=await Pt(e.paths,e.name),n=await Ee(e.paths.projectRoot),a=LI(i.name,t),o=Ew.resolve(e.paths.nativeRoot,...a.split("/"));if(!V(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(v=>VI(e.paths,i.name,v))),dd({paths:e.paths,state:i,now:t}),fs(e.paths,i.name),Fo(e.paths,i.name),Qm(e.paths,i.name),FI(e.paths,i.name),Cw(o)]);return Gg({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}async function qI(e,t){let i=U(e,t.name),r=await dr(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await jo(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Pi(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function MI(e,t){let i=await qI(e,t);return{committed:i,latest:kg(i),history:bg(i)}}async function xw(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await MI(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var Ot=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function zI(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function JI(e){return(await Vv(e))?.change??null}function GI(e,t,i=!1,r){return as({state:e,archiveReady:t,evidenceRetreat:i}).command}async function UI(e,t){let i=fe(e,t.name),r=[...(await ou(i,t.brief)).findings,...(await av(e,t)).findings,...await Fv(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Po(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Cm(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await pr({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Tg(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await su(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function pd(e,t,i){let r=await JI(e)===t,n=await Sl(e,t),a=await Pn(e,t),o;try{let w=await nu(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=Ku({paths:e,state:o,findings:[w]}),O=as({state:o,findings:C});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:Yu(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...i?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await Wg({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await xw(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await pr({changeDir:fe(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let pe=await xr(e,o.name,o.verification_evidence);for(let Q of pe.acceptanceTrace.entries)C.set(Q.acceptanceId,Q.status==="failed"?"failed":Q.status==="missing"?"missing":"satisfied")}let O=Wh({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),T=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...T?{nextPageCommand:zI(T),nextPageArgs:T}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await fs(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await Pt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let C=await Rn({paths:e,identity:w});C.state==="drifted"&&C.code&&f.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await Ho({paths:e,identity:w});f.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let w=await Sw({paths:e,state:o});v=w.freshness!=="fresh",p.push(...w.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await fd({paths:e,name:o.name}),m.push(...h.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let S=[...await UI(e,o),...s.findings,...d,...f,...p,...l,...m].filter((w,C,O)=>O.findIndex(T=>T.code===w.code&&T.path===w.path)===C),y=Ku({paths:e,state:o,findings:S}),N=y.filter(w=>!fr(w.code)),k=o.phase==="archive"&&h?.ready===!0&&N.length===0,E=v||o.phase==="archive"&&(h?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=y.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),x=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",g=y.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:b||x?null:GI(o,k,E,i?.clarificationMode),archiveReady:k,inspection:s.inspection,findingSummary:Yu(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:as({state:o,findings:y,archiveReady:k,evidenceRetreat:E,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:cs,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...g?{error:g.message}:{}}}async function Pw(e){let t;try{t=await Hl({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await WI.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Ot.maxChanges))throw new Error(`Native status exceeds ${Ot.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}import eT from"node:path";function Ti(e,t,i){return e.language==="zh-CN"?i:t}function KI(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:Ti(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:Ti(e,"Reply A or B","回复 A 或 B"),agentInstruction:Ti(e,"Relay the two coordination choices and wait for the user decision. Do not treat a generic confirmation as a mode selection or run --confirmed without --coordination-mode.","转述这两个推进方式并等待用户选择。不要把普通“确认”视为已选择推进方式,也不要在没有 --coordination-mode 时运行 --confirmed。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready")return i(Ti(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(Ti(e,"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(e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"由于独立验收服务暂时不可用,目前只能完成自动检查。你可以选择接受当前检查结果,或者等验收服务恢复后再重试。",suggestedReply: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(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return i(Ti(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 md(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function hs(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Rw(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function YI(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function XI(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function QI(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--confirmed","--expected-state-version",String(e.stateVersion),"--expected-action","confirm-shape"]}function Qn(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:md({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[hs("summary","--summary"),Rw(e.name,e.flag)]}}function hd(e){return[Qn({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Qn({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Aw(e,t){let i=XI(t)&&e.coordination_mode===void 0,r={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:KI(e,i)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...r,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...r,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[hs("summary","--summary")],commandAlternatives:[Qn({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...hd({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...r,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:md({change:e.name,stateVersion:e.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")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...r,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[hs("summary","--summary")],commandAlternatives:[Qn({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...hd({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...r,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[hs("summary","--summary")],commandAlternatives:hd({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...r,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:n("none")};if(e.status==="blocked"){let a=e.blockers.some(({resolution_action:o})=>o==="retry-verifier");return{...r,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?md({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:a?["summary"]:["repair-runtime"],inputOptions:a?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:n(a?"retry-verifier":"none")}}if(e.phase==="shape")return{...r,disposition:i?"await-user":"continue",action:"confirm-shape",commandArgs:QI({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[YI("coordination-mode","--coordination-mode",Uh)]:[],Rw("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...r,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:n("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...r,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...r,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")};let a=t.children.some(({status:s})=>s==="blocked"||s==="needs-reverify"),o=t.children.some(({status:s})=>s==="ready"||s==="active");return{...r,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...r,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")}}if(e.phase==="verify"){let a=e.loop.next_action==="await-verifier-result",o=!!e.children_contract_hash,s={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...r,userCommunication:!a&&o?{...r.userCommunication,agentInstruction:`${r.userCommunication.agentInstruction} ${Ti(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:r.userCommunication,disposition:"continue",action:a?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[a?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:a?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[s]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:o?[s]:[]}}],runnerAction:n(a?"await-verifier":"dispatch-verifier")}}return e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived?{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[Qn({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}function ZI(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function _w(e){let t=e.acceptance.reduce((i,r)=>({...i,[r.result]:i[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:ZI(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}function tT(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function iT(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function rT(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:oT(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:sT(r,i)}))]:[]]}function nT(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function Iw(e,t){let i=be(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:eT.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}function aT(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function ms(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function oT(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:ms(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function sT(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:ms(e.summary,t)??""}}async function vd(e){let t=await Bv(e),i=_w(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await vu({paths:e.paths,state:t.state}),a=await On(e.paths,e.name),o=a?{...Iw(e.paths,t.state),projectRoot:"."}:Iw(e.paths,t.state),s=Aw(t.state,n),c=o.bindingState==="mismatch"?{...s,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...s.runnerAction,kind:"none"}}:s,l=a?aT(e.paths,a):[],u=a?(()=>{let p=a.children.filter(({status:N})=>N==="pending"||N==="ready").length,v=a.children.filter(({status:N})=>N==="active"||N==="verified").length,h=a.children.filter(({status:N})=>N==="integrated"||N==="archived").length,m=a.children.filter(({status:N})=>N==="blocked"||N==="needs-reverify").length,S=a.children.filter(({status:N})=>N==="active"||N==="blocked"||N==="needs-reverify").slice(0,16).map(N=>({name:N.name,summary:N.summary,projectRoot:N.task?.projectRoot??N.projectRoot?"<worktree>":null,reason:ms(N.blocker,l)})),y=a.children.flatMap(({blocker:N})=>{let k=ms(N,l);return k?[k]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:a.children.length,waiting:p,working:v,integrated:h,blocked:m,active:S,agents:{working:a.children.filter(({task:N})=>N!==null).length,completed:h},risks:y,nextAction:a.finalVerification.status==="passed"?"final-delivery":a.finalVerification.status==="pending"&&h===a.children.length?"parent-verification":p>0?"dispatch-ready-child":m>0?"resolve-blocker":"continue-supervisor"}})():null,d=e.details?(()=>{let p=a?.stateVersion??0,v=rT(t.state,a,l),h=iT(e.cursor,t.state.state_version,p),m=v.slice(h,h+32),S=h+m.length<v.length?tT(t.state.state_version,p,h+m.length):null;return{items:m,nextCursor:S,supervisorStateVersion:p}})():null,f=a?{schema:a.schema,parent:a.parent,integration:{branch:a.integration.branch,targetBranch:a.integration.targetBranch},finalVerification:{status:a.finalVerification.status,summary:a.finalVerification.summary},summary:u}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:nT(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:a?[]:i.blockers,workspace:o,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((p,v)=>({...p,[v.status]:(p[v.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},continuation:c,...e.details?{details:{stateVersion:t.state.state_version,...a?{supervisorStateVersion:d.supervisorStateVersion}:{},items:d.items,nextCursor:d.nextCursor,nextPageArgs:d.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",d.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}var lT=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function vs(e,t){let i=vi.normalize(gd(e)),r=vi.normalize(gd(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function gd(e){let t=vi.resolve(e);try{return cT.native(t)}catch{return t}}function uT(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function Tw(e){let t=[];for(let i of await Pw(e))t.push({name:i,kind:await Nu(e,i)?"portable":"legacy"});return t}async function Hw(e){let t=vi.resolve(e),i=Dt(e),r=i.length>0?i:[t];r.some(o=>vs(o,t))||r.push(t);let n=[],a=new Set;for(let o of r.map(s=>vi.resolve(s)).sort()){let s=vs(o,t)?t:o,c=gd(s),l=process.platform==="win32"?c.toLowerCase():c;if(a.has(l))continue;a.add(l);let u=await Ee(s);if(!u)continue;let d=await kt(s,u.native.artifact_root);n.push({projectRoot:s,config:u,paths:d,changes:await Tw(d)})}if(n.length===0){let o=await Ee(e);if(!o)throw new Error(".comet/config.yaml was not found in any registered worktree");let s=await kt(e,o.native.artifact_root);n.push({projectRoot:vi.resolve(e),config:o,paths:s,changes:await Tw(s)})}return n}function jw(e,t){return e.workspace.bindingState==="aligned"?0:vs(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function Dw(e,t){let i=new Map;for(let n of t)for(let a of n.changes)i.set(a.name,[...i.get(a.name)??[],{source:n,kind:a.kind}]);let r=[];for(let[n,a]of[...i.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:c,kind:l})=>{if(l==="portable")try{let u=await vd({paths:c.paths,name:n});return{source:c,name:n,kind:l,workspace:u.workspace,portableStatus:u,inspectionError:null}}catch(u){return{source:c,name:n,kind:l,workspace:await Pn(c.paths,n),portableStatus:null,inspectionError:u instanceof Error?u.message:String(u)}}return{source:c,name:n,kind:l,workspace:await Pn(c.paths,n),portableStatus:null,inspectionError:null}}));o.sort((c,l)=>jw(c,e)-jw(l,e)||c.source.projectRoot.localeCompare(l.source.projectRoot));let s=o.filter(c=>c.workspace.bindingState==="aligned");s.length>1?r.push(...s):r.push(s[0]??o[0])}if(r.length>Ot.maxChanges)throw new Error(`Native status discovery exceeds ${Ot.maxChanges} visible changes`);return r.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function $w(e,t){let i=t.toString(36),r=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${i}.${r}`}function dT(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=lT.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let r=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:i});if(t[3]!==r)throw new Error("Native workspace status cursor integrity failed");return i}function Ow(e,t){let i=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:i?uT(i):null,nextPageArgs:i}}async function fT(e,t,i){let r=null;try{r=await ev(e.source.paths,e.name)}catch{}return r?.state?{schema:"comet.native.status.v2",name:e.name,phase:r.state.phase,status:"blocked",migrationRequired:!0,legacySchema:r.schema,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:r.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:pd(e.source.paths,e.name,{details:t,...i?{acceptanceCursor:i}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function Lw(e,t,i,r){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(i)throw new Error("Portable Native status includes the complete acceptance list");return!t&&e.portableStatus?e.portableStatus:vd({paths:e.source.paths,name:e.name,details:t,...r?{cursor:r}:{}})}return fT(e,t,i)}async function Bw(e){let t=await Hw(e.projectRoot),i=(await Dw(e.projectRoot,t)).filter(r=>r.name===e.name);if(i.length===0){let r=t.find(n=>vs(n.projectRoot,e.projectRoot))??t[0];return pd(r.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:r.config.native.clarification_mode,maxVerifyFailures:r.config.native.max_verify_failures})}if(i.length>1)throw new Error(`Native change ${e.name} has multiple aligned workspace bindings: ${i.map(r=>r.source.projectRoot).join(", ")}`);return Lw(i[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function Vw(e){let t=await Hw(e.projectRoot),i=await Dw(e.projectRoot,t),r=j("comet.native.workspace-status-candidates.v1",i.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=dT({candidatesHash:r,total:i.length,cursor:e.cursor}),a=await Promise.all(i.slice(n,n+Ot.maxItems).map(u=>Lw(u,!1))),o=[],s=i.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],f=n+d.length,p=f<i.length?$w(r,f):null,v={schema:s,total:i.length,offset:n,items:d,nextCursor:p,...Ow(vi.resolve(e.projectRoot),p),limits:{...Ot}};if(Buffer.byteLength(JSON.stringify(v),"utf8")>Ot.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<i.length?$w(r,c):null;return{schema:s,total:i.length,offset:n,items:o,nextCursor:l,...Ow(vi.resolve(e.projectRoot),l),limits:{...Ot}}}import Zn from"path";import{realpathSync as _T}from"fs";var Ht={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Fw(e){return e?e.command?`${Ht.next} ${e.command}`:e.ask_user?`${Ht.next} ${e.ask_user}`:null:null}function qw(e,t){let i=[e.summary],r=Fw(e.next);return r&&i.push(r),e.user_message&&i.push("",Ht.relay,e.user_message),t!==void 0&&i.push("",Ht.details,JSON.stringify(t,null,2)),`${i.join(`
|
|
165
|
+
${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Bo(p),p}async function Pt(e,t){let i=await pP(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Bo(i),i)}async function Vo(e){Bo(e.identity);let t=await hP({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),ru==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function Tn(e){if(Bo(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 Vo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=be(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function Um(e,t){let i=await Pt(e,t);if(i===null)return null;let r=await Tn({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var Xm=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],vP=new Set(Xm),Qm=new Set([...Xm,"minimum_runtime_version","revision"]),gP=new Set([...Qm,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),wP=new Set(["capability","operation","source","base_hash"]),yP=new Set(["shape","build","verify","archive"]),NP=new Set(["implicit","confirmed"]),bP=new Set(["pending","pass","fail"]),ci="comet-state.yaml",ou=/^[a-f0-9]{64}$/u,Zm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kP=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Fo=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},_i=class extends Error{constructor(i,r){super(i!==ii||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},qo=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},jn=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Mo=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},uL=so("en");function On(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ev(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Wo(e){if(!Zm.test(e))throw new Error(`Invalid Native change name: ${e}`)}function SP(e){if(!Zm.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function tv(e,t){if(e.length===0||Rt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function EP(e,t){let i=On(e,`spec_changes[${t}]`);if(ev(i,wP,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(SP(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&tv(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!ou.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!ou.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function CP(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 cu(e,t){if(ev(e,t,ci),typeof e.name!="string")throw new Error("Native change name is required");if(Wo(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"||!yP.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&&!NP.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(EP),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!bP.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"&&tv(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!CP(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function sr(e){let t=On(e,ci);if(t.schema!==ni)throw new Error(`Expected ${ni}`);return{schema:ni,...cu(t,vP)}}function $n(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function au(e,t,i){if(e===null)return null;let r=typeof e=="string"?kP.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function xP(e){if(e==null)return null;if(typeof e!="string"||!ou.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function PP(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 cr(e){let t=On(e,ci);if(t.schema!==ri)throw new Error(`Expected ${ri}`);if($n(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ri} minimum_runtime_version must be 2`);return{schema:ri,minimum_runtime_version:2,revision:$n(t.revision,"Native v2 revision"),...cu(t,Qm)}}function ai(e){let t=On(e,ci);if(t.schema!==ii){if(t.schema===ni||t.schema===ri){let o=t.schema===ni?sr(t):cr(t);throw new Fo(o.name,o.schema)}throw new _i(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=$n(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new _i(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=$n(t.revision,"Native revision"),n=cu(t,gP),a=xP(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ii,minimum_runtime_version:3,revision:r,verification_protocol:PP(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:au(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:au(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:au(t.partial_allowance,"Native partial_allowance","allowances")}}function iv(e){let t=On(e,ci);if(t.schema===ni){let n=sr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ii}`}}if(t.schema===ri){let n=cr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ii}`}}if(t.schema!==ii){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 _i(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=$n(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new _i(t.schema,i).message};let r=ai(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function pe(e,t){Wo(t);let i=Rt.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}async function zo(e,t){let i=U(e,t),r=Rt.join(i,"schema-migration.json");await J(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Ym.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function rv(e,t){let i=U(e,t),r=Rt.join(i,"checkpoint-journal.json");await J(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Ym.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function nv(e,t=Rt.dirname(e)){let i=Rt.relative(t,e).split(Rt.sep).join("/"),r=await ne({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,su.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function lu(e,t){let i=Rt.join(pe(e,t),ci);await J(e.nativeRoot,i);let r=iv(await nv(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await zo(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await RP(e,r.state),r)}async function av(e,t){let i=Rt.join(pe(e,t),ci);await J(e.nativeRoot,i);let r=iv(await nv(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function RP(e,t){if(await Io(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function At(e,t){let i=await lu(e,t);if(i.status==="migration-required")throw new Fo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new _i(i.schema,i.minimumRuntimeVersion);return await Um(e,t),i.state}import{promises as XI}from"fs";import{promises as uu}from"fs";import ov from"path";var sv=["outcome","scope","nonGoals","acceptanceExamples"],AP=[...sv,"constraints","decisions","openQuestions","verificationExpectations"],_P=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],cv={maxFileBytes:pn};function lv(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
|
|
166
|
+
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function IP(e,t){let i=ov.resolve(e,...t.split(/[\\/]/u));if(!V(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await uu.realpath(e),n=await uu.realpath(i);if(!V(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await uu.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function Hn(e){return{valid:e.length===0,findings:e}}function uv(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),i=null;for(let r of e.split(/\r?\n/u)){let n=r.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];i===null?i=s:i===s&&(i=null);continue}if(i!==null)continue;let a=r.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function du(e,t){let i=[],r;try{r=(await ne({root:e,ref:t,maxBytes:cv.maxFileBytes})).text}catch(a){return Hn([{code:"brief-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of lv(r))n.set(oo(a)??a,o);for(let a of AP)n.has(a)||i.push({code:"brief-section-missing",message:`Missing brief section: ${a}`,path:t});for(let a of sv)(n.get(a)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${a}`,path:t});return uv(r)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Hn(i)}async function fu(e,t){let i=[],r;try{r=(await ne({root:e,ref:t,maxBytes:cv.maxFileBytes})).text}catch(a){return Hn([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of lv(r))n.set(Ch(a)??a,o);for(let a of _P)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Hn(i)}function Jo(e,t){return ov.join(e.specsDir,t,"spec.md")}async function dv(e,t){let i=[],r=pe(e,t.name);for(let n of t.spec_changes){let a=Jo(e,n.capability),o=null;try{await J(e.nativeRoot,a),o=await ql(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await IP(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return Hn(i)}import fv from"node:path";var TP="comet.native.contract.v1",jP="comet.native.acceptance-set.v1",pv=/^[a-f0-9]{64}$/u,Dn={maxAcceptanceCriteria:yn.maxCriteria};function hv(e,t){let i=fv.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||fv.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function mv(e){return j("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
167
|
+
`))}function $P(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(pv))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(pv))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=hv(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:mv(e.markdown)},markdown:e.markdown}}function OP(e,t){return vv(e.id,t.id)}function vv(e,t){return e<t?-1:e>t?1:0}function gv(e){let t=hv(e.briefSource??"brief.md","Native brief source"),i=e.specs.map($P).sort((d,f)=>vv(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=$l(e.briefMarkdown,t,Dn.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Ol(f,d.source,Dn.maxAcceptanceCriteria-a.length)),a.push(...Kh(f,d.source,Dn.maxAcceptanceCriteria-a.length)));if(a.sort(OP),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Dn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Dn.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:mv(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=j(jP,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(TP,u)}}var Go={maxSpecs:64,maxFileBytes:pn,maxTotalBytes:4*1024*1024};async function gr(e){if(e.specChanges.length>Go.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ne({root:e.changeDir,ref:e.briefRef,maxBytes:Go.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ne({root:e.changeDir,ref:n.source,maxBytes:Go.maxFileBytes});if(i+=a.size,i>Go.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:gv({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import HP from"path";var pu="comet.selection.v2",DP=16*1024;function yv(e){return HP.join(e,".comet","current-change.json")}function LP(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function wv(e){return e===null||typeof e=="string"}function BP(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!LP(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&&!wv(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:pu,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==pu)throw new Error(`current change selection schema must be ${pu}`);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(!wv(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 Nv(e){let t;try{let r=yv(e),{bytes:n}=await Qi(r,DP,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...BP(t)}}import{promises as IR}from"node:fs";import Eu from"node:path";var Nu=jr(Ki(),1);import{promises as Tv}from"node:fs";import Ve from"node:path";import{execFileSync as VP}from"node:child_process";var FP=3e4,qP=8*1024*1024,hu=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function MP(e,t){try{return VP("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:FP,maxBuffer:qP,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new hu(e,t,r)}}function Uo(e,t){return MP(e,t).trim()}import vu from"node:path";import{promises as bv}from"node:fs";var Ko=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var mu="comet.native.supervisor.v2",zP=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function JP(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function GP(e,t){return vu.join(ei(e,t),"supervisor")}function Yo(e,t){return vu.join(GP(e,t),"state.json")}function kv(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==mu)throw new Error(`Native Supervisor state schema must be ${mu}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Ln(t.integration.targetCommit,"Native Supervisor target commit"),Ln(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Ln(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(Ln(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Ii(e,t){try{let i=await bv.readFile(Yo(e,t),"utf8"),r=JSON.parse(i);return kv(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function gu(e,t){kv(t),await bv.mkdir(e.changesRuntimeDir,{recursive:!0}),await Ye(Yo(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Ln(e,t){if(!zP.test(e))throw new Error(`${t} must be a Git commit`)}function UP(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function Sv(e){Ln(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:mu,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function wu(e){let t=JP(e.parent),i=yi(e.paths.projectRoot,t);if(!i)return null;let r=yi(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Lt(e.paths.projectRoot).map(o=>vu.resolve(o)).find(o=>be(o).currentBranch===t);if(!n)return null;let a=Sv({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return UP(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Ev(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var Cv="children.yaml",Bn="comet.native.children.v1",wr="comet.native.children.v2",jv=wr,KP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xv=new Set(["schema","children"]),YP=new Set(["schema","acceptance_index","children"]),XP=new Set(["name","depends_on","covers"]),QP=new Set(["name","summary","depends_on"]),ZP=new Set(["name","depends_on","covers"]);function Qo(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function Xo(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function Pv(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function yu(e,t){let i=Ve.normalize(Ve.resolve(e)),r=Ve.normalize(Ve.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function eR(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function Rv(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function tR(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===jv&&e.acceptance_index){let n=i.requiredAcceptanceIds??t??[],a=i.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);r.missing=n.filter(l=>!(l in e.acceptance_index)),r.extra=o.filter(l=>!a.includes(l));let s=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&r.mismatched.push(l)}let c=new Set(o);for(let l of e.children)r.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return r.uncovered=o.filter(l=>!Av(e.children,l)),_v(r)?r:null}if(e.schema===Bn&&t){let n=new Set(t);for(let a of e.children)r.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return r.uncovered=t.filter(a=>!Av(e.children,a)),_v(r)?r:null}return null}function Av(e,t){return e.some(i=>i.covers.includes(t))}function _v(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function $v(e){let t=new Set(e.acceptance.map(({id:n})=>n)),i=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),r=new Set(i);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&r.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])i.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...i],allowedAcceptanceIds:[...r]}}function iR(e){let t=Qo(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=Qo(n,`Native children acceptance_index.${r}`);if(Xo(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function rR(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=i.allowedAcceptanceIds??r,a=Object.keys(e),o=r.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(p=>d[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function nR(e,t,i={}){let r=(0,Nu.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=Qo(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Bn&&a!==wr)throw Xo(n,xv,"Native children contract"),new Error(`Native children schema must be ${Bn} or ${wr}`);let o=a===Bn?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Xo(n,o==="indexed-v2"?YP:xv,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,p)=>{let v=Qo(f,`Native child ${p}`);if(Xo(v,o==="indexed-v2"?ZP:o==="summary-v2"?QP:XP,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!KP.test(v.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:h?v.summary:null,depends_on:Pv(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Pv(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let p=f.depends_on.filter(v=>!u.has(v));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}eR(c);let d=i.policy==="advisory";if(a===jv){if(o==="indexed-v2"){let f=iR(n.acceptance_index);d||rR(f,t,i);let p=Object.keys(f);return d||Rv(c,p,p),{schema:wr,acceptance_index:f,children:c}}return{schema:wr,children:c}}return t&&!d&&Rv(c,t),{schema:Bn,children:c}}async function Zo(e){let t=Ve.join(e.changeDir,Cv);try{await Tv.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await ne({root:e.changeDir,ref:Cv}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=nR(i.text,e.acceptanceIds,n);return{contract:a,hash:i.hash,size:i.size,drift:r?tR(a,e.acceptanceIds,e.validation??{}):null}}function aR(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function oR(e){let t=aR(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function Ov(e){try{let t=await ne({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return oR(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Hv(e){return j("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function sR(e){let t=Lt(e.projectRoot);t.some(r=>yu(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Ve.resolve(n)))]){let n=await Ee(r);n&&i.push({projectRoot:r,paths:await kt(r,n.native.artifact_root),parent:yu(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function cR(e,t){let i=Ve.join(e.paths.changesDir,t,"comet-state.yaml");try{return await kn(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function lR(e,t){let i;try{i=await Tv.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Ve.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await kn(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function uR(e,t,i){let r=Ve.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Ve.sep}`))return null;let n=r.split(Ve.sep).join("/");try{let a=(0,Nu.parseDocument)(Uo(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:bn(a.toJS({mapAsMap:!1}))}catch{return null}}function dR(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Iv(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function bu(e){let t=Ve.join(e.paths.changesDir,e.state.name),i=await Ov(t),r=await Zo({changeDir:t,validation:$v(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:m})=>m)}:{},policy:"advisory"});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=Hv({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!r.drift;if(r.contract.schema===wr){let m=await Ii(e.paths,e.state.name);if(!m){let k=e.state.workspace.target_branch??e.state.workspace.change_branch;if(k){let N=await wu({paths:e.paths,parent:e.state.name,targetBranch:k,contract:r.contract});N&&(m=N,await gu(e.paths,N))}}if(m){let k=Ev(m);return e.state.children_contract_hash!==n||r.drift?{...k,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:k.children.map(N=>({...N,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...k,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let S=new Map(r.contract.children.map(k=>[k.name,k])),y=r.contract.children.map(k=>({name:k.name,summary:k.summary,dependsOn:[...k.depends_on],covers:[],status:o&&k.depends_on.every(N=>r.contract.children.filter(({name:E})=>E!==k.name).every(({name:E})=>E!==N))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let k of y){if(k.status!=="ready")continue;S.get(k.name).depends_on.length>0&&(k.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:y,readyChildren:y.filter(({status:k})=>k==="ready").map(({name:k})=>k),allDone:!1}}let s=await sR(e.paths),c=new Set(r.contract.children.map(({name:m})=>m)),l=new Map,u=new Map;for(let m of s){let S=m.parent&&a?`refs/heads/${a}`:"HEAD";for(let y of await lR(m,c)){let k={...y,source:m,committedState:uR(m,y.file,S)};l.set(y.state.name,[...l.get(y.state.name)??[],k])}for(let y of c){let k=await cR(m,y);k&&u.set(y,[...u.get(y)??[],{source:m,state:k}])}}let d=new Map;for(let m of r.contract.children){let S=(l.get(m.name)??[]).find(({source:N,committedState:E})=>N.parent&&E?.name===m.name&&Iv(E,a));if(S){d.set(m.name,{kind:"done",phase:S.state.phase,projectRoot:S.source.projectRoot,message:null});continue}let y=l.get(m.name)?.[0];if(y){d.set(m.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${m.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let k=u.get(m.name)??[];k.length>1?d.set(m.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${m.name} has multiple active workspace owners`}):k[0]&&d.set(m.name,dR(k[0].state,k[0].source,a))}let f=new Map(r.contract.children.map(m=>[m.name,m])),p=new Map,v=m=>{let S=p.get(m);if(S)return S;let y=f.get(m),N=y.depends_on.map(v).every(({status:C})=>C==="done"),E=d.get(m),b=E?.kind==="active"&&N?y.depends_on.filter(C=>!(l.get(C)??[]).some(({source:O,committedState:T})=>yu(O.projectRoot,E.projectRoot)&&T?.name===C&&Iv(T,a))):[],x,g=E?.message??null;E?.kind==="done"?(x=N?"done":"blocked",N||(g=`Native child ${m} was merged before its dependencies`)):E?.kind==="active"?(x=N&&b.length===0?"active":"blocked",N?b.length>0&&(g=`Native child ${m} does not include merged dependencies: ${b.join(", ")}`):g=`Native child ${m} started before its dependencies merged`):E?.kind==="blocked"?x="blocked":(x=o&&N?"ready":"pending",o||(g="Parent Shape confirmation is required"));let w={name:m,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:x,phase:E?.phase??null,projectRoot:E?.projectRoot??null,message:g};return p.set(m,w),w},h=r.contract.children.map(({name:m})=>v(m));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:h,readyChildren:h.filter(({status:m})=>m==="ready").map(({name:m})=>m),allDone:h.every(({status:m})=>m==="done")}}var dB=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var fR=/\b(Bearer|Basic)\s+[^\s"']+/giu,pR=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,hR=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,mR=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,vR=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,gR=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,wR=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function Fe(e){return e.replace(fR,"$1 [REDACTED]").replace(pR,"[REDACTED PRIVATE KEY]").replace(hR,"$1[REDACTED]@").replace(mR,"[REDACTED TOKEN]").replace(vR,'$1"[REDACTED]"').replace(gR,"$1$2$1$3$4[REDACTED]$4").replace(wR,"$1$2[REDACTED]")}import{promises as ER}from"node:fs";import Dv from"node:path";function es(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ts(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function pt(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function Lv(e,t){return e===null?null:pt(e,t)}function rs(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function CR(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 xR(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function is(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ku(e,t){if(e===null)return null;let i=pt(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Su(e,t){let i=pt(e,t);if(!Dv.isAbsolute(i))throw new Error(`${t} must be absolute`);return Dv.resolve(i)}function PR(e,t){let i=`Native local checks[${t}]`,r=es(e,i);if(ts(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>pt(l,`${i}.argv[${u}]`,!0)),a=is(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=ku(r.startedAt,`${i}.startedAt`),s=ku(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=rs(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:pt(r.id,`${i}.id`),name:pt(r.name,`${i}.name`),operationId:pt(r.operationId,`${i}.operationId`),status:a,repeatable:xR(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:rs(r.executionCount,`${i}.executionCount`),argv:n,cwd:Su(r.cwd,`${i}.cwd`),exitCode:CR(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:pt(r.log,`${i}.log`)}}function RR(e){let t="Native local execution state",i=es(e,t);if(ts(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==No)throw new Error(`Native local execution schema must be ${No}`);let r=es(i.workspace,"Native local workspace");ts(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=es(i.execution,"Native local execution");ts(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=ku(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:pt(o.operationId,"Native local execution.operationId"),stage:is(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:is(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Lv(o.executionId,"Native local execution.executionId"),status:is(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:rs(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(PR);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:No,change:pt(i.change,"Native local change"),basedOnStateVersion:rs(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Su(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Su(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Lv(r.branch,"Native local workspace.branch")},execution:n,checks:a}}async function Bv(e){let t;try{t=await ER.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return RR(i)}var TR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jR="comet-state.yaml",$R="state.json",zV=so("en");function Vv(e,t){if(!TR.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Eu.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}function Fv(e,t){return Eu.join(Vv(e,t),jR)}function OR(e,t){return Eu.join(ei(e,t),$R)}async function Cu(e,t){try{let i=await IR.readFile(Fv(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function qv(e,t){return kn(Fv(e,t))}async function Mv(e){let t=await qv(e.paths,e.name),i=OR(e.paths,e.name);try{let r=await Bv(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var tF=16*1024;async function Wv(e){let t=await Nv(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Wo(t.selection.change),t.selection)}async function zv(e,t){let i=[],r=U(e,t.name),n=ti(r,Be.stateRef),a;try{a=await mr(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=ti(r,a.trajectoryRef),s=await Bm(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await Ai(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=ti(r,a.checkpointRef);try{let u=await Do(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import PA from"path";import{isDeepStrictEqual as zu}from"util";var yr={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var HR=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function DR(e,t){return e<t?-1:e>t?1:0}function LR(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!HR.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(DR)}function xu(e=[]){return LR(e,"Native repair failed check IDs",yr.maxFailedCheckIds,!0)}function Jv(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function BR(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Jv(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Jv(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Pu(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(BR(r,a))break;i+=1,r=a}return i}import fg from"node:path";import{createHash as eg}from"node:crypto";import Gv from"path";var Ru="comet.native.implementation-scope.v2",tg="comet.native.content-snapshot-projection.v1",Vn="comet.native.content-snapshot-projection.v1",ig="comet.native.implementation-scope.v2",VR="comet.native.unresolved-scope-id.v1",FR="comet.native.scope-detail-overflow.v1",qR="comet.native.snapshot-projection-overflow.v2",Tu=/^[a-f0-9]{64}$/u,ji=1024*1024,MR=128,WR=128;function ve(e,t){return e<t?-1:e>t?1:0}function Au(e){if(!Tu.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function zR(e,t){return e===t?0:e===null?-1:t===null?1:ve(e,t)}function ui(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=Gv.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Gv.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function rg(e,t){return e==="."?e:ui(e,t)}function Nr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function JR(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:ui(e.path,`${t} path`),hash:e.hash,size:Nr(e.size,`${t} size`),type:"file"}}function GR(e,t){return{path:rg(e.path,`${t} path`),size:e.size===null?null:Nr(e.size,`${t} size`),type:e.type,reason:e.reason}}function UR(e,t){return ve(e.path,t.path)||ve(e.hash,t.hash)||e.size-t.size}function KR(e,t){return ve(e.path,t.path)||ve(e.reason,t.reason)||ve(e.type,t.type)||(e.size??-1)-(t.size??-1)}function qn(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
168
|
+
`,"utf8")}function li(e,t,i){let r=`${t}
|
|
169
|
+
${Or(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function YR(e){if(qn(e)<=ji)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=eg("sha256");a.update(`${qR}
|
|
170
|
+
`),e.omissionOverflow&&li(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(r+=1),n+=1,li(a,"omission",f)},s=f=>{r+=1,n+=1,li(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let p=i[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(f,1),p}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;qn(u)>ji;){if(i.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(i.length/4));for(let v=0;v<p;v+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-p))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function _u(e){let t=Ri(e),i=t.entries.map((n,a)=>JR(n,`Snapshot entry ${a}`));if(i.sort(UR),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>GR(n,`Snapshot omission ${a}`));return r.sort(KR),YR({schema:tg,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Mn(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:ui(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>ve(i.path,r.path)||ve(i.kind,r.kind))}function Wn(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Uv(e){return e?{hash:e.hash,size:e.size}:null}function ju(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:ve(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:Uv(c),after:Uv(l)})}}function ng(e,t){return{...e,attributedTo:t.filter(i=>Wn(i,e.path))}}function $u(e){let t=Mn(e.declaredArtifacts),i=[];return ju(e.baseline,e.current,r=>{i.push(ng(r,t))}),i}function _t(e,t){return{id:`scope:${j(VR,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function XR(e,t){let i=t.omitted.map(r=>_t({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(_t({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(_t({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function Kv(e,t){return XR(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Iu(e,t){return ve(e.kind,t.kind)||ve(e.source,t.source)||zR(e.path,t.path)||ve(e.id,t.id)}function QR(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Iu)}function ag(e){return[...new Set(e.map((t,i)=>ui(t,`Git path ${i}`)))].sort(ve)}function Yv(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function ZR(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function og(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=ag(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Yv(e.baseCommit,"Native external drift base commit"),targetBranch:ZR(e.targetBranch,"Native external drift target branch"),targetCommit:Yv(e.targetCommit,"Native external drift target commit"),paths:t}}function sg(e){if(typeof e.contractHash!="string"||!Tu.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Mn(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:ag(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:og(e.externalDrift)}}}function eA(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return ju(e,t,p=>{let v=i.some(h=>Wn(h,p.path));if(d+=1,c.push(p.path),!v&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<MR){let h=ng(p,i),m=qn(h);l+m<=ji?(a.push(h),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function cg(e,t){return _t({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function tA(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let i={changes:Nr(Number(t[1]),"Scope overflow change count"),unresolved:Nr(Number(t[2]),"Scope overflow unresolved count"),unattributed:Nr(Number(t[3]),"Scope overflow unattributed count")},r=Ti(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(cg(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function iA(e){let t=eg("sha256");t.update(`${FR}
|
|
171
|
+
`);let i=0;ju(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){li(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Wn(o,n.path)&&(a+=1,li(t,"change-attribution",o));li(t,"change-end",{attributionCount:a}),a===0&&li(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&li(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function lg(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=eA(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let x=new Set(i.externalDrift.paths),g=new Set(o.changePaths),w=i.externalDrift.paths.filter(C=>!g.has(C)||n.some(O=>Wn(O,C)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(x.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=j(Vn,e),c=j(Vn,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[x,g]of[["baseline",e],["current",t]])for(let w of g.omitted){if(l.length>=WR)break;l.push(_t({kind:"snapshot-omission",source:x,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${x} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...Kv("baseline",e),...Kv("current",t),...o.totalChanges===0&&a===null?[_t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(i.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(g=>x.has(g)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(g=>!x.has(g))}},v=x=>{let g=o.candidates.slice(0,x.detailedChangeCount),w=g.filter(We=>We.attributedTo.length===0&&!u.has(We.path)),C=o.totalChanges-g.length,O=o.totalUnattributed-w.length,T=d-x.detailedOmissionCount,he=O+T,Q=[...w.map(We=>_t({kind:"unattributed-change",source:"implementation-scope",path:We.path,evidence:{after:We.after,before:We.before,changeKind:We.kind}},`Changed path is not covered by a declared artifact: ${We.path}`)),...l.slice(0,x.detailedOmissionCount),...f,...he>0?[cg(x.overflowHash,{changes:C,unattributed:O,unresolved:he})]:[]],G=QR(Q),at=x.includeGitAdvisory?p():void 0;return{schema:Ru,contractHash:r,baselineProjectionRef:Au(s),baselineProjectionHash:s,currentProjectionRef:Au(c),currentProjectionHash:c,complete:G.length===0,declaredArtifacts:n,changes:g,unattributed:w,unresolvedScopes:G,noCodeReason:a,...at?{gitAdvisory:at}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},h=o.candidates.length,m=l.length,S=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let x=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:y});if(qn({...x,scopeHash:y})<=ji)break;if(S){S=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>h||d>m?iA({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):y,E=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:N}),b={...E,scopeHash:j(ig,E)};if(qn(b)>ji)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function Ou(e){let t=_u(e.baseline),i=_u(e.current),r=sg(e);return{authority:r,baseline:t,current:i,scope:lg(t,i,r)}}var rA=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function ht(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mt(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function Ti(e,t){if(typeof e!="string"||!Tu.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Xv(e,t,i){let r=Au(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function ns(e,t){let i=ht(e,"Native snapshot projection");if(mt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==tg)throw new Error("Native snapshot projection schema is invalid");let r=Ri({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=_u(r);if(j(Vn,i)!==j(Vn,n))throw new Error("Native snapshot projection is not canonical");let a=j(Vn,n);if(t!==void 0&&Ti(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Hu(e,t){let i=ht(e,`Declared artifact ${t}`);if(mt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:ui(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Qv(e,t){if(e===null)return null;let i=ht(e,t);return mt(i,["hash","size"],[],t),{hash:Ti(i.hash,`${t} hash`),size:Nr(i.size,`${t} size`)}}function Zv(e,t){let i=ht(e,`Implementation change ${t}`);if(mt(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Hu),n=Mn(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Qv(i.before,`Implementation change ${t} before`),o=Qv(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:ui(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function nA(e,t){let i=ht(e,`Unresolved scope ${t}`);mt(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?rg(i.path,`Unresolved scope ${t} path`):ui(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Fn(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>ui(n,`${t} ${a}`)),r=[...new Set(i)].sort(ve);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function ug(e){let t=ht(e,"Native implementation external drift");if(mt(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=Fn(t.paths,"Native external drift paths");return og({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function as(e){let t=ht(e,"Native implementation scope"),i=[...rA].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(mt(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Ru)throw new Error("Native implementation scope schema is invalid");let r=Ti(t.contractHash,"Implementation scope contractHash"),n=Ti(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Xv(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Ti(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Xv(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Hu);if(JSON.stringify(c)!==JSON.stringify(Mn(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Zv),u=[...l].sort((w,C)=>ve(w.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(C=>Wn(C,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Zv),p=t.externalDrift===void 0?void 0:ug(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(nA),S=m.filter(w=>w.kind==="scope-detail-overflow");if(S.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=S[0]===void 0?null:tA(S[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let k=t.noCodeReason,N=[...h.map(w=>_t({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(y?.changes??0)===0&&k===null?[_t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Iu))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(E)!==JSON.stringify(N.sort(Iu))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=ht(t.gitAdvisory,"Implementation scope Git advisory");if(mt(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Fn(w.changedPaths,"Git changed paths"),O=Fn(w.pathsPresentInSnapshotChanges,"Git present paths"),T=Fn(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),he=[...O,...T].sort(ve);if(JSON.stringify(he)!==JSON.stringify(C)||T.some(Q=>l.some(G=>G.path===Q)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:T}}let x={schema:Ru,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:k,...b?{gitAdvisory:b}:{},...p?{externalDrift:p}:{}},g=Ti(t.scopeHash,"Implementation scope scopeHash");if(j(ig,x)!==g)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:g}}function aA(e){let t=ht(e,"Native implementation scope authority");if(mt(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Hu);if(JSON.stringify(i)!==JSON.stringify(Mn(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=Fn(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:ug(t.externalDrift),a=sg({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function zn(e){let t=ht(e,"Native implementation scope bundle");mt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=aA(t.authority),r=ns(t.baseline),n=ns(t.current),a=as(t.scope),o=lg(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function dg(e){let t=as(e.scope);return zn({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var hg=/^[a-f0-9]{64}$/u;var oA="comet.native.acceptance-trace.v2",sA="comet.native.partial-allowance.v1",cA="comet.native.verification-evidence.v2";function It(e,t){if(!hg.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function mg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function vg(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Du(e,t,i=2e3){let r=Fe(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Jn(e,t){let i=fg.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||fg.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function lA(e,t,i){let r=Jn(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ct(r),a=r.toLowerCase(),o=i?Jn(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function Lu(e){let t=Jn(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function br(e,t){return e<t?-1:e>t?1:0}function os(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ss(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function gg(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function pg(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function uA(e){let t=os(e,"Native acceptance trace");if(ss(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!hg.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=Jn(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=os(o,`Native acceptance trace entry ${s}`);if(ss(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>Lu(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(br))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Jn(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Du(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>br(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=It(t.traceHash,"Native acceptance trace hash");if(j(oA,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function wg(e){let t=os(e,"Native partial allowance");if(ss(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(br))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:vg(t.change),scopeHash:It(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Du(t.reason,"Partial allowance reason"),confirmedSummary:Du(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:mg(t.sourceRevision),confirmedAt:gg(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=It(t.allowanceHash,"Native partial allowance hash");if(j(sA,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function Bu(e){let t=os(e,"Native verification evidence");if(ss(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=It(t.implementationScopeHash,"Native verification implementation scope hash"),r=uA(t.acceptanceTrace),n=It(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:It(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Lu(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(br)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(br);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Lu(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(br)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:vg(t.change),sourceRevision:mg(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:It(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:pg(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:lA(t.reportRef,"Native verification report ref"),reportHash:It(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:pg(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:gg(t.createdAt,"Native verification timestamp")},d=It(t.envelopeHash,"Native verification envelope hash");if(j(cA,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function Vu(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var yg="repairStagnation",Ie={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},fA=/^[a-f0-9]{64}$/u;var pA=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),hA=["data","runId","sequence","timestamp","type"],Ng=["disposition","overrideSummaryHash","signatureHash"],mA=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],bg=12;function qu(e,t){return e<t?-1:e>t?1:0}function kg(e,t,i){let r=Object.keys(e).sort(qu);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function cs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Gn(e,t){if(typeof e!="string"||!fA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function vA(e){if(!Array.isArray(e)||e.length>yr.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(qu)}function Sg(e){if(typeof e!="string"||e.length===0||e.length>Ie.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Fu(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Ie.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Ie.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Ie.maxTextCharacters&&(!n||e.length>Ie.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Ie.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Ie.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Fu(s,t+1,i,`${r}[${c}]`));return}let a=cs(e,r),o=Object.keys(a);if(o.length>Ie.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Ie.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Ie.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Fu(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function gA(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function wA(e,t,i){let r=cs(e,`Native repair trajectory event ${t+1}`);if(kg(r,hA,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(gA(r.timestamp),typeof r.type!="string"||!pA.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(Sg(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Fu(r.data,0,n,"Native trajectory event data"),cs(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Mu(e){let t=cs(e,"Native repair trajectory projection"),i=Object.keys(t).sort(qu),r=i.length===Ng.length&&i.every((l,u)=>l===Ng[u]);r||kg(t,mA,"Native repair trajectory projection");let n=Gn(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Gn(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Gn(t.contractHash,"Native repair trajectory contract hash"),s=vA(t.failedAcceptanceIds),c=xu(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function yA(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function NA(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??bg;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Pu({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<yr.warningAtConsecutiveFailures?"continue":a<yr.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function bA(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??bg;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Eg(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Ie.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Sg(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=wA(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Ie.maxTotalDataNodes||c>Ie.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Gn(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Gn(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,yg)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Mu(f[yg]);if(yA(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(i.length=0,o=0),p!==null&&(n=p),NA(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");bA(v,i,r);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>yr.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function Cg(e){return Eg(e).history}function xg(e){let t=Eg(e).latestProjection;return t?{...t}:null}var kr={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:[]},Wu=K("comet-native-runtime:v3:scope-reopen"),kA=[{skillVersion:"3",skillHash:K("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:K("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:K("comet-native-runtime:v1")}];function Pg(e){return e.skillVersion===kr.definition.metadata.version&&e.skillHash===Wu||kA.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function Rg(e){return K(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var jg=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],RA=new Set(jg),$g=new Set([...jg,"minimum_runtime_version","revision"]),AA=new Set([...$g,"operation"]),_A=512*1024,Ju=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),IA=new Set([...Ju,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Gu=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Ku(e,t){return PA.join(U(e,t),"transition.json")}function us(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Yu(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function ls(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Uu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!IA.has(u)),a=[...Ju].find(u=>!Object.hasOwn(i,u)),o=Ju.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Vu(i.summary,"Native transition journal event summary"),Fe(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Vu(i.noCodeReason,"Native transition journal event no-code reason"),Fe(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Mu(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function TA(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return Uu({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Uu(e,t)}function Xu(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?TA(e.eventData,e.evidenceHash):Uu(e.eventData,e.evidenceHash),n=eu(e.nextRun),a=e.previousRun===null?null:eu(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Ag(e,t,i=!1){if(e.skill!==kr.definition.metadata.name||(i?!Pg(e):e.skillVersion!==kr.definition.metadata.version||e.skillHash!==Wu)||e.orchestration!==kr.definition.orchestration.mode||e.pendingRef!==Be.pendingRef||e.trajectoryRef!==Be.trajectoryRef||e.contextRef!==Be.contextRef||e.artifactsRef!==Be.artifactsRef||e.checkpointRef!==Be.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function _g(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Ig(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function Qu(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Ag(o,"next Run",r||a!==null),Ig(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Ag(a,"previous Run",!0),Ig(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!zu(_g(a),_g(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function jA(e,t,i){return K(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Og(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Tg(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Zu(e,t,i,r,n=!1){let a=i.eventData,o=Tg(e),s=Tg(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&zu(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&zu(e.spec_changes,t.spec_changes),l=Rg({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=jA(e.name,a.summary,t.spec_changes),l=K(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function $A(e,t){let i=us(e);if(Yu(i,AA),i.schema!==ar)throw new Error(`Expected Native transition schema ${ar}`);let r=ls(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${ar} minimum_runtime_version must be ${3}`);let n=ls(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Xu(i,t),o=ai(i.previousState),s=ai(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Zu(o,s,a,i.operation),Qu(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:ar,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function OA(e,t){let i=us(e);if(Yu(i,RA),i.schema!==Sn)throw new Error(`Expected Native transition schema ${Sn}`);let r=Xu(i,t,!0),n=sr(i.previousState),a=sr(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Zu(n,a,r,Og(n,a,r.eventData),!0),Qu(n,a,r,!0),{schema:Sn,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function HA(e,t){let i=us(e);if(Yu(i,$g),i.schema!==or)throw new Error(`Expected Native transition schema ${or}`);if(ls(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${or} minimum_runtime_version must be 2`);let n=ls(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Xu(i,t,!0),o=cr(i.previousState),s=cr(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Zu(o,s,a,Og(o,s,a.eventData),!0),Qu(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:or,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function DA(e,t){let i=us(e);if(i.schema===ar)return{status:"current",journal:$A(i,t)};if(i.schema===Sn)return{status:"migration-required",journal:OA(i,t)};if(i.schema===or)return{status:"migration-required",journal:HA(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function LA(e,t){let i=Ku(e,t),r=ue(e,i);await J(r,i);try{let n=await Et({root:r,file:i,maxBytes:_A,label:`Native transition journal ${t}`});return DA(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Hg(e,t){let i=await LA(e,t);if(!i)return null;if(i.status==="migration-required")throw new Gu(t);return i.journal}var BA=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function VA(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function FA(e){return e?e.map(VA).join(" "):null}function qA(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function qe(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function MA(e){return e.map(t=>qe(t,[],null))}function WA(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[qe("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(qe("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(qe("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),qe("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(qe("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(qe("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),qe("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function ge(e,t){let i=t.commandArgs===void 0?qA(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?FA(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??MA(t.requiredInputs??[])}}function ds(e){let i=(e.findings??[]).filter(d=>!vr(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||BA.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return ge(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[qe("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return ge(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[qe("summary",["--summary"],"<summary>")]});if(n)return ge(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[qe("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),ge(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[qe("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):ge(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return ge(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=WA(e.state);return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Un from"path";var Dg=8,zA={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function JA(e){let t=zA[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:vr(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function GA(e,t,i){if(!i.path)return null;let r;if(Un.isAbsolute(i.path)?r=Un.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Un.resolve(pe(e,t.name),...i.path.split(/[\\/]/u)):r=Un.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!V(e.projectRoot,r))return null;let n=Un.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function UA(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function ed(e){return e.findings.map(t=>{let i=JA(t.code);return{code:t.code,message:t.message,severity:i.severity,path:GA(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:UA(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function td(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,Dg),truncated:t.length>Dg}}import Sr from"path";var fi={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Er=/^[a-f0-9]{64}$/u;function fs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ps(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function di(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Lg(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function id(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function KA(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Sr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Sr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Bg(e,t){return Sr.join(U(e,t),"checkpoints","progress.json")}function Kn(e,t){return Sr.join(U(e,t),"checkpoint-journal.json")}function Vg(e,t,i){if(!Er.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Sr.join(U(e,t),"checkpoints","manifests",`${i}.json`)}function YA(e){if(!Er.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function rd(e,t,i){let r=await Et({root:e,file:t,maxBytes:fi.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function XA(e,t){let i=fs(e,`checkpoint manifest artifact ${t}`);ps(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=KA(di(i.path,`checkpoint artifact ${t} path`,4096)),n=ct(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!Er.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:id(i.size,`checkpoint artifact ${t} size`)}}function nd(e,t){let i=fs(e,"Native checkpoint manifest");if(ps(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>fi.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(XA),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=id(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>fi.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Fg(e){return K(JSON.stringify(nd(e,e.change)))}function qg(e,t){let i=fs(e,"Native progress checkpoint");if(ps(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Lg(i.previousRevision,"Native checkpoint previousRevision"),a=Lg(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=di(i.manifestHash,"Native checkpoint manifestHash",64);if(!Er.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=YA(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=di(i.inputHash,"Native checkpoint inputHash",64);if(!Er.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=di(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=id(i.artifactCount,"Native checkpoint artifactCount");if(u>fi.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=di(i.summary,"Native checkpoint summary"),f=di(i.nextAction,"Native checkpoint nextAction");if(Fe(d)!==d||Fe(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:di(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function QA(e,t){let i=fs(e,"Native checkpoint journal");if(ps(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=ai(i.previousState),n=ai(i.nextState),a=qg(i.checkpoint,t),o=nd(i.manifest,t),s=di(i.inputHash,"Native checkpoint journal inputHash",64),c=K(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Er.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Fg(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function ZA(e,t,i){let r=Sr.resolve(e.projectRoot,...t.split("/"));if(!V(e.projectRoot,r)||V(e.nativeRoot,r)||V(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=ul(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await Et({root:e.projectRoot,file:r,maxBytes:fi.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function e_(e,t){let i=Bg(e,t),r=ue(e,i);await J(r,i);try{return qg(await rd(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function t_(e,t,i){let r=Vg(e,t,i),n=ue(e,r);await J(n,r);let a=await rd(n,r,"Native checkpoint manifest"),o=nd(a,t);if(Mg(e,o),Fg(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function ad(e,t){let i=Kn(e,t),r=ue(e,i);await J(r,i);try{let n=QA(await rd(r,i,"Native checkpoint journal"),t);return Mg(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Mg(e,t){for(let i of t.artifacts){let r=ul(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Wg(e){let t;try{t=await e_(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Bg(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await t_(e.paths,e.name,t.manifestHash);let a=K(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await ZA(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Vg(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}var zg=240,Jg=8,hs=50;function Gg(e){let t=Array.from(e);return t.length<=zg?e:`${t.slice(0,zg-1).join("")}…`}function i_(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function r_(e){let t=[...new Set(e.map(i_))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Jg),reasonCount:e.length,codesTruncated:t.length>Jg};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,hs),reasonsTruncated:e.length>hs}}}async function Ug(e){let t=null;try{let s=await ad(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Kn(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Kn(e.paths,e.state.name)}}let i=await Wg({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=r_(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:fi.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Gg(i.checkpoint.summary),nextAction:Gg(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:fi.maxArtifacts}}import{promises as WI}from"node:fs";import Rw from"node:path";import Kg from"node:path";var n_="comet.native.archive-preflight.v1",a_="comet.native.archive-preflight.v1",o_="comet.native.archive-operation.v1",s_=/^[a-f0-9]{64}$/u,Yg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,c_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function ms(e,t){return e<t?-1:e>t?1:0}function l_(e,t){if(typeof e!="string"||!s_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Tt(e,t){return e===null?null:l_(e,t)}function u_(e,t){let i=Kg.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Kg.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function d_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function f_(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function p_(e,t){if(!Yg.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Tt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Tt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Tt(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function h_(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Tt(e.contractHash,"Native archive contract hash"),acceptanceHash:Tt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Tt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Tt(e.reportHash,"Native archive report hash"),envelopeHash:Tt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Tt(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function m_(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!c_.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(ms);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function v_(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(ms)}function Xg(e){if(!Yg.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(p_).sort((l,u)=>ms(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:j(o_,l)})),r=h_(e.evidence),n=f_(e.workspace),a=[...new Set([...m_(e.findingCodes??[]),...v_({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(ms),o=d_(e.revision),s=u_(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:n_,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:j(a_,c)}}import{createHash as g_}from"node:crypto";import Qg from"node:path";var w_="comet.native.conflict-radar.v1",Ce=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}),y_="comet.native.conflict-radar.v1",N_="comet.native.conflict-radar-signals.v1",b_=/^[a-f0-9]{64}$/u,tw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,k_=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),S_=new Set(["capability","operation","baseHash"]),E_=new Set(["path","kind"]);function Cr(e,t){return e<t?-1:e>t?1:0}function od(e){return Buffer.byteLength(e,"utf8")}function sd(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function cd(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(od(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function C_(e,t){let i=cd(e,t,Ce.maxArtifactPathBytes),r=Qg.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||Qg.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function iw(e,t){if(typeof e!="string"||!b_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function x_(e,t){let i=sd(e,S_,t),r=cd(i.capability,`${t} capability`,Ce.maxCapabilityBytes);if(!tw.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:iw(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function P_(e,t){let i=sd(e,E_,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:C_(i.path,`${t} path`),kind:i.kind}}function R_(e,t){let i=sd(e,k_,`Conflict radar change ${t}`),r=cd(i.name,`Conflict radar change ${t} name`,Ce.maxNameBytes);if(!tw.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>Ce.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>Ce.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>x_(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>Cr(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>P_(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>Cr(c.path,l.path)||Cr(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:iw(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function A_(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Ce.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(R_).sort((n,a)=>Cr(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>Ce.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Ce.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function __(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function I_(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function T_(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function j_(e,t){let i=[],r=g_("sha256").update(`${N_}
|
|
172
|
+
[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(Or(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Ce.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(__(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=I_(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:T_(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function Zg(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function $_(e,t){return Zg(e.classification)-Zg(t.classification)||Cr(e.left,t.left)||Cr(e.right,t.right)}function ew(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:w_,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function rw(e){let t=A_(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(j_(t[s],t[c]));i.sort($_);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(y_,{changes:t,relationships:r}),a=i.slice(0,Ce.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=ew(t,i,a,n);for(;a.length>0&&od(JSON.stringify(o))>Ce.maxSerializedBytes;)a=a.slice(0,-1),o=ew(t,i,a,n);if(od(JSON.stringify(o))>Ce.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as pI}from"node:crypto";import{promises as nt}from"node:fs";import vt from"node:path";import nw from"node:path";var aw="comet.native.check-receipt.v1",O_="comet.native.check-receipt.v1",xr="scoped-text-safety",ld=1,xe=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),H_=/^[a-f0-9]{64}$/u,D_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,L_="comet.native.checker-policy.v1",B_="comet.native.check-input.v1",V_=2048,ow=j(L_,{policy:xr,version:ld,limits:xe,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),F_=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),sw=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],lw=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],q_=new Set(lw);function pi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hi(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function jt(e,t){if(typeof e!="string"||!H_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Te(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function uw(e,t){let i=Te(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function cw(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function M_(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>V_||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=nw.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||nw.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function W_(e){let t=pi(e,"Native check receipt checker");hi(t,["policy","version","hash","limits"],"Native check receipt checker");let i=pi(t.limits,"Native check receipt limits");if(hi(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==xr||t.version!==ld||t.hash!==ow||i.maxFiles!==xe.maxFiles||i.maxFileBytes!==xe.maxFileBytes||i.maxTotalBytes!==xe.maxTotalBytes||i.maxIssues!==xe.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:xr,version:ld,hash:ow,limits:{...xe}}}function z_(e){let t=pi(e,"Native check receipt contract");return hi(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:jt(t.expectedHash,"Native check expected contract hash"),beforeHash:jt(t.beforeHash,"Native check before contract hash"),afterHash:jt(t.afterHash,"Native check after contract hash")}}function J_(e){let t=pi(e,"Native check receipt implementation");return hi(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:jt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:jt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:jt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:jt(t.afterSnapshotHash,"Native check after snapshot hash")}}function G_(e,t){let i=pi(e,`Native check batch ${t}`);hi(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Te(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Te(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Te(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Te(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Te(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Te(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>xe.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>xe.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function U_(e){let t=pi(e,"Native check receipt counts");hi(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Te(t.filesSelected,"Native check filesSelected"),filesScanned:Te(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Te(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Te(t.bytesScanned,"Native check bytesScanned"),issueCount:Te(t.issueCount,"Native check issueCount"),recordedIssueCount:Te(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(G_):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>xe.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>xe.maxFiles||i.bytesScanned>xe.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function K_(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||sw.indexOf(e.kind)-sw.indexOf(t.kind)}function Y_(e){if(!Array.isArray(e)||e.length>xe.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=pi(r,`Native check issue ${n}`);if(hi(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!F_.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:M_(a.path,`Native check issue ${n} path`),line:uw(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(K_);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function X_(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!q_.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=lw.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function Q_(e){return j(B_,e)}function dw(e){let t=pi(e,"Native check receipt");if(hi(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==aw)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!D_.test(t.change))throw new Error("Native check receipt change name is invalid");let i=uw(t.sourceRevision,"Native check source revision"),r=W_(t.checker),n=z_(t.contract),a=J_(t.implementation),o=Q_({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(jt(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=cw(t.startedAt,"Native check receipt startedAt"),c=cw(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=U_(t.counts),u=Y_(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=X_(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>xe.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>xe.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:aw,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=jt(t.receiptHash,"Native check receipt content hash");if(j(O_,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var dd="comet.native.verification-receipt.v3",Z_=dd,eI="comet.native.declared-artifacts.v1",tI=/^[a-f0-9]{64}$/u,iI=/^acceptance-[a-f0-9]{64}$/u,rI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nI=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,aI=4096,oI=256,sI=1024;function Pr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function mi(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function $t(e,t){if(typeof e!="string"||!tI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function rt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=Fe(e).trim();if(!i||i.length>aI||i!==e.trim())throw new Error(`${t} is invalid`);return i}function ud(e,t){let i=rt(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function Yn(e,t,i=rt,r=!1,n=oI){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function cI(e,t){if(typeof e!="string"||!iI.test(e))throw new Error(`${t} is invalid`);return e}function lI(e){let t=Pr(e,"Native verification receipt bindings");if(mi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!rI.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:$t(t.contractHash,"Native verification receipt contract hash"),scopeHash:$t(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:$t(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:$t(t.artifactHash,"Native verification receipt artifact hash")}}function uI(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=nI.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function dI(e,t,i,r){let n=Pr(t,`Native ${e} evidence`);if(e==="automated-check"){if(mi(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=ud(n.startedAt,"Native automated-check start time"),o=ud(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Pr(n.worktree,"Native automated-check worktree");if(mi(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=Pr(n.afterFence,"Native automated-check after fence");if(mi(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:rt(n.executable,"Native automated-check executable"),args:Yn(n.args,"Native automated-check arguments",rt,!0),cwd:rt(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:rt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:$t(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:$t(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:$t(n.outputHash,"Native automated-check output hash"),outputSummary:rt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){mi(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=uI(n.checkReceiptRef);if($t(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Yn(n.subjects,"Native static inspection subjects",rt,r==="required-check"),rule:rt(n.rule,"Native static inspection rule"),resultSummary:rt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return mi(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Yn(n.steps,"Native manual evidence steps"),observations:Yn(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function fI(e){let t=Pr(e,"Native verification receipt");if(mi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=rt(t.actor,"Native verification receipt actor"),o=Yn(t.acceptanceIds,"Native receipt acceptance IDs",cI,r==="required-check",sI).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:dd,kind:i,role:r,status:n,bindings:lI(t.bindings),acceptanceIds:o,actor:a,issuedAt:ud(t.issuedAt,"Native verification receipt issue time"),evidence:dI(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==xr||s.actor!==`native-runtime:${xr}`))throw new Error("Native required check policy identity is invalid");return s}function fw(e){let t=Pr(e,"Native verification receipt");if(mi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==dd)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=fI(r),a=$t(t.receiptHash,"Native verification receipt hash");if(j(Z_,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function fd(e){return j(eI,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var vw=/^[a-f0-9]{64}$/u,Rr=ji,U1=3*Rr;function pd(e,t){let i=vt.relative(e,t);return i===""||!vt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${vt.sep}`)}function hI(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function vs(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function pw(e){let t=await nt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await nt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function mI(e,t){let i=vt.resolve(e),r=vt.resolve(t);if(!pd(i,r))throw new Error("Native evidence path is outside its change");let n=[await pw(i)],a=i;for(let o of vt.relative(i,r).split(vt.sep).filter(Boolean)){a=vt.join(a,o);let s=await pw(a);if(!pd(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function hw(e){for(let t of e){let i=await nt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!hI(t,i)||await nt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function vI(e,t,i={}){let r=await mI(t,vt.dirname(e));await i.afterParentChainCaptured?.();let n=await nt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await nt.realpath(e);if(!pd(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await nt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),nt.lstat(e),nt.realpath(e)]);if(await hw(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!vs(s,n)||!vs(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Rr)throw new Error(`Native evidence document exceeds ${Rr} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=Rr+1-d,S=await o.read(f,0,Math.min(f.length,m),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>Rr)throw new Error(`Native evidence document exceeds ${Rr} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),nt.lstat(e),nt.realpath(e)]);if(await hw(r),!v.isFile()||v.isSymbolicLink()||h!==a||!vs(s,p)||!vs(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function gw(e,t){if(!vw.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function gI(e,t,i,r,n){if(!vw.test(i))throw new Error("Native report evidence hash is invalid");let a=await $i({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||pI("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function Ar(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function wI(e,t,i,r,n){let a=gw(i,r);return n?vt.join(n,...a.split("/")):ti(U(e,t),a)}async function $i(e){let t=wI(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??ue(e.paths,t);return await J(i,t),vI(t,i,e.hooks)}function mw(e,t){return ns(e,t)}function yI(e,t){let i=as(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function NI(e,t,i){let r=wg(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function bI(e,t,i){let r=Bu(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function kI(e,t,i,r=!1,n){let a=await gs(e,t,i.implementationScopeRef,void 0,n);if(r&&await gI(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await ww(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Xn(e,t,i,r,n){let a=Ar(i,"scopes"),o=yI(await $i({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Ar(o.baselineProjectionRef,"snapshots"),c=Ar(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([$i({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>mw(d,s)),$i({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>mw(d,c))]);return dg({baseline:l,current:u,scope:o})}async function gs(e,t,i,r,n){return(await Xn(e,t,i,r,n)).scope}async function ww(e,t,i,r,n){let a=Ar(i,"allowances");return NI(await $i({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function Qn(e,t,i,r,n){let a=Ar(i,"receipts"),o=fw(await $i({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function _r(e,t,i,r,n){let a=Ar(i,"verifications"),o=bI(await $i({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await kI(e,t,o,!1,n),o}var SI=4096;async function EI(e,t=Ce.maxChanges){try{let i=await En({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function yw(e,t){let i=await At(e,t),[r,n]=await Promise.all([i.implementation_scope?gs(e,t,i.implementation_scope):null,Pt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function ws(e,t,i={}){let n=(await EI(e,SI)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await yw(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await yw(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=rw([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{execFile as OI}from"node:child_process";import{promisify as HI}from"node:util";import{constants as hd,promises as Me}from"node:fs";import Ir from"node:path";var xI=/^[a-f0-9]{64}$/u,PI=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Zn=512*1024;function RI(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ys(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return $e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function AI(e,t){let i=Ir.resolve(e),r=Ir.resolve(t);if(!V(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...Ir.relative(i,r).split(Ir.sep).filter(Boolean)]){o&&(a=Ir.join(a,o));let s=await Me.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Me.realpath(a);if(n.length>0&&!V(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function bw(e){for(let t of e){let i=await Me.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!RI(t,i)||await Me.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function _I(e){if(!xI.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function II(e){let t=PI.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function TI(e,t,i){return ti(U(e,t),_I(i))}async function jI(e,t,i){let r=await AI(i,Ir.dirname(e)),n=await Me.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Zn)throw new Error(`Native check receipt exceeds ${Zn} bytes`);let[a,o]=await Promise.all([Me.realpath(t),Me.realpath(e)]);if(!V(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":hd.O_RDONLY|hd.O_NOFOLLOW|hd.O_NONBLOCK,c=await Me.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Me.lstat(e),Me.realpath(e)]);if(await bw(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ys(n,l)||!ys(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=Zn+1-p,k=await c.read(v,0,Math.min(v.length,y),null);if(k.bytesRead===0)break;if(p+=k.bytesRead,p>Zn)throw new Error(`Native check receipt exceeds ${Zn} bytes`);f.push(Buffer.from(v.subarray(0,k.bytesRead)))}let[h,m,S]=await Promise.all([c.stat(),Me.lstat(e),Me.realpath(e)]);if(await bw(r),!m.isFile()||m.isSymbolicLink()||S!==o||!V(a,S)||!ys(l,h)||!ys(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function kw(e,t,i){let r=II(i),n=U(e,t),a=TI(e,t,r),o=ue(e,a);await J(o,a);let s=dw(await jI(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var ea=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var Fq=64*1024;var qq=3600*1e3;var Mq=HI(OI);var DI=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Sw(e,t){let i=[];for(let r of DI){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function Ew(e){if(e.receipt.kind!=="static-inspection")return null;let t=await kw(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var vi=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function LI(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function BI(e){let t=LI(e.bundle.baseline),i=await Ql(e.paths,t,{origin:"explicit",now:e.now});return Ou({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function xw(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Xn(e.paths,e.state.name,e.state.implementation_scope),i=await gr({changeDir:pe(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await BI({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function Pw(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await xw(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function VI(e){let t=await ne({root:pe(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Xh(t.text)}}function FI(e){let{receipt:t,implementationScope:i}=e,r=[],n=$u({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function qI(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:fd(e.implementationScope.scope.declaredArtifacts)}}async function Cw(e){let t=await Qn(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=Sw(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new vi([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await Ew({paths:e.paths,state:e.state,receipt:t});if(n){let a=FI({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function MI(e){let t=qI({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await Cw({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof vi)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await Cw({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof vi)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new vi(i)}function md(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function vd(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:md(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([xw(e),_r(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:md(e.state.verification_result,"stale"),envelope:null};let r=await VI({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await MI({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:md(e.state.verification_result,"invalid"),envelope:null}}}function zI(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function Aw(e){try{return await WI.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function JI(e,t){try{return(await ne({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function GI(e,t,i){let r=Jo(e,i.capability);if(!V(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=Rw.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await JI(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ne({root:pe(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function UI(e,t){return Aw(Ku(e,t))}async function gd(e){let t=e.now??new Date,i=await At(e.paths,e.name),r=await Pt(e.paths,e.name),n=await Ee(e.paths.projectRoot),a=zI(i.name,t),o=Rw.resolve(e.paths.nativeRoot,...a.split("/"));if(!V(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(v=>GI(e.paths,i.name,v))),vd({paths:e.paths,state:i,now:t}),ws(e.paths,i.name),zo(e.paths,i.name),rv(e.paths,i.name),UI(e.paths,i.name),Aw(o)]);return Xg({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}async function KI(e,t){let i=U(e,t.name),r=await mr(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Do(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Ai(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function YI(e,t){let i=await KI(e,t);return{committed:i,latest:xg(i),history:Cg(i)}}async function _w(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await YI(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var Ot=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function QI(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function ZI(e){return(await Wv(e))?.change??null}function eT(e,t,i=!1,r){return ds({state:e,archiveReady:t,evidenceRetreat:i}).command}async function tT(e,t){let i=pe(e,t.name),r=[...(await du(i,t.brief)).findings,...(await dv(e,t)).findings,...await zv(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Io(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await _m(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await gr({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Hg(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await fu(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function wd(e,t,i){let r=await ZI(e)===t,n=await Rl(e,t),a=await In(e,t),o;try{let w=await lu(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=ed({paths:e,state:o,findings:[w]}),O=ds({state:o,findings:C});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:td(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...i?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await Ug({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await _w(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await gr({changeDir:pe(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let he=await _r(e,o.name,o.verification_evidence);for(let Q of he.acceptanceTrace.entries)C.set(Q.acceptanceId,Q.status==="failed"?"failed":Q.status==="missing"?"missing":"satisfied")}let O=Uh({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),T=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...T?{nextPageCommand:QI(T),nextPageArgs:T}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await ws(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await Pt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let C=await Tn({paths:e,identity:w});C.state==="drifted"&&C.code&&f.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await Vo({paths:e,identity:w});f.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let w=await Pw({paths:e,state:o});v=w.freshness!=="fresh",p.push(...w.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await gd({paths:e,name:o.name}),m.push(...h.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let S=[...await tT(e,o),...s.findings,...d,...f,...p,...l,...m].filter((w,C,O)=>O.findIndex(T=>T.code===w.code&&T.path===w.path)===C),y=ed({paths:e,state:o,findings:S}),k=y.filter(w=>!vr(w.code)),N=o.phase==="archive"&&h?.ready===!0&&k.length===0,E=v||o.phase==="archive"&&(h?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=y.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),x=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",g=y.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:b||x?null:eT(o,N,E,i?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:td(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:ds({state:o,findings:y,archiveReady:N,evidenceRetreat:E,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:hs,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...g?{error:g.message}:{}}}async function Iw(e){let t;try{t=await Fl({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await XI.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Ot.maxChanges))throw new Error(`Native status exceeds ${Ot.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}import vT from"node:path";import{promises as Tw}from"node:fs";import iT from"node:path";var rT=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),nT=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),aT=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),oT=new Set(["status","summary"]);function Ns(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function bs(e,t,i){let r=new Set(Object.keys(e)),n=[...t].filter(o=>!r.has(o)),a=[...r].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${i} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function sT(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((i,r)=>i===t[r])}function Oi(e,t,i){return{status:"incompatible",file:e,snapshot:t,message:i}}function cT(e,t,i,r){let n=Ns(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=bs(n,rT,"Native Supervisor overlay");if(a)return a;if(r.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(r.parent!==t.name)return`Native Supervisor overlay parent ${r.parent} does not match ${t.name}`;let o=Ns(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=bs(o,nT,"Native Supervisor integration");if(s)return s;if(r.integration.headCommit!==r.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=Ns(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=bs(c,oT,"Native Supervisor finalVerification");if(l)return l;if(r.finalVerification.status!=="pending"||r.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==i.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let f=Ns(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let p=bs(f,aT,`Native Supervisor child ${u}`);if(p)return p;let v=i.children[u];if(f.name!==v.name||f.summary!==v.summary||!sT(f.dependsOn,v.depends_on))return`Native Supervisor child ${v.name} does not match the legacy children contract`;let h=v.depends_on.length===0?"ready":"pending";if(f.status!==h)return`Native Supervisor child ${v.name} has progressed beyond its initial ${h} status`;if(f.baseCommit!==null||f.candidateCommit!==null||f.verifiedCommit!==null||f.integrationCommit!==null||f.verification!==null||f.blocker!==null||f.projectRoot!==null||f.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function jw(e){let t=Yo(e.paths,e.state.name),i;try{let c=await Tw.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Oi(t,"","Native Supervisor overlay is not a regular file");i=await Tw.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Oi(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let r;try{r=JSON.parse(i)}catch(c){return Oi(t,i,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=iT.join(e.paths.changesDir,e.state.name),a;try{a=await Zo({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Oi(t,i,`Native children contract cannot be validated: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:i};let o;try{o=await Ii(e.paths,e.state.name)}catch(c){return Oi(t,i,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Oi(t,i,"Native Supervisor overlay disappeared during inspection");let s=cT(r,e.state,a.contract,o);return s?Oi(t,i,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:i}}function Ht(e,t,i){return e.language==="zh-CN"?i:t}function lT(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:Ht(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:Ht(e,"Reply A or B","回复 A 或 B"),agentInstruction:Ht(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i(Ht(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(Ht(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return i(Ht(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 uT(e){let t=e.workspace.change_branch??"<change-branch>",i=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${i}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${i}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function dT(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:r,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",r],requiredInputs:[],inputOptions:[],description:Ht(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Ht(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Ow(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Tr(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function fT(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function $w(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function pT(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function hT(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 gi(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Ow({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Tr("summary","--summary"),fT(e.name,e.flag)]}}function yd(e){return[gi({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),gi({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Hw(e,t,i={}){let r=pT(t)&&e.coordination_mode===void 0,n=lT(e,r),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[Tr("summary","--summary")],commandAlternatives:[gi({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:[Tr("summary","--summary")],commandAlternatives:[gi({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...yd({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:[Tr("summary","--summary")],commandAlternatives:[gi({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),gi({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:[Tr("summary","--summary")],commandAlternatives:[gi({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...yd({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:[Tr("summary","--summary")],commandAlternatives:yd({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?Ow({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:r?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:hT({change:e.name,stateVersion:e.state_version,coordinationRequired:r}),requiredInputs:["summary",...r?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...r?[$w("coordination-mode","--coordination-mode",Qh)]:[]],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} ${Ht(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=i.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?i.archiveBlockers&&i.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[$w("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...dT(e)],userCommunication:uT(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[gi({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")}}function mT(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Dw(e){let t=e.acceptance.reduce((i,r)=>({...i,[r.result]:i[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:mT(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}function gT(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function wT(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function yT(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:kT(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:ST(r,i)}))]:[]]}function NT(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function Lw(e,t){let i=be(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:vT.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}function bT(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function ks(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function kT(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:ks(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function ST(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:ks(e.summary,t)??""}}async function Nd(e){let t=await Mv(e),i=Dw(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await bu({paths:e.paths,state:t.state}),a=await jw({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await Ii(e.paths,e.name),s=o?{...Lw(e.paths,t.state),projectRoot:"."}:Lw(e.paths,t.state),c=Hw(t.state,n),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?bT(e.paths,o):[],d=o?(()=>{let v=o.children.filter(({status:N})=>N==="pending"||N==="ready").length,h=o.children.filter(({status:N})=>N==="active"||N==="verified").length,m=o.children.filter(({status:N})=>N==="integrated"||N==="archived").length,S=o.children.filter(({status:N})=>N==="blocked"||N==="needs-reverify").length,y=o.children.filter(({status:N})=>N==="active"||N==="blocked"||N==="needs-reverify").slice(0,16).map(N=>({name:N.name,summary:N.summary,projectRoot:N.task?.projectRoot??N.projectRoot?"<worktree>":null,reason:ks(N.blocker,u)})),k=o.children.flatMap(({blocker:N})=>{let E=ks(N,u);return E?[E]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:h,integrated:m,blocked:S,active:y,agents:{working:o.children.filter(({task:N})=>N!==null).length,completed:m},risks:k,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&m===o.children.length?"parent-verification":v>0?"dispatch-ready-child":S>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let v=o?.stateVersion??0,h=yT(t.state,o,u),m=wT(e.cursor,t.state.state_version,v),S=h.slice(m,m+32),y=m+S.length<h.length?gT(t.state.state_version,v,m+S.length):null;return{items:S,nextCursor:y,supervisorStateVersion:v}})():null,p=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:NT(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:i.blockers,workspace:s,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((v,h)=>({...v,[h.status]:(v[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...p?{supervisor:p}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:f.supervisorStateVersion}:{},items:f.items,nextCursor:f.nextCursor,nextPageArgs:f.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",f.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}var CT=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function Ss(e,t){let i=wi.normalize(bd(e)),r=wi.normalize(bd(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function bd(e){let t=wi.resolve(e);try{return ET.native(t)}catch{return t}}function xT(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function Bw(e){let t=[];for(let i of await Iw(e))t.push({name:i,kind:await Cu(e,i)?"portable":"legacy"});return t}async function Mw(e){let t=wi.resolve(e),i=Lt(e),r=i.length>0?i:[t];r.some(o=>Ss(o,t))||r.push(t);let n=[],a=new Set;for(let o of r.map(s=>wi.resolve(s)).sort()){let s=Ss(o,t)?t:o,c=bd(s),l=process.platform==="win32"?c.toLowerCase():c;if(a.has(l))continue;a.add(l);let u=await Ee(s);if(!u)continue;let d=await kt(s,u.native.artifact_root);n.push({projectRoot:s,config:u,paths:d,changes:await Bw(d)})}if(n.length===0){let o=await Ee(e);if(!o)throw new Error(".comet/config.yaml was not found in any registered worktree");let s=await kt(e,o.native.artifact_root);n.push({projectRoot:wi.resolve(e),config:o,paths:s,changes:await Bw(s)})}return n}function Vw(e,t){return e.workspace.bindingState==="aligned"?0:Ss(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function Ww(e,t){let i=new Map;for(let n of t)for(let a of n.changes)i.set(a.name,[...i.get(a.name)??[],{source:n,kind:a.kind}]);let r=[];for(let[n,a]of[...i.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:c,kind:l})=>{if(l==="portable")try{let u=await Nd({paths:c.paths,name:n});return{source:c,name:n,kind:l,workspace:u.workspace,portableStatus:u,inspectionError:null}}catch(u){return{source:c,name:n,kind:l,workspace:await In(c.paths,n),portableStatus:null,inspectionError:u instanceof Error?u.message:String(u)}}return{source:c,name:n,kind:l,workspace:await In(c.paths,n),portableStatus:null,inspectionError:null}}));o.sort((c,l)=>Vw(c,e)-Vw(l,e)||c.source.projectRoot.localeCompare(l.source.projectRoot));let s=o.filter(c=>c.workspace.bindingState==="aligned");s.length>1?r.push(...s):r.push(s[0]??o[0])}if(r.length>Ot.maxChanges)throw new Error(`Native status discovery exceeds ${Ot.maxChanges} visible changes`);return r.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function Fw(e,t){let i=t.toString(36),r=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${i}.${r}`}function PT(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=CT.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let r=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:i});if(t[3]!==r)throw new Error("Native workspace status cursor integrity failed");return i}function qw(e,t){let i=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:i?xT(i):null,nextPageArgs:i}}async function RT(e,t,i){let r=null;try{r=await av(e.source.paths,e.name)}catch{}return r?.state?{schema:"comet.native.status.v2",name:e.name,phase:r.state.phase,status:"blocked",migrationRequired:!0,legacySchema:r.schema,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:r.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:wd(e.source.paths,e.name,{details:t,...i?{acceptanceCursor:i}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function zw(e,t,i,r){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(i)throw new Error("Portable Native status includes the complete acceptance list");return!t&&e.portableStatus?e.portableStatus:Nd({paths:e.source.paths,name:e.name,details:t,...r?{cursor:r}:{}})}return RT(e,t,i)}async function Jw(e){let t=await Mw(e.projectRoot),i=(await Ww(e.projectRoot,t)).filter(r=>r.name===e.name);if(i.length===0){let r=t.find(n=>Ss(n.projectRoot,e.projectRoot))??t[0];return wd(r.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:r.config.native.clarification_mode,maxVerifyFailures:r.config.native.max_verify_failures})}if(i.length>1)throw new Error(`Native change ${e.name} has multiple aligned workspace bindings: ${i.map(r=>r.source.projectRoot).join(", ")}`);return zw(i[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function Gw(e){let t=await Mw(e.projectRoot),i=await Ww(e.projectRoot,t),r=j("comet.native.workspace-status-candidates.v1",i.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=PT({candidatesHash:r,total:i.length,cursor:e.cursor}),a=await Promise.all(i.slice(n,n+Ot.maxItems).map(u=>zw(u,!1))),o=[],s=i.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],f=n+d.length,p=f<i.length?Fw(r,f):null,v={schema:s,total:i.length,offset:n,items:d,nextCursor:p,...qw(wi.resolve(e.projectRoot),p),limits:{...Ot}};if(Buffer.byteLength(JSON.stringify(v),"utf8")>Ot.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<i.length?Fw(r,c):null;return{schema:s,total:i.length,offset:n,items:o,nextCursor:l,...qw(wi.resolve(e.projectRoot),l),limits:{...Ot}}}import ta from"path";import{realpathSync as JT}from"fs";var Dt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Uw(e){return e?e.command?`${Dt.next} ${e.command}`:e.ask_user?`${Dt.next} ${e.ask_user}`:null:null}function Kw(e,t){let i=[e.summary],r=Uw(e.next);return r&&i.push(r),e.user_message&&i.push("",Dt.relay,e.user_message),t!==void 0&&i.push("",Dt.details,JSON.stringify(t,null,2)),`${i.join(`
|
|
173
173
|
`)}
|
|
174
|
-
`}function
|
|
175
|
-
`)}var
|
|
176
|
-
`)}}let i=t.continuation;if(
|
|
177
|
-
comet native next <change-name> --
|
|
178
|
-
comet native
|
|
174
|
+
`}function Yw(e,t,i){let r=[e.summary],n=Uw(e.next);return n&&r.push(n),e.user_message&&r.push("",Dt.relay,e.user_message),r.push("",`${Dt.detail} ${t}`),i!==void 0&&r.push("",Dt.details,JSON.stringify(i,null,2)),r.join(`
|
|
175
|
+
`)}var FW={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var QW=16*1024*1024,ZW=256*1024,e2=16*1024;var o2=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var J2=16*1024*1024,Es=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Cs=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function B(e,t,i){return e==="zh-CN"?i:t}var kd={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Xw(e,t){return typeof e=="string"&&kd[e]?B(t,kd[e].en,kd[e].zh):typeof e=="string"?e:""}function Sd(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 TT(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let i of e){if(!i||typeof i!="object")return null;let r=i.result;if(r!=="passed"&&r!=="failed"&&r!=="blocked"&&r!=="pending")return null;t[r]+=1}return t}function Qw(e,t){let i=[];e.failed>0&&i.push(B(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&i.push(B(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&i.push(B(t,`${e.pending} pending`,`${e.pending} 项待验`));let r=B(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return i.length>0?`${r} (${i.join(", ")})`:r}function Zw(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let i=t.userCommunication;return!!(i&&typeof i=="object"&&typeof i.required=="boolean"&&(i.message===null||typeof i.message=="string")&&typeof i.agentInstruction=="string")}function Ed(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function jT(e,t,i){return e==="done"?B(i,"complete","已完成"):e==="await-user"?B(i,"waiting for a user decision","等待用户决定"):e==="blocked"?B(i,"paused: needs attention","已暂停,需要处理"):t?B(i,"waiting for a user decision","等待用户决定"):B(i,"ready to continue","可继续推进")}function $T(e,t,i){let r=Ed(e),n=[];i&&n.push(i);let a=B(r,`Change ${e.change}`,`需求 ${e.change}`),o=Xw(e.phase,r),s=jT(e.disposition,e.userCommunication.required,r);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Qw(t,r));let c=e.userCommunication,l=ey(e,r);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function ey(e,t){let i=e.userCommunication;if(e.disposition==="await-user"&&i.required)return{ask_user:B(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:B(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:B(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function OT(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function HT(e,t){let i=typeof e.name=="string"?e.name:"(unnamed)",r=Xw(e.phase,t),n=e.status==="await-user"?B(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?B(t,"paused","已暂停"):e.status==="done"?B(t,"complete","已完成"):B(t,"in progress","进行中"),a=Sd(e.acceptance)?`${B(t,", ",",")}${Qw(e.acceptance,t)}`:"";return` ${i} · ${r||String(e.phase??"?")} · ${n}${a}`}function DT(e){for(let t of e){let i=t.continuation;if(i?.userCommunication&&typeof i.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(i.userCommunication.agentInstruction))return"zh-CN"}return"en"}function LT(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 BT(e){if(e.healthy){let r=e.repaired?B("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):B("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=VT(e.continuation);return n?{summary:r,next:n}:{summary:r}}let i=Array.isArray(e.findings)?e.findings.length:0;return{summary:B("en",i>0?`Diagnostics found ${i} problem${i===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",i>0?`诊断发现 ${i} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:B("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function VT(e){return Zw(e)?ey(e,Ed(e)):void 0}function ty(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(LT(t))return BT(t);if(OT(t)){let r=DT(t.items);return{summary:[t.total===t.items.length?B(r,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):B(r,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>HT(a,r))].join(`
|
|
176
|
+
`)}}let i=t.continuation;if(Zw(i))return $T(i,FT(t),qT(t,Ed(i)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let r=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:B(r,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function FT(e){if(Sd(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t;if(Sd(i.acceptance))return i.acceptance;if(Array.isArray(i.acceptance))return TT(i.acceptance)}return null}function qT(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return B(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let i=e.migration;return i&&typeof i=="object"&&i.completed===!0?B(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function iy(e){let i=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:B("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof i.change=="string"?{next:{command:`comet native status ${i.change} --json`}}:{}};case"baseline-incomplete":return{summary:B("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:B("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:B("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:B("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:B("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:B("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:B("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:B("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var ry=["--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."],xd=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:ry,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>]
|
|
177
|
+
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>]
|
|
178
|
+
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]
|
|
179
|
+
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 Cd(e,t){return`${e}:
|
|
179
180
|
${t.map(i=>` ${i}`).join(`
|
|
180
|
-
`)}`}function
|
|
181
|
-
${i.output}`),i.examples&&r.push("",
|
|
181
|
+
`)}`}function MT(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return xd[i]||t.length>1&&xd[t[0]]?.subcommands?i:t[0]}function WT(e=[]){let t=MT(e),i=xd[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Cd("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...ry];return n&&n.length>0&&r.push("",Cd("Options",n)),r.push("",`Output:
|
|
182
|
+
${i.output}`),i.examples&&r.push("",Cd("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
|
|
182
183
|
`)}
|
|
183
|
-
`}}var
|
|
184
|
-
`}function
|
|
185
|
-
`}:e.error?{exitCode:e.exitCode,stderr:r?
|
|
186
|
-
${
|
|
184
|
+
`}}var zT=WT().usage;var fz=10*1024*1024,gt=class extends Error{};function ia(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new gt(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function xs(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new gt(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new gt(`${t} requires a value`);return e.splice(r,2),n}function ay(e){if(e.length>0)throw new gt(`Unexpected argument: ${e[0]}`)}function Pd(e,t){let i=ta.normalize(ny(e)),r=ta.normalize(ny(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function ny(e){let t=ta.resolve(e);try{return JT.native(t)}catch{return t}}function GT(e){let t=ta.resolve(e),i=be(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=be(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Pd(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Pd(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:Pd(process.cwd(),i.currentWorktreeRoot)?ta.resolve(process.cwd()):i.currentWorktreeRoot}async function oy(e){return e?GT(e):xl(process.cwd())}function sy(e){return JSON.stringify(e,null,2)+`
|
|
185
|
+
`}function cy(e,t,i){return{command:e,exitCode:0,data:t,text:i??sy(t)}}function UT(e,t){if(t instanceof gt)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Es)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 Cs)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof qo)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 jn)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 Ko)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Mo)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 vi)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ea)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function ly(e,t){let i=UT(e,t),r=i.error;if(!r)return i;let n=iy({code:r.code,message:r.message,data:i.data});return n?{...i,envelope:n}:i}function uy(e,t,i=!1){let r=e.envelope??ty(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...r===void 0?{}:{summary:r.summary,...r.next===void 0?{}:{next:r.next},...r.user_message===void 0?{}:{user_message:r.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
186
|
+
`}:e.error?{exitCode:e.exitCode,stderr:r?Yw(r,e.error.message,i?e.data:void 0):e.error.message}:r?{exitCode:e.exitCode,stdout:Kw(r,i?e.data:void 0)}:i&&e.text!==void 0&&e.data!==void 0&&e.text!==sy(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
187
|
+
${Dt.details}
|
|
187
188
|
${JSON.stringify(e.data,null,2)}
|
|
188
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}async function
|
|
189
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}async function dy(e,t){let i=ia(e,"--details"),r=xs(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(i&&!n)throw new gt("status --details requires a change name");if(r&&n&&!i)throw new gt("--cursor for a named status requires --details");ay(e);let a=n?await Jw({projectRoot:t,name:n,details:i,...r?{detailsCursor:r}:{}}):await Gw({projectRoot:t,...r?{cursor:r}:{}});return cy("status",a)}async function fy(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{ia(n,"--json"),ia(n,"--verbose"),c=xs(n,"--project-root");let d=[...n,...a],f=await oy(c);l=await t(d,f)}catch(d){l=ly(e,d)}let u=uy(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
189
190
|
`)?"":`
|
|
190
|
-
`)),u.exitCode}process.exitCode=await
|
|
191
|
+
`)),u.exitCode}process.exitCode=await fy("status",dy);
|