@rpamis/comet 0.4.0-beta.18 → 0.4.0-beta.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -3
- package/assets/manifest.json +3 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +121 -121
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +84 -84
- package/assets/skills/comet/scripts/comet-guard.mjs +152 -152
- package/assets/skills/comet/scripts/comet-handoff.mjs +123 -123
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +75 -75
- package/assets/skills/comet/scripts/comet-hook-router.mjs +91 -91
- package/assets/skills/comet/scripts/comet-intent.mjs +6 -6
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +79 -79
- package/assets/skills/comet/scripts/comet-runtime.mjs +169 -169
- package/assets/skills/comet/scripts/comet-state.mjs +88 -88
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +97 -97
- package/assets/skills/comet-build/SKILL.md +21 -6
- package/assets/skills/comet-design/SKILL.md +2 -2
- package/assets/skills/comet-native/SKILL.md +7 -7
- package/assets/skills/comet-native/reference/artifacts.md +3 -3
- package/assets/skills/comet-native/reference/clarification.md +1 -1
- package/assets/skills/comet-native/reference/commands.md +3 -3
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +114 -113
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +123 -123
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +88 -88
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +116 -116
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +100 -100
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +118 -118
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +95 -95
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +145 -144
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +101 -101
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +83 -83
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +87 -87
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +98 -98
- package/assets/skills/comet-review/SKILL.md +121 -0
- package/assets/skills/comet-review/agents/openai.yaml +5 -0
- package/assets/skills-zh/comet-build/SKILL.md +21 -6
- package/assets/skills-zh/comet-design/SKILL.md +2 -2
- package/assets/skills-zh/comet-native/SKILL.md +7 -7
- package/assets/skills-zh/comet-native/reference/artifacts.md +3 -3
- package/assets/skills-zh/comet-native/reference/clarification.md +1 -1
- package/assets/skills-zh/comet-native/reference/commands.md +3 -3
- package/assets/skills-zh/comet-review/SKILL.md +121 -0
- package/assets/skills-zh/comet-review/agents/openai.yaml +5 -0
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +5 -9
- package/dist/app/commands/init.js.map +1 -1
- package/dist/app/commands/update.d.ts.map +1 -1
- package/dist/app/commands/update.js +5 -9
- package/dist/app/commands/update.js.map +1 -1
- package/dist/domains/comet-classic/classic-command-context.d.ts +9 -0
- package/dist/domains/comet-classic/classic-command-context.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-command-context.js +10 -0
- package/dist/domains/comet-classic/classic-command-context.js.map +1 -1
- package/dist/domains/comet-classic/classic-guard.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-guard.js +2 -2
- package/dist/domains/comet-classic/classic-guard.js.map +1 -1
- package/dist/domains/comet-classic/classic-handoff.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-handoff.js +44 -6
- package/dist/domains/comet-classic/classic-handoff.js.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard.js +2 -1
- package/dist/domains/comet-classic/classic-hook-guard.js.map +1 -1
- package/dist/domains/comet-classic/classic-intent-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-intent-command.js +2 -1
- package/dist/domains/comet-classic/classic-intent-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-resume-probe-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-resume-probe-command.js +4 -3
- package/dist/domains/comet-classic/classic-resume-probe-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-runtime-run.d.ts +6 -0
- package/dist/domains/comet-classic/classic-runtime-run.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-runtime-run.js +58 -9
- package/dist/domains/comet-classic/classic-runtime-run.js.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.js +8 -5
- package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-validate-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-validate-command.js +2 -2
- package/dist/domains/comet-classic/classic-validate-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-workspace-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-workspace-command.js +3 -3
- package/dist/domains/comet-classic/classic-workspace-command.js.map +1 -1
- package/dist/domains/comet-entry/hook-adapter.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-adapter.js +4 -1
- package/dist/domains/comet-entry/hook-adapter.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 +2 -0
- package/dist/domains/comet-native/native-archive-command.js.map +1 -1
- package/dist/domains/comet-native/native-atomic-file.d.ts.map +1 -1
- package/dist/domains/comet-native/native-atomic-file.js +17 -10
- package/dist/domains/comet-native/native-atomic-file.js.map +1 -1
- package/dist/domains/comet-native/native-children.d.ts +18 -2
- package/dist/domains/comet-native/native-children.d.ts.map +1 -1
- package/dist/domains/comet-native/native-children.js +73 -8
- package/dist/domains/comet-native/native-children.js.map +1 -1
- package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +10 -4
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-shared.js +18 -5
- package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
- package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
- package/dist/domains/comet-native/native-hook-guard.js +15 -2
- package/dist/domains/comet-native/native-hook-guard.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 +94 -15
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts +19 -7
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +115 -72
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-portable-migration-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-migration-runtime.js +9 -4
- package/dist/domains/comet-native/native-portable-migration-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.d.ts +14 -1
- package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.js +59 -1
- package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-pull-request-finish.d.ts +35 -0
- package/dist/domains/comet-native/native-pull-request-finish.d.ts.map +1 -0
- package/dist/domains/comet-native/native-pull-request-finish.js +282 -0
- package/dist/domains/comet-native/native-pull-request-finish.js.map +1 -0
- package/dist/domains/comet-native/native-status-discovery.d.ts.map +1 -1
- package/dist/domains/comet-native/native-status-discovery.js +24 -6
- package/dist/domains/comet-native/native-status-discovery.js.map +1 -1
- package/dist/domains/comet-native/native-workspace-finish.d.ts +6 -0
- package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -1
- package/dist/domains/comet-native/native-workspace-finish.js +86 -35
- package/dist/domains/comet-native/native-workspace-finish.js.map +1 -1
- package/dist/domains/dashboard/web/assets/{abnfDiagram-N423BO3Z-B5cFR6hS.js → abnfDiagram-N423BO3Z-BYya6ofk.js} +1 -1
- package/dist/domains/dashboard/web/assets/{arc-CVQDtMsu.js → arc-DJbo4TD3.js} +1 -1
- package/dist/domains/dashboard/web/assets/{architectureDiagram-T3A2C74G-C0v0kULK.js → architectureDiagram-T3A2C74G-D8uZ2IB-.js} +1 -1
- package/dist/domains/dashboard/web/assets/{blockDiagram-VBNYF7ZC-DpHLuxu4.js → blockDiagram-VBNYF7ZC-B16BVj-r.js} +1 -1
- package/dist/domains/dashboard/web/assets/{c4Diagram-5PPSVZJV-BHnFxUs1.js → c4Diagram-5PPSVZJV-ayV208_D.js} +1 -1
- package/dist/domains/dashboard/web/assets/channel-CEsrvmig.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-2GRJ4B5K-CGC9gh5n.js → chunk-2GRJ4B5K-Bn5o8p3H.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-2Q5K7J3B-l4puLU_O.js → chunk-2Q5K7J3B-BnF1SI6B.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-5RXB4S5H-ls9jQHZc.js → chunk-5RXB4S5H-ETnma053.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-5VM5RSS4-BVavmTEq.js → chunk-5VM5RSS4-Cuvy639H.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-6Q2QTUOP-Dungt2g9.js → chunk-6Q2QTUOP-DOXBzl73.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-GF5L2VYU-BidXO_ZP.js → chunk-GF5L2VYU-CfREXlEl.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-JWPE2WC7-57L5Up5X.js → chunk-JWPE2WC7-DWIdpYTb.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-KBJHAD2P-C5u5vbwr.js → chunk-KBJHAD2P-BnqPcfZB.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-RYQCIY6F-CvLz21I2.js → chunk-RYQCIY6F-DdJ00fZz.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-D5nJpckG.js → chunk-XXDRQBXY-BVDhdJyW.js} +1 -1
- package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-CKFe0hg4.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-CKFe0hg4.js +1 -0
- package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-Dp0JAGyE.js → cose-bilkent-JH36ORCC-C-nglwHC.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-EjC54l1g.js → cynefin-VYW2F7L2-C8TMmrbP.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefinDiagram-MW4NZA55-CpYrW3w3.js → cynefinDiagram-MW4NZA55-C3pnQnjg.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dagre-VZM6K2ZE-h5K39rCk.js → dagre-VZM6K2ZE-DY7UWiPI.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-7IWD3JNH-CKQj9O4H.js → diagram-7IWD3JNH-voTyDkQ5.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-B4RE2ZJO-DXRIYcnW.js → diagram-B4RE2ZJO-B3VkUMck.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-LBJQPF4R-wWutQYmv.js → diagram-LBJQPF4R-BdJzPkv8.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-Q27KOJAE-EgXLJQYi.js → diagram-Q27KOJAE-Bsq0anZx.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-UB23O5K3-CsQRXDQZ.js → diagram-UB23O5K3-CBaKRbcu.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ebnfDiagram-BXEA7PRR-gm328Eho.js → ebnfDiagram-BXEA7PRR-Bl9Bm5wa.js} +1 -1
- package/dist/domains/dashboard/web/assets/{erDiagram-JOGREHBK-BbbMVUx_.js → erDiagram-JOGREHBK-DjOZzfKI.js} +1 -1
- package/dist/domains/dashboard/web/assets/{flowDiagram-UKHOOZJN-1Y7scCns.js → flowDiagram-UKHOOZJN-C21e4siK.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ganttDiagram-PKOTCBZU-BAoBqczv.js → ganttDiagram-PKOTCBZU-Bs62uy6-.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraphDiagram-DS77QQ5N-CMUAyEzl.js → gitGraphDiagram-DS77QQ5N-DQY_Ba00.js} +1 -1
- package/dist/domains/dashboard/web/assets/{index-CCApJ0Yr.js → index-BLv71GRj.js} +1 -1
- package/dist/domains/dashboard/web/assets/{index-DWdm_XBi.js → index-Be4r99N4.js} +3 -3
- package/dist/domains/dashboard/web/assets/index-ByVYiA6g.css +1 -0
- package/dist/domains/dashboard/web/assets/{infoDiagram-6WML65LV-BaCdtYYC.js → infoDiagram-6WML65LV-CNgNNG9l.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ishikawaDiagram-WSZJBQD7-DQQlNnjU.js → ishikawaDiagram-WSZJBQD7-D9k1fTO1.js} +1 -1
- package/dist/domains/dashboard/web/assets/{journeyDiagram-NVQOT4AX-DW9wUMqn.js → journeyDiagram-NVQOT4AX-CHijUnPl.js} +1 -1
- package/dist/domains/dashboard/web/assets/{kanban-definition-27J2QSJJ-C_ITaZ0q.js → kanban-definition-27J2QSJJ-DfWlntDq.js} +1 -1
- package/dist/domains/dashboard/web/assets/{linear-DXOo6ZRT.js → linear-o6hemX-z.js} +1 -1
- package/dist/domains/dashboard/web/assets/{mermaid.core-ol-0NI97.js → mermaid.core-B1DoOsPD.js} +4 -4
- package/dist/domains/dashboard/web/assets/{mindmap-definition-FAOFIHXS-CHF_HOLV.js → mindmap-definition-FAOFIHXS-COMQF9Yy.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pegDiagram-VL7TDLO6-wQEvkNF8.js → pegDiagram-VL7TDLO6-C_21n7Ps.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pieDiagram-7S7Q4E2Y-C3H3kiIP.js → pieDiagram-7S7Q4E2Y-D3EmoYDY.js} +1 -1
- package/dist/domains/dashboard/web/assets/{quadrantDiagram-CIZ2JOQS-S0FdVzJb.js → quadrantDiagram-CIZ2JOQS-C3fGdiMa.js} +1 -1
- package/dist/domains/dashboard/web/assets/{railroadDiagram-AXF67PYL-DCDXDaVg.js → railroadDiagram-AXF67PYL-mIsjemD-.js} +1 -1
- package/dist/domains/dashboard/web/assets/{requirementDiagram-LRYGKXZP-BW8J4gO_.js → requirementDiagram-LRYGKXZP-D_UMpS5e.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sankeyDiagram-W5VNT64P-DQQBmLoy.js → sankeyDiagram-W5VNT64P-D1MwyMF6.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sequenceDiagram-SI44F4Z6-2tDcli0Y.js → sequenceDiagram-SI44F4Z6-B8jp1RxX.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sizeCapture-X5ZJPWSS-4sEZLBKb.js → sizeCapture-X5ZJPWSS-BKioI1Ql.js} +1 -1
- package/dist/domains/dashboard/web/assets/{stateDiagram-OKZ733FA-OgPb8pyR.js → stateDiagram-OKZ733FA-B7l8_CDo.js} +1 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-BIxuwbeV.js +1 -0
- package/dist/domains/dashboard/web/assets/{swimlanes-SLNWSIFB-DR7lwtxd.js → swimlanes-SLNWSIFB-951PRLYp.js} +2 -2
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-CEo6cGsy.js +8 -0
- package/dist/domains/dashboard/web/assets/{timeline-definition-Z64GVDOM-DNIJVlQV.js → timeline-definition-Z64GVDOM-CeyA2KbI.js} +1 -1
- package/dist/domains/dashboard/web/assets/{vennDiagram-T6HMQDX7-CClhw4QZ.js → vennDiagram-T6HMQDX7-BHe0TZJV.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardleyDiagram-T6FBY63Y-DzR3aFPS.js → wardleyDiagram-T6FBY63Y-CWqdSzJ-.js} +1 -1
- package/dist/domains/dashboard/web/assets/{xychartDiagram-ELKLHX3M-DZhq0ZRj.js → xychartDiagram-ELKLHX3M-DCKiZVPV.js} +1 -1
- package/dist/domains/dashboard/web/index.html +2 -2
- package/dist/domains/dashboard/workspace.d.ts +3 -0
- package/dist/domains/dashboard/workspace.d.ts.map +1 -1
- package/dist/domains/dashboard/workspace.js +23 -2
- package/dist/domains/dashboard/workspace.js.map +1 -1
- package/dist/domains/integrations/openspec.d.ts +1 -1
- package/dist/domains/integrations/openspec.d.ts.map +1 -1
- package/dist/domains/integrations/openspec.js +43 -84
- package/dist/domains/integrations/openspec.js.map +1 -1
- package/dist/domains/integrations/superpowers.d.ts +10 -1
- package/dist/domains/integrations/superpowers.d.ts.map +1 -1
- package/dist/domains/integrations/superpowers.js +73 -4
- package/dist/domains/integrations/superpowers.js.map +1 -1
- package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
- package/dist/domains/skill/platform-inspect.js +3 -3
- package/dist/domains/skill/platform-inspect.js.map +1 -1
- package/dist/domains/skill/platform-install.d.ts +3 -1
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +15 -9
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/domains/skill/project-instructions.d.ts.map +1 -1
- package/dist/domains/skill/project-instructions.js +6 -0
- package/dist/domains/skill/project-instructions.js.map +1 -1
- package/dist/domains/skill/uninstall.d.ts.map +1 -1
- package/dist/domains/skill/uninstall.js +39 -29
- package/dist/domains/skill/uninstall.js.map +1 -1
- package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
- package/dist/domains/workflow-contract/contained-atomic-write.js +18 -10
- package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
- package/dist/domains/workflow-contract/project-config.d.ts +4 -2
- package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config.js +132 -0
- package/dist/domains/workflow-contract/project-config.js.map +1 -1
- package/dist/domains/workflow-contract/types.d.ts +9 -0
- package/dist/domains/workflow-contract/types.d.ts.map +1 -1
- package/dist/platform/fs/strip-bom.d.ts +10 -0
- package/dist/platform/fs/strip-bom.d.ts.map +1 -0
- package/dist/platform/fs/strip-bom.js +12 -0
- package/dist/platform/fs/strip-bom.js.map +1 -0
- package/dist/platform/install/platforms.d.ts +11 -0
- package/dist/platform/install/platforms.d.ts.map +1 -1
- package/dist/platform/install/platforms.js +36 -0
- package/dist/platform/install/platforms.js.map +1 -1
- package/dist/platform/process/external-command.d.ts +1 -0
- package/dist/platform/process/external-command.d.ts.map +1 -1
- package/dist/platform/process/external-command.js +2 -1
- package/dist/platform/process/external-command.js.map +1 -1
- package/eval/local/tests/conftest.py +18 -3
- package/eval/local/tests/scaffold/test_conftest_helpers.py +57 -0
- package/package.json +11 -26
- package/dist/domains/dashboard/web/assets/channel-eM0x3m1G.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-CEFhao2K.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-CEFhao2K.js +0 -1
- package/dist/domains/dashboard/web/assets/index-DhhbseFJ.css +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-CiDNPr4P.js +0 -1
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-DggHFP9q.js +0 -8
- package/eval/local/tasks/comet-native-interrupted-transition/environment/.comet/config.yaml +0 -6
|
@@ -1,77 +1,77 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`)}};
|
|
6
|
-
`)
|
|
4
|
+
var Xp=Object.create;var Sa=Object.defineProperty;var Qp=Object.getOwnPropertyDescriptor;var Zp=Object.getOwnPropertyNames;var eh=Object.getPrototypeOf,th=Object.prototype.hasOwnProperty;var Nn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var L=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var w=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},rh=(t,e)=>{for(var r in e)Sa(t,r,{get:e[r],enumerable:!0})},nh=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Zp(e))!th.call(t,i)&&i!==r&&Sa(t,i,{get:()=>e[i],enumerable:!(n=Qp(e,i))||n.enumerable});return t};var Ve=(t,e,r)=>(r=t!=null?Xp(eh(t)):{},nh(e||!t||!t.__esModule?Sa(r,"default",{value:t,enumerable:!0}):r,t));var P=w(B=>{"use strict";var Ea=Symbol.for("yaml.alias"),hc=Symbol.for("yaml.document"),kn=Symbol.for("yaml.map"),mc=Symbol.for("yaml.pair"),Pa=Symbol.for("yaml.scalar"),Sn=Symbol.for("yaml.seq"),je=Symbol.for("yaml.node.type"),ih=t=>!!t&&typeof t=="object"&&t[je]===Ea,ah=t=>!!t&&typeof t=="object"&&t[je]===hc,oh=t=>!!t&&typeof t=="object"&&t[je]===kn,sh=t=>!!t&&typeof t=="object"&&t[je]===mc,gc=t=>!!t&&typeof t=="object"&&t[je]===Pa,ch=t=>!!t&&typeof t=="object"&&t[je]===Sn;function vc(t){if(t&&typeof t=="object")switch(t[je]){case kn:case Sn:return!0}return!1}function lh(t){if(t&&typeof t=="object")switch(t[je]){case Ea:case kn:case Pa:case Sn:return!0}return!1}var uh=t=>(gc(t)||vc(t))&&!!t.anchor;B.ALIAS=Ea;B.DOC=hc;B.MAP=kn;B.NODE_TYPE=je;B.PAIR=mc;B.SCALAR=Pa;B.SEQ=Sn;B.hasAnchor=uh;B.isAlias=ih;B.isCollection=vc;B.isDocument=ah;B.isMap=oh;B.isNode=lh;B.isPair=sh;B.isScalar=gc;B.isSeq=ch});var dr=w(Ca=>{"use strict";var D=P(),K=Symbol("break visit"),wc=Symbol("skip children"),Ne=Symbol("remove node");function En(t,e){let r=yc(e);D.isDocument(t)?jt(null,t.contents,r,Object.freeze([t]))===Ne&&(t.contents=null):jt(null,t,r,Object.freeze([]))}En.BREAK=K;En.SKIP=wc;En.REMOVE=Ne;function jt(t,e,r,n){let i=bc(t,e,r,n);if(D.isNode(i)||D.isPair(i))return Nc(t,n,i),jt(t,i,r,n);if(typeof i!="symbol"){if(D.isCollection(e)){n=Object.freeze(n.concat(e));for(let a=0;a<e.items.length;++a){let o=jt(a,e.items[a],r,n);if(typeof o=="number")a=o-1;else{if(o===K)return K;o===Ne&&(e.items.splice(a,1),a-=1)}}}else if(D.isPair(e)){n=Object.freeze(n.concat(e));let a=jt("key",e.key,r,n);if(a===K)return K;a===Ne&&(e.key=null);let o=jt("value",e.value,r,n);if(o===K)return K;o===Ne&&(e.value=null)}}return i}async function Pn(t,e){let r=yc(e);D.isDocument(t)?await Ot(null,t.contents,r,Object.freeze([t]))===Ne&&(t.contents=null):await Ot(null,t,r,Object.freeze([]))}Pn.BREAK=K;Pn.SKIP=wc;Pn.REMOVE=Ne;async function Ot(t,e,r,n){let i=await bc(t,e,r,n);if(D.isNode(i)||D.isPair(i))return Nc(t,n,i),Ot(t,i,r,n);if(typeof i!="symbol"){if(D.isCollection(e)){n=Object.freeze(n.concat(e));for(let a=0;a<e.items.length;++a){let o=await Ot(a,e.items[a],r,n);if(typeof o=="number")a=o-1;else{if(o===K)return K;o===Ne&&(e.items.splice(a,1),a-=1)}}}else if(D.isPair(e)){n=Object.freeze(n.concat(e));let a=await Ot("key",e.key,r,n);if(a===K)return K;a===Ne&&(e.key=null);let o=await Ot("value",e.value,r,n);if(o===K)return K;o===Ne&&(e.value=null)}}return i}function yc(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function bc(t,e,r,n){if(typeof r=="function")return r(t,e,n);if(D.isMap(e))return r.Map?.(t,e,n);if(D.isSeq(e))return r.Seq?.(t,e,n);if(D.isPair(e))return r.Pair?.(t,e,n);if(D.isScalar(e))return r.Scalar?.(t,e,n);if(D.isAlias(e))return r.Alias?.(t,e,n)}function Nc(t,e,r){let n=e[e.length-1];if(D.isCollection(n))n.items[t]=r;else if(D.isPair(n))t==="key"?n.key=r:n.value=r;else if(D.isDocument(n))n.contents=r;else{let i=D.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}Ca.visit=En;Ca.visitAsync=Pn});var xa=w(Sc=>{"use strict";var kc=P(),fh=dr(),dh={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},ph=t=>t.replace(/[!,[\]{}]/g,e=>dh[e]),pr=class t{constructor(e,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,r)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,r){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[a,o]=n;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=n;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${i}`,!0),!1}}tagName(e,r){if(e==="!")return"!";if(e[0]!=="!")return r(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||r(`The ${e} tag has no suffix`);let a=this.tags[n];if(a)try{return a+decodeURIComponent(i)}catch(o){return r(String(o)),null}return n==="!"?e:(r(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[r,n]of Object.entries(this.tags))if(e.startsWith(n))return r+ph(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(e&&n.length>0&&kc.isNode(e.contents)){let a={};fh.visit(e.contents,(o,s)=>{kc.isNode(s)&&s.tag&&(a[s.tag]=!0)}),i=Object.keys(a)}else i=[];for(let[a,o]of n)a==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
|
|
5
|
+
`)}};pr.defaultYaml={explicit:!1,version:"1.2"};pr.defaultTags={"!!":"tag:yaml.org,2002:"};Sc.Directives=pr});var Cn=w(hr=>{"use strict";var Ec=P(),hh=dr();function mh(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(r)}return!0}function Pc(t){let e=new Set;return hh.visit(t,{Value(r,n){n.anchor&&e.add(n.anchor)}}),e}function Cc(t,e){for(let r=1;;++r){let n=`${t}${r}`;if(!e.has(n))return n}}function gh(t,e){let r=[],n=new Map,i=null;return{onAnchor:a=>{r.push(a),i??(i=Pc(t));let o=Cc(e,i);return i.add(o),o},setAnchors:()=>{for(let a of r){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(Ec.isScalar(o.node)||Ec.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:n}}hr.anchorIsValid=mh;hr.anchorNames=Pc;hr.createNodeAnchors=gh;hr.findNewAnchor=Cc});var _a=w(xc=>{"use strict";function mr(t,e,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,a=n.length;i<a;++i){let o=n[i],s=mr(t,n,String(i),o);s===void 0?delete n[i]:s!==o&&(n[i]=s)}else if(n instanceof Map)for(let i of Array.from(n.keys())){let a=n.get(i),o=mr(t,n,i,a);o===void 0?n.delete(i):o!==a&&n.set(i,o)}else if(n instanceof Set)for(let i of Array.from(n)){let a=mr(t,n,i,i);a===void 0?n.delete(i):a!==i&&(n.delete(i),n.add(a))}else for(let[i,a]of Object.entries(n)){let o=mr(t,n,i,a);o===void 0?delete n[i]:o!==a&&(n[i]=o)}return t.call(e,r,n)}xc.applyReviver=mr});var ze=w(Rc=>{"use strict";var vh=P();function _c(t,e,r){if(Array.isArray(t))return t.map((n,i)=>_c(n,String(i),r));if(t&&typeof t.toJSON=="function"){if(!r||!vh.hasAnchor(t))return t.toJSON(e,r);let n={aliasCount:0,count:1,res:void 0};r.anchors.set(t,n),r.onCreate=a=>{n.res=a,delete r.onCreate};let i=t.toJSON(e,r);return r.onCreate&&r.onCreate(i),i}return typeof t=="bigint"&&!r?.keep?Number(t):t}Rc.toJS=_c});var xn=w(Tc=>{"use strict";var wh=_a(),Ac=P(),yh=ze(),Ra=class{constructor(e){Object.defineProperty(this,Ac.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:r,maxAliasCount:n,onAnchor:i,reviver:a}={}){if(!Ac.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},s=yh.toJS(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof a=="function"?wh.applyReviver(a,{"":s},"",s):s}};Tc.NodeBase=Ra});var gr=w(Ic=>{"use strict";var bh=Cn(),Nh=dr(),$t=P(),kh=xn(),Sh=ze(),Aa=class extends kh.NodeBase{constructor(e){super($t.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;r?.aliasResolveCache?n=r.aliasResolveCache:(n=[],Nh.visit(e,{Node:(a,o)=>{($t.isAlias(o)||$t.hasAnchor(o))&&n.push(o)}}),r&&(r.aliasResolveCache=n));let i;for(let a of n){if(a===this)break;a.anchor===this.source&&(i=a)}return i}toJSON(e,r){if(!r)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:a}=r,o=this.resolve(i,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=n.get(o);if(s||(Sh.toJS(o,null,r),s=n.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=_n(i,o,n)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(e,r,n){let i=`*${this.source}`;if(e){if(bh.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(e.implicitKey)return`${i} `}return i}};function _n(t,e,r){if($t.isAlias(e)){let n=e.resolve(t),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if($t.isCollection(e)){let n=0;for(let i of e.items){let a=_n(t,i,r);a>n&&(n=a)}return n}else if($t.isPair(e)){let n=_n(t,e.key,r),i=_n(t,e.value,r);return Math.max(n,i)}return 1}Ic.Alias=Aa});var j=w(Ta=>{"use strict";var Eh=P(),Ph=xn(),Ch=ze(),xh=t=>!t||typeof t!="function"&&typeof t!="object",Ge=class extends Ph.NodeBase{constructor(e){super(Eh.SCALAR),this.value=e}toJSON(e,r){return r?.keep?this.value:Ch.toJS(this.value,e,r)}toString(){return String(this.value)}};Ge.BLOCK_FOLDED="BLOCK_FOLDED";Ge.BLOCK_LITERAL="BLOCK_LITERAL";Ge.PLAIN="PLAIN";Ge.QUOTE_DOUBLE="QUOTE_DOUBLE";Ge.QUOTE_SINGLE="QUOTE_SINGLE";Ta.Scalar=Ge;Ta.isScalarValue=xh});var vr=w(Oc=>{"use strict";var _h=gr(),ft=P(),jc=j(),Rh="tag:yaml.org,2002:";function Ah(t,e,r){if(e){let n=r.filter(a=>a.tag===e),i=n.find(a=>!a.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return r.find(n=>n.identify?.(t)&&!n.format)}function Th(t,e,r){if(ft.isDocument(t)&&(t=t.contents),ft.isNode(t))return t;if(ft.isPair(t)){let f=r.schema[ft.MAP].createNode?.(r.schema,null,r);return f.items.push(t),f}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(n&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=i(t)),new _h.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=Rh+e.slice(2));let l=Ah(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let f=new jc.Scalar(t);return c&&(c.node=f),f}l=t instanceof Map?o[ft.MAP]:Symbol.iterator in Object(t)?o[ft.SEQ]:o[ft.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,t,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,t,r):new jc.Scalar(t);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}Oc.createNode=Th});var An=w(Rn=>{"use strict";var Ih=vr(),ke=P(),jh=xn();function Ia(t,e,r){let n=r;for(let i=e.length-1;i>=0;--i){let a=e[i];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=n,n=o}else n=new Map([[a,n]])}return Ih.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var $c=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,ja=class extends jh.NodeBase{constructor(e,r){super(e),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(e){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(r.schema=e),r.items=r.items.map(n=>ke.isNode(n)||ke.isPair(n)?n.clone(e):n),this.range&&(r.range=this.range.slice()),r}addIn(e,r){if($c(e))this.add(r);else{let[n,...i]=e,a=this.get(n,!0);if(ke.isCollection(a))a.addIn(i,r);else if(a===void 0&&this.schema)this.set(n,Ia(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){let[r,...n]=e;if(n.length===0)return this.delete(r);let i=this.get(r,!0);if(ke.isCollection(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(e,r){let[n,...i]=e,a=this.get(n,!0);return i.length===0?!r&&ke.isScalar(a)?a.value:a:ke.isCollection(a)?a.getIn(i,r):void 0}hasAllNullValues(e){return this.items.every(r=>{if(!ke.isPair(r))return!1;let n=r.value;return n==null||e&&ke.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[r,...n]=e;if(n.length===0)return this.has(r);let i=this.get(r,!0);return ke.isCollection(i)?i.hasIn(n):!1}setIn(e,r){let[n,...i]=e;if(i.length===0)this.set(n,r);else{let a=this.get(n,!0);if(ke.isCollection(a))a.setIn(i,r);else if(a===void 0&&this.schema)this.set(n,Ia(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};Rn.Collection=ja;Rn.collectionFromPath=Ia;Rn.isEmptyPath=$c});var wr=w(Tn=>{"use strict";var Oh=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Oa(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var $h=(t,e,r)=>t.endsWith(`
|
|
6
|
+
`)?Oa(r,e):r.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
|
|
9
|
-
`)r
|
|
8
|
+
`+Oa(r,e):(t.endsWith(" ")?"":" ")+r;Tn.indentComment=Oa;Tn.lineComment=$h;Tn.stringifyComment=Oh});var Dc=w(yr=>{"use strict";var Lh="flow",$a="block",In="quoted";function Dh(t,e,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return t;i<a&&(a=0);let c=Math.max(1+a,1+i-e.length);if(t.length<=c)return t;let l=[],u={},f=i-e.length;typeof n=="number"&&(n>i-Math.max(2,a)?l.push(0):f=i-n);let d,h,v=!1,p=-1,m=-1,y=-1;r===$a&&(p=Lc(t,p,e.length),p!==-1&&(f=p+c));for(let k;k=t[p+=1];){if(r===In&&k==="\\"){switch(m=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}y=p}if(k===`
|
|
9
|
+
`)r===$a&&(p=Lc(t,p,e.length)),f=p+e.length+c,d=void 0;else{if(k===" "&&h&&h!==" "&&h!==`
|
|
10
10
|
`&&h!==" "){let S=t[p+1];S&&S!==" "&&S!==`
|
|
11
|
-
`&&S!==" "&&(d=p)}if(p>=f)if(d)l.push(d),f=d+c,d=void 0;else if(r===
|
|
12
|
-
${e}${t.slice(0,E)}`:(r===
|
|
13
|
-
${e}${t.slice(S+1,E)}`)}return b}function
|
|
14
|
-
`);n=e,i=e+1,a=t[i]}return n}
|
|
15
|
-
`){if(a-o>n)return!0;if(o=a+1,i-o<=n)return!1}return!0}function
|
|
11
|
+
`&&S!==" "&&(d=p)}if(p>=f)if(d)l.push(d),f=d+c,d=void 0;else if(r===In){for(;h===" "||h===" ";)h=k,k=t[p+=1],v=!0;let S=p>y+1?p-2:m-1;if(u[S])return t;l.push(S),u[S]=!0,f=S+c,d=void 0}else v=!0}h=k}if(v&&s&&s(),l.length===0)return t;o&&o();let b=t.slice(0,l[0]);for(let k=0;k<l.length;++k){let S=l[k],E=l[k+1]||t.length;S===0?b=`
|
|
12
|
+
${e}${t.slice(0,E)}`:(r===In&&u[S]&&(b+=`${t[S]}\\`),b+=`
|
|
13
|
+
${e}${t.slice(S+1,E)}`)}return b}function Lc(t,e,r){let n=e,i=e+1,a=t[i];for(;a===" "||a===" ";)if(e<i+r)a=t[++e];else{do a=t[++e];while(a&&a!==`
|
|
14
|
+
`);n=e,i=e+1,a=t[i]}return n}yr.FOLD_BLOCK=$a;yr.FOLD_FLOW=Lh;yr.FOLD_QUOTED=In;yr.foldFlowLines=Dh});var Nr=w(Bc=>{"use strict";var ue=j(),Ue=Dc(),On=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),$n=t=>/^(%|---|\.\.\.)/m.test(t);function Bh(t,e,r){if(!e||e<0)return!1;let n=e-r,i=t.length;if(i<=n)return!1;for(let a=0,o=0;a<i;++a)if(t[a]===`
|
|
15
|
+
`){if(a-o>n)return!0;if(o=a+1,i-o<=n)return!1}return!0}function br(t,e){let r=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return r;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,a=e.indent||($n(t)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(n||r[c+2]==='"'||r.length<i)c+=1;else{for(o+=r.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,n?o:
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(t))return
|
|
20
|
-
${r}`)+"'";return e.implicitKey?n:
|
|
18
|
+
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,n?o:Ue.foldFlowLines(o,a,Ue.FOLD_QUOTED,On(e,!1))}function La(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(t))return br(t,e);let r=e.indent||($n(t)?" ":""),n="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${r}`)+"'";return e.implicitKey?n:Ue.foldFlowLines(n,r,Ue.FOLD_FLOW,On(e,!1))}function Lt(t,e){let{singleQuote:r}=e.options,n;if(r===!1)n=br;else{let i=t.includes('"'),a=t.includes("'");i&&!a?n=La:a&&!i?n=br:n=r?La:br}return n(t,e)}var Da;try{Da=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{Da=/\n+(?!\n|$)/g}function jn({comment:t,type:e,value:r},n,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(r))return Lt(r,n);let l=n.indent||(n.forceBlockIndent||$n(r)?" ":""),u=o==="literal"?!0:o==="folded"||e===ue.Scalar.BLOCK_FOLDED?!1:e===ue.Scalar.BLOCK_LITERAL?!0:!Bh(r,c,l.length);if(!r)return u?`|
|
|
24
24
|
`:`>
|
|
25
25
|
`;let f,d;for(d=r.length;d>0;--d){let E=r[d-1];if(E!==`
|
|
26
26
|
`&&E!==" "&&E!==" ")break}let h=r.substring(d),v=h.indexOf(`
|
|
27
27
|
`);v===-1?f="-":r===h||v!==h.length-1?(f="+",a&&a()):f="",h&&(r=r.slice(0,-h.length),h[h.length-1]===`
|
|
28
|
-
`&&(h=h.slice(0,-1)),h=h.replace(
|
|
28
|
+
`&&(h=h.slice(0,-1)),h=h.replace(Da,`$&${l}`));let p=!1,m,y=-1;for(m=0;m<r.length;++m){let E=r[m];if(E===" ")p=!0;else if(E===`
|
|
29
29
|
`)y=m;else break}let b=r.substring(0,y<m?y+1:m);b&&(r=r.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let S=(p?l?"2":"1":"")+f;if(t&&(S+=" "+s(t.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){let E=r.replace(/\n+/g,`
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,C=
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,C=On(n,!0);o!=="folded"&&e!==ue.Scalar.BLOCK_FOLDED&&(C.onOverflow=()=>{g=!0});let N=Ue.foldFlowLines(`${b}${E}${h}`,l,Ue.FOLD_BLOCK,C);if(!g)return`>${S}
|
|
31
31
|
${l}${N}`}return r=r.replace(/\n+/g,`$&${l}`),`|${S}
|
|
32
|
-
${l}${b}${r}${h}`}function
|
|
33
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
34
|
-
`)
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),{compat:h,tags:v}=e.doc.schema;if(v.some(d)||h?.some(d))return
|
|
37
|
-
${e.indent}${s}`:s}
|
|
38
|
-
${s}:`):(m=`${m}:`,d&&(m+=
|
|
32
|
+
${l}${b}${r}${h}`}function Mh(t,e,r,n){let{type:i,value:a}=t,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=e;if(s&&a.includes(`
|
|
33
|
+
`)||u&&/[[\]{},]/.test(a))return Lt(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
+
`)?Lt(a,e):jn(t,e,r,n);if(!s&&!u&&i!==ue.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return jn(t,e,r,n);if($n(a)){if(c==="")return e.forceBlockIndent=!0,jn(t,e,r,n);if(s&&c===l)return Lt(a,e)}let f=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),{compat:h,tags:v}=e.doc.schema;if(v.some(d)||h?.some(d))return Lt(a,e)}return s?f:Ue.foldFlowLines(f,c,Ue.FOLD_FLOW,On(e,!1))}function qh(t,e,r,n){let{implicitKey:i,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==ue.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=ue.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case ue.Scalar.BLOCK_FOLDED:case ue.Scalar.BLOCK_LITERAL:return i||a?Lt(o.value,e):jn(o,e,r,n);case ue.Scalar.QUOTE_DOUBLE:return br(o.value,e);case ue.Scalar.QUOTE_SINGLE:return La(o.value,e);case ue.Scalar.PLAIN:return Mh(o,e,r,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:f}=e.options,d=i&&u||f;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Bc.stringifyString=qh});var kr=w(Ba=>{"use strict";var Wh=Cn(),Ke=P(),Fh=wr(),Hh=Nr();function Vh(t,e){let r=Object.assign({blockQuote:!0,commentString:Fh.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},t.schema.toStringOptions,e),n;switch(r.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:t,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:n,options:r}}function zh(t,e){if(e.tag){let i=t.filter(a=>a.tag===e.tag);if(i.length>0)return i.find(a=>a.format===e.format)??i[0]}let r,n;if(Ke.isScalar(e)){n=e.value;let i=t.filter(a=>a.identify?.(n));if(i.length>1){let a=i.filter(o=>o.test);a.length>0&&(i=a)}r=i.find(a=>a.format===e.format)??i.find(a=>!a.format)}else n=e,r=t.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!r){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return r}function Gh(t,e,{anchors:r,doc:n}){if(!n.directives)return"";let i=[],a=(Ke.isScalar(t)||Ke.isCollection(t))&&t.anchor;a&&Wh.anchorIsValid(a)&&(r.add(a),i.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Uh(t,e,r,n){if(Ke.isPair(t))return t.toString(e,r,n);if(Ke.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let i,a=Ke.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>i=c});i??(i=zh(e.doc.schema.tags,a));let o=Gh(a,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof i.stringify=="function"?i.stringify(a,e,r,n):Ke.isScalar(a)?Hh.stringifyString(a,e,r,n):a.toString(e,r,n);return o?Ke.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${e.indent}${s}`:s}Ba.createStringifyContext=Vh;Ba.stringify=Uh});var Fc=w(Wc=>{"use strict";var Oe=P(),Mc=j(),qc=kr(),Sr=wr();function Kh({key:t,value:e},r,n,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:f}}=r,d=Oe.isNode(t)&&t.comment||null;if(f){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Oe.isCollection(t)||!Oe.isNode(t)&&typeof t=="object"){let C="With simple keys, collection cannot be used as a key value";throw new Error(C)}}let h=!f&&(!t||d&&e==null&&!r.inFlow||Oe.isCollection(t)||(Oe.isScalar(t)?t.type===Mc.Scalar.BLOCK_FOLDED||t.type===Mc.Scalar.BLOCK_LITERAL:typeof t=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!h&&(f||!a),indent:s+c});let v=!1,p=!1,m=qc.stringify(t,r,()=>v=!0,()=>p=!0);if(!h&&!r.inFlow&&m.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(r.inFlow){if(a||e==null)return v&&n&&n(),m===""?"?":h?`? ${m}`:m}else if(a&&!f||e==null&&h)return m=`? ${m}`,d&&!v?m+=Sr.lineComment(m,r.indent,l(d)):p&&i&&i(),m;v&&(d=null),h?(d&&(m+=Sr.lineComment(m,r.indent,l(d))),m=`? ${m}
|
|
38
|
+
${s}:`):(m=`${m}:`,d&&(m+=Sr.lineComment(m,r.indent,l(d))));let y,b,k;Oe.isNode(e)?(y=!!e.spaceBefore,b=e.commentBefore,k=e.comment):(y=!1,b=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),r.implicitKey=!1,!h&&!d&&Oe.isScalar(e)&&(r.indentAtStart=m.length+1),p=!1,!u&&c.length>=2&&!r.inFlow&&!h&&Oe.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(r.indent=r.indent.substring(2));let S=!1,E=qc.stringify(e,r,()=>S=!0,()=>p=!0),g=" ";if(d||y||b){if(g=y?`
|
|
39
39
|
`:"",b){let C=l(b);g+=`
|
|
40
|
-
${
|
|
40
|
+
${Sr.indentComment(C,r.indent)}`}E===""&&!r.inFlow?g===`
|
|
41
41
|
`&&k&&(g=`
|
|
42
42
|
|
|
43
43
|
`):g+=`
|
|
44
|
-
${r.indent}`}else if(!h
|
|
45
|
-
`),
|
|
44
|
+
${r.indent}`}else if(!h&&Oe.isCollection(e)){let C=E[0],N=E.indexOf(`
|
|
45
|
+
`),R=N!==-1,ee=r.inFlow??e.flow??e.items.length===0;if(R||!ee){let It=!1;if(R&&(C==="&"||C==="!")){let $=E.indexOf(" ");C==="&"&&$!==-1&&$<N&&E[$+1]==="!"&&($=E.indexOf(" ",$+1)),($===-1||N<$)&&(It=!0)}It||(g=`
|
|
46
46
|
${r.indent}`)}}else(E===""||E[0]===`
|
|
47
|
-
`)&&(g="");return m+=g+E,r.inFlow?S&&n&&n():k&&!S?m+=
|
|
47
|
+
`)&&(g="");return m+=g+E,r.inFlow?S&&n&&n():k&&!S?m+=Sr.lineComment(m,r.indent,l(k)):p&&i&&i(),m}Wc.stringifyPair=Kh});var qa=w(Ma=>{"use strict";var Hc=Nn("process");function Jh(t,...e){t==="debug"&&console.log(...e)}function Yh(t,e){(t==="debug"||t==="warn")&&(typeof Hc.emitWarning=="function"?Hc.emitWarning(e):console.warn(e))}Ma.debug=Jh;Ma.warn=Yh});var qn=w(Mn=>{"use strict";var Bn=P(),Vc=j(),Ln="<<",Dn={identify:t=>t===Ln||typeof t=="symbol"&&t.description===Ln,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Vc.Scalar(Symbol(Ln)),{addToJSMap:zc}),stringify:()=>Ln},Xh=(t,e)=>(Dn.identify(e)||Bn.isScalar(e)&&(!e.type||e.type===Vc.Scalar.PLAIN)&&Dn.identify(e.value))&&t?.doc.schema.tags.some(r=>r.tag===Dn.tag&&r.default);function zc(t,e,r){let n=Gc(t,r);if(Bn.isSeq(n))for(let i of n.items)Wa(t,e,i);else if(Array.isArray(n))for(let i of n)Wa(t,e,i);else Wa(t,e,n)}function Wa(t,e,r){let n=Gc(t,r);if(!Bn.isMap(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,t,Map);for(let[a,o]of i)e instanceof Map?e.has(a)||e.set(a,o):e instanceof Set?e.add(a):Object.prototype.hasOwnProperty.call(e,a)||Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Gc(t,e){return t&&Bn.isAlias(e)?e.resolve(t.doc,t):e}Mn.addMergeToJSMap=zc;Mn.isMergeKey=Xh;Mn.merge=Dn});var Ha=w(Jc=>{"use strict";var Qh=qa(),Uc=qn(),Zh=kr(),Kc=P(),Fa=ze();function em(t,e,{key:r,value:n}){if(Kc.isNode(r)&&r.addToJSMap)r.addToJSMap(t,e,n);else if(Uc.isMergeKey(t,r))Uc.addMergeToJSMap(t,e,n);else{let i=Fa.toJS(r,"",t);if(e instanceof Map)e.set(i,Fa.toJS(n,i,t));else if(e instanceof Set)e.add(i);else{let a=tm(r,i,t),o=Fa.toJS(n,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function tm(t,e,r){if(e===null)return"";if(typeof e!="object")return String(e);if(Kc.isNode(t)&&r?.doc){let n=Zh.createStringifyContext(r.doc,{});n.anchors=new Set;for(let a of r.anchors.keys())n.anchors.add(a.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=t.toString(n);if(!r.mapKeyWarned){let a=JSON.stringify(i);a.length>40&&(a=a.substring(0,36)+'..."'),Qh.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return i}return JSON.stringify(e)}Jc.addPairToJSMap=em});var Je=w(Va=>{"use strict";var Yc=vr(),rm=Fc(),nm=Ha(),Wn=P();function im(t,e,r){let n=Yc.createNode(t,void 0,r),i=Yc.createNode(e,void 0,r);return new Fn(n,i)}var Fn=class t{constructor(e,r=null){Object.defineProperty(this,Wn.NODE_TYPE,{value:Wn.PAIR}),this.key=e,this.value=r}clone(e){let{key:r,value:n}=this;return Wn.isNode(r)&&(r=r.clone(e)),Wn.isNode(n)&&(n=n.clone(e)),new t(r,n)}toJSON(e,r){let n=r?.mapAsMap?new Map:{};return nm.addPairToJSMap(r,n,this)}toString(e,r,n){return e?.doc?rm.stringifyPair(this,e,r,n):JSON.stringify(this)}};Va.Pair=Fn;Va.createPair=im});var za=w(Qc=>{"use strict";var dt=P(),Xc=kr(),Hn=wr();function am(t,e,r){return(e.inFlow??t.flow?sm:om)(t,e,r)}function om({comment:t,items:e},r,{blockItemPrefix:n,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),f=!1,d=[];for(let v=0;v<e.length;++v){let p=e[v],m=null;if(dt.isNode(p))!f&&p.spaceBefore&&d.push(""),Vn(r,d,p.commentBefore,f),p.comment&&(m=p.comment);else if(dt.isPair(p)){let b=dt.isNode(p.key)?p.key:null;b&&(!f&&b.spaceBefore&&d.push(""),Vn(r,d,b.commentBefore,f))}f=!1;let y=Xc.stringify(p,u,()=>m=null,()=>f=!0);m&&(y+=Hn.lineComment(y,a,l(m))),f&&m&&(f=!1),d.push(n+y)}let h;if(d.length===0)h=i.start+i.end;else{h=d[0];for(let v=1;v<d.length;++v){let p=d[v];h+=p?`
|
|
48
48
|
${c}${p}`:`
|
|
49
49
|
`}}return t?(h+=`
|
|
50
|
-
`+
|
|
51
|
-
`)),v<t.length-1?y+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=f.reduce((b,k)=>b+k.length+2,2)+(y.length+2)>e.options.lineWidth)),l&&(y+=",")),m&&(y+=
|
|
50
|
+
`+Hn.indentComment(l(t),c),s&&s()):f&&o&&o(),h}function sm({items:t},e,{flowChars:r,itemIndent:n}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=e;n+=a;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,u=0,f=[];for(let v=0;v<t.length;++v){let p=t[v],m=null;if(dt.isNode(p))p.spaceBefore&&f.push(""),Vn(e,f,p.commentBefore,!1),p.comment&&(m=p.comment);else if(dt.isPair(p)){let b=dt.isNode(p.key)?p.key:null;b&&(b.spaceBefore&&f.push(""),Vn(e,f,b.commentBefore,!1),b.comment&&(l=!0));let k=dt.isNode(p.value)?p.value:null;k?(k.comment&&(m=k.comment),k.commentBefore&&(l=!0)):p.value==null&&b?.comment&&(m=b.comment)}m&&(l=!0);let y=Xc.stringify(p,c,()=>m=null);l||(l=f.length>u||y.includes(`
|
|
51
|
+
`)),v<t.length-1?y+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=f.reduce((b,k)=>b+k.length+2,2)+(y.length+2)>e.options.lineWidth)),l&&(y+=",")),m&&(y+=Hn.lineComment(y,n,s(m))),f.push(y),u=f.length}let{start:d,end:h}=r;if(f.length===0)return d+h;if(!l){let v=f.reduce((p,m)=>p+m.length+2,2);l=e.options.lineWidth>0&&v>e.options.lineWidth}if(l){let v=d;for(let p of f)v+=p?`
|
|
52
52
|
${a}${i}${p}`:`
|
|
53
53
|
`;return`${v}
|
|
54
|
-
${i}${h}`}else return`${d}${o}${f.join(" ")}${o}${h}`}function
|
|
55
|
-
`:" ")}return
|
|
54
|
+
${i}${h}`}else return`${d}${o}${f.join(" ")}${o}${h}`}function Vn({indent:t,options:{commentString:e}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let a=Hn.indentComment(e(n),t);r.push(a.trimStart())}}Qc.stringifyCollection=am});var Xe=w(Ua=>{"use strict";var cm=za(),lm=Ha(),um=An(),Ye=P(),zn=Je(),fm=j();function Er(t,e){let r=Ye.isScalar(e)?e.value:e;for(let n of t)if(Ye.isPair(n)&&(n.key===e||n.key===r||Ye.isScalar(n.key)&&n.key.value===r))return n}var Ga=class extends um.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ye.MAP,e),this.items=[]}static from(e,r,n){let{keepUndefined:i,replacer:a}=n,o=new this(e),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||i)&&o.items.push(zn.createPair(c,l,n))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,r){let n;Ye.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new zn.Pair(e,e?.value):n=new zn.Pair(e.key,e.value);let i=Er(this.items,n.key),a=this.schema?.sortMapEntries;if(i){if(!r)throw new Error(`Key ${n.key} already set`);Ye.isScalar(i.value)&&fm.isScalarValue(n.value)?i.value.value=n.value:i.value=n.value}else if(a){let o=this.items.findIndex(s=>a(n,s)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let r=Er(this.items,e);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(e,r){let i=Er(this.items,e)?.value;return(!r&&Ye.isScalar(i)?i.value:i)??void 0}has(e){return!!Er(this.items,e)}set(e,r){this.add(new zn.Pair(e,r),!0)}toJSON(e,r,n){let i=n?new n:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(i);for(let a of this.items)lm.addPairToJSMap(r,i,a);return i}toString(e,r,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!Ye.isPair(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),cm.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:r})}};Ua.YAMLMap=Ga;Ua.findPair=Er});var Dt=w(el=>{"use strict";var dm=P(),Zc=Xe(),pm={collection:"map",default:!0,nodeClass:Zc.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return dm.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,r)=>Zc.YAMLMap.from(t,e,r)};el.map=pm});var Qe=w(tl=>{"use strict";var hm=vr(),mm=za(),gm=An(),Un=P(),vm=j(),wm=ze(),Ka=class extends gm.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Un.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let r=Gn(e);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(e,r){let n=Gn(e);if(typeof n!="number")return;let i=this.items[n];return!r&&Un.isScalar(i)?i.value:i}has(e){let r=Gn(e);return typeof r=="number"&&r<this.items.length}set(e,r){let n=Gn(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let i=this.items[n];Un.isScalar(i)&&vm.isScalarValue(r)?i.value=r:this.items[n]=r}toJSON(e,r){let n=[];r?.onCreate&&r.onCreate(n);let i=0;for(let a of this.items)n.push(wm.toJS(a,String(i++),r));return n}toString(e,r,n){return e?mm.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:r}):JSON.stringify(this)}static from(e,r,n){let{replacer:i}=n,a=new this(e);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof i=="function"){let c=r instanceof Set?s:String(o++);s=i.call(r,c,s)}a.items.push(hm.createNode(s,void 0,n))}}return a}};function Gn(t){let e=Un.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}tl.YAMLSeq=Ka});var Bt=w(nl=>{"use strict";var ym=P(),rl=Qe(),bm={collection:"seq",default:!0,nodeClass:rl.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return ym.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,r)=>rl.YAMLSeq.from(t,e,r)};nl.seq=bm});var Pr=w(il=>{"use strict";var Nm=Nr(),km={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,r,n){return e=Object.assign({actualString:!0},e),Nm.stringifyString(t,e,r,n)}};il.string=km});var Kn=w(sl=>{"use strict";var al=j(),ol={identify:t=>t==null,createNode:()=>new al.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new al.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&ol.test.test(t)?t:e.options.nullStr};sl.nullTag=ol});var Ja=w(ll=>{"use strict";var Sm=j(),cl={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Sm.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},r){if(t&&cl.test.test(t)){let n=t[0]==="t"||t[0]==="T";if(e===n)return t}return e?r.options.trueStr:r.options.falseStr}};ll.boolTag=cl});var Mt=w(ul=>{"use strict";function Em({format:t,minFractionDigits:e,tag:r,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let a=Object.is(n,-0)?"-0":JSON.stringify(n);if(!t&&e&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=e-(a.length-o-1);for(;s-- >0;)a+="0"}return a}ul.stringifyNumber=Em});var Xa=w(Jn=>{"use strict";var Pm=j(),Ya=Mt(),Cm={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ya.stringifyNumber},xm={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Ya.stringifyNumber(t)}},_m={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new Pm.Scalar(parseFloat(t)),r=t.indexOf(".");return r!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-r-1),e},stringify:Ya.stringifyNumber};Jn.float=_m;Jn.floatExp=xm;Jn.floatNaN=Cm});var Za=w(Xn=>{"use strict";var fl=Mt(),Yn=t=>typeof t=="bigint"||Number.isInteger(t),Qa=(t,e,r,{intAsBigInt:n})=>n?BigInt(t):parseInt(t.substring(e),r);function dl(t,e,r){let{value:n}=t;return Yn(n)&&n>=0?r+n.toString(e):fl.stringifyNumber(t)}var Rm={identify:t=>Yn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,r)=>Qa(t,2,8,r),stringify:t=>dl(t,8,"0o")},Am={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,r)=>Qa(t,0,10,r),stringify:fl.stringifyNumber},Tm={identify:t=>Yn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,r)=>Qa(t,2,16,r),stringify:t=>dl(t,16,"0x")};Xn.int=Am;Xn.intHex=Tm;Xn.intOct=Rm});var hl=w(pl=>{"use strict";var Im=Dt(),jm=Kn(),Om=Bt(),$m=Pr(),Lm=Ja(),eo=Xa(),to=Za(),Dm=[Im.map,Om.seq,$m.string,jm.nullTag,Lm.boolTag,to.intOct,to.int,to.intHex,eo.floatNaN,eo.floatExp,eo.float];pl.schema=Dm});var vl=w(gl=>{"use strict";var Bm=j(),Mm=Dt(),qm=Bt();function ml(t){return typeof t=="bigint"||Number.isInteger(t)}var Qn=({value:t})=>JSON.stringify(t),Wm=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Qn},{identify:t=>t==null,createNode:()=>new Bm.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Qn},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Qn},{identify:ml,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:r})=>r?BigInt(t):parseInt(t,10),stringify:({value:t})=>ml(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Qn}],Fm={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Hm=[Mm.map,qm.seq].concat(Wm,Fm);gl.schema=Hm});var no=w(wl=>{"use strict";var Cr=Nn("buffer"),ro=j(),Vm=Nr(),zm={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Cr.Buffer=="function")return Cr.Buffer.from(t,"base64");if(typeof atob=="function"){let r=atob(t.replace(/[\n\r]/g,"")),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:r},n,i,a){if(!r)return"";let o=r,s;if(typeof Cr.Buffer=="function")s=o instanceof Cr.Buffer?o.toString("base64"):Cr.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(e??(e=ro.Scalar.BLOCK_LITERAL),e!==ro.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let f=0,d=0;f<l;++f,d+=c)u[f]=s.substr(d,c);s=u.join(e===ro.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return Vm.stringifyString({comment:t,type:e,value:s},n,i,a)}};wl.binary=zm});var ti=w(ei=>{"use strict";var Zn=P(),io=Je(),Gm=j(),Um=Qe();function yl(t,e){if(Zn.isSeq(t))for(let r=0;r<t.items.length;++r){let n=t.items[r];if(!Zn.isPair(n)){if(Zn.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let i=n.items[0]||new io.Pair(new Gm.Scalar(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
|
|
56
56
|
${i.key.commentBefore}`:n.commentBefore),n.comment){let a=i.value??i.key;a.comment=a.comment?`${n.comment}
|
|
57
|
-
${a.comment}`:n.comment}n=i}t.items[r]=Qn.isPair(n)?n:new ao.Pair(n)}}else e("Expected a sequence for this tag");return t}function yl(t,e,r){let{replacer:n}=r,i=new Fm.YAMLSeq(t);i.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;i.items.push(ao.createPair(s,c,r))}return i}var Hm={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:wl,createNode:yl};Zn.createPairs=yl;Zn.pairs=Hm;Zn.resolvePairs=wl});var co=w(so=>{"use strict";var bl=P(),oo=Ge(),Cr=Qe(),Vm=Ze(),Nl=ei(),dt=class t extends Vm.YAMLSeq{constructor(){super(),this.add=Cr.YAMLMap.prototype.add.bind(this),this.delete=Cr.YAMLMap.prototype.delete.bind(this),this.get=Cr.YAMLMap.prototype.get.bind(this),this.has=Cr.YAMLMap.prototype.has.bind(this),this.set=Cr.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,r){if(!r)return super.toJSON(e);let n=new Map;r?.onCreate&&r.onCreate(n);for(let i of this.items){let a,o;if(bl.isPair(i)?(a=oo.toJS(i.key,"",r),o=oo.toJS(i.value,a,r)):a=oo.toJS(i,"",r),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(e,r,n){let i=Nl.createPairs(e,r,n),a=new this;return a.items=i.items,a}};dt.tag="tag:yaml.org,2002:omap";var zm={collection:"seq",identify:t=>t instanceof Map,nodeClass:dt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let r=Nl.resolvePairs(t,e),n=[];for(let{key:i}of r.items)bl.isScalar(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new dt,r)},createNode:(t,e,r)=>dt.from(t,e,r)};so.YAMLOMap=dt;so.omap=zm});var Cl=w(lo=>{"use strict";var kl=j();function Sl({value:t,source:e},r){return e&&(t?El:Pl).test.test(e)?e:t?r.options.trueStr:r.options.falseStr}var El={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new kl.Scalar(!0),stringify:Sl},Pl={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new kl.Scalar(!1),stringify:Sl};lo.falseTag=Pl;lo.trueTag=El});var xl=w(ti=>{"use strict";var Gm=j(),uo=Bt(),Km={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:uo.stringifyNumber},Jm={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():uo.stringifyNumber(t)}},Um={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Gm.Scalar(parseFloat(t.replace(/_/g,""))),r=t.indexOf(".");if(r!==-1){let n=t.substring(r+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:uo.stringifyNumber};ti.float=Um;ti.floatExp=Jm;ti.floatNaN=Km});var Rl=w(_r=>{"use strict";var _l=Bt(),xr=t=>typeof t=="bigint"||Number.isInteger(t);function ri(t,e,r,{intAsBigInt:n}){let i=t[0];if((i==="-"||i==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),n){switch(r){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return i==="-"?BigInt(-1)*o:o}let a=parseInt(t,r);return i==="-"?-1*a:a}function fo(t,e,r){let{value:n}=t;if(xr(n)){let i=n.toString(e);return n<0?"-"+r+i.substr(1):r+i}return _l.stringifyNumber(t)}var Ym={identify:xr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,r)=>ri(t,2,2,r),stringify:t=>fo(t,2,"0b")},Xm={identify:xr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,r)=>ri(t,1,8,r),stringify:t=>fo(t,8,"0")},Qm={identify:xr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,r)=>ri(t,0,10,r),stringify:_l.stringifyNumber},Zm={identify:xr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,r)=>ri(t,2,16,r),stringify:t=>fo(t,16,"0x")};_r.int=Qm;_r.intBin=Ym;_r.intHex=Zm;_r.intOct=Xm});var ho=w(po=>{"use strict";var ai=P(),ni=Ye(),ii=Qe(),pt=class t extends ii.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let r;ai.isPair(e)?r=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?r=new ni.Pair(e.key,null):r=new ni.Pair(e,null),ii.findPair(this.items,r.key)||this.items.push(r)}get(e,r){let n=ii.findPair(this.items,e);return!r&&ai.isPair(n)?ai.isScalar(n.key)?n.key.value:n.key:n}set(e,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let n=ii.findPair(this.items,e);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new ni.Pair(e))}toJSON(e,r){return super.toJSON(e,r,Set)}toString(e,r,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(e,r,n){let{replacer:i}=n,a=new this(e);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof i=="function"&&(o=i.call(r,o,o)),a.items.push(ni.createPair(o,null,n));return a}};pt.tag="tag:yaml.org,2002:set";var eg={collection:"map",identify:t=>t instanceof Set,nodeClass:pt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,r)=>pt.from(t,e,r),resolve(t,e){if(ai.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new pt,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};po.YAMLSet=pt;po.set=eg});var go=w(oi=>{"use strict";var tg=Bt();function mo(t,e){let r=t[0],n=r==="-"||r==="+"?t.substring(1):t,i=o=>e?BigInt(o):Number(o),a=n.replace(/_/g,"").split(":").reduce((o,s)=>o*i(60)+i(s),i(0));return r==="-"?i(-1)*a:a}function Al(t){let{value:e}=t,r=o=>o;if(typeof e=="bigint")r=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return tg.stringifyNumber(t);let n="";e<0&&(n="-",e*=r(-1));let i=r(60),a=[e%i];return e<60?a.unshift(0):(e=(e-a[0])/i,a.unshift(e%i),e>=60&&(e=(e-a[0])/i,a.unshift(e))),n+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var rg={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:r})=>mo(t,r),stringify:Al},ng={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>mo(t,!1),stringify:Al},Tl={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Tl.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,n,i,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(r,n-1,i,a||0,o||0,s||0,c),u=e[8];if(u&&u!=="Z"){let f=mo(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};oi.floatTime=ng;oi.intTime=rg;oi.timestamp=Tl});var Ol=w(jl=>{"use strict";var ig=Lt(),ag=Kn(),og=Dt(),sg=Er(),cg=io(),Il=Cl(),vo=xl(),si=Rl(),lg=Mn(),ug=co(),fg=ei(),dg=ho(),wo=go(),pg=[ig.map,og.seq,sg.string,ag.nullTag,Il.trueTag,Il.falseTag,si.intBin,si.intOct,si.int,si.intHex,vo.floatNaN,vo.floatExp,vo.float,cg.binary,lg.merge,ug.omap,fg.pairs,dg.set,wo.intTime,wo.floatTime,wo.timestamp];jl.schema=pg});var Vl=w(No=>{"use strict";var Bl=Lt(),hg=Kn(),Ml=Dt(),mg=Er(),gg=Ya(),yo=Qa(),bo=eo(),vg=pl(),wg=gl(),Wl=io(),Rr=Mn(),ql=co(),Fl=ei(),$l=Ol(),Hl=ho(),ci=go(),Ll=new Map([["core",vg.schema],["failsafe",[Bl.map,Ml.seq,mg.string]],["json",wg.schema],["yaml11",$l.schema],["yaml-1.1",$l.schema]]),Dl={binary:Wl.binary,bool:gg.boolTag,float:yo.float,floatExp:yo.floatExp,floatNaN:yo.floatNaN,floatTime:ci.floatTime,int:bo.int,intHex:bo.intHex,intOct:bo.intOct,intTime:ci.intTime,map:Bl.map,merge:Rr.merge,null:hg.nullTag,omap:ql.omap,pairs:Fl.pairs,seq:Ml.seq,set:Hl.set,timestamp:ci.timestamp},yg={"tag:yaml.org,2002:binary":Wl.binary,"tag:yaml.org,2002:merge":Rr.merge,"tag:yaml.org,2002:omap":ql.omap,"tag:yaml.org,2002:pairs":Fl.pairs,"tag:yaml.org,2002:set":Hl.set,"tag:yaml.org,2002:timestamp":ci.timestamp};function bg(t,e,r){let n=Ll.get(e);if(n&&!t)return r&&!n.includes(Rr.merge)?n.concat(Rr.merge):n.slice();let i=n;if(!i)if(Array.isArray(t))i=[];else{let a=Array.from(Ll.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)i=i.concat(a);else typeof t=="function"&&(i=t(i.slice()));return r&&(i=i.concat(Rr.merge)),i.reduce((a,o)=>{let s=typeof o=="string"?Dl[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Dl).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},[])}No.coreKnownTags=yg;No.getTags=bg});var Eo=w(zl=>{"use strict";var ko=P(),Ng=Lt(),kg=Dt(),Sg=Er(),li=Vl(),Eg=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,So=class t{constructor({compat:e,customTags:r,merge:n,resolveKnownTags:i,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?li.getTags(e,"compat"):e?li.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=i?li.coreKnownTags:{},this.tags=li.getTags(r,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,ko.MAP,{value:Ng.map}),Object.defineProperty(this,ko.SCALAR,{value:Sg.string}),Object.defineProperty(this,ko.SEQ,{value:kg.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Eg:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};zl.Schema=So});var Kl=w(Gl=>{"use strict";var Pg=P(),Po=Nr(),Ar=vr();function Cg(t,e){let r=[],n=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(r.push(c),n=!0):t.directives.docStart&&(n=!0)}n&&r.push("---");let i=Po.createStringifyContext(t,e),{commentString:a}=i.options;if(t.commentBefore){r.length!==1&&r.unshift("");let c=a(t.commentBefore);r.unshift(Ar.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(Pg.isNode(t.contents)){if(t.contents.spaceBefore&&n&&r.push(""),t.contents.commentBefore){let u=a(t.contents.commentBefore);r.push(Ar.indentComment(u,""))}i.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Po.stringify(t.contents,i,()=>s=null,c);s&&(l+=Ar.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Po.stringify(t.contents,i));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
|
|
58
|
-
`)?(r.push("..."),r.push(
|
|
57
|
+
${a.comment}`:n.comment}n=i}t.items[r]=Zn.isPair(n)?n:new io.Pair(n)}}else e("Expected a sequence for this tag");return t}function bl(t,e,r){let{replacer:n}=r,i=new Um.YAMLSeq(t);i.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;i.items.push(io.createPair(s,c,r))}return i}var Km={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:yl,createNode:bl};ei.createPairs=bl;ei.pairs=Km;ei.resolvePairs=yl});var so=w(oo=>{"use strict";var Nl=P(),ao=ze(),xr=Xe(),Jm=Qe(),kl=ti(),pt=class t extends Jm.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=t.tag}toJSON(e,r){if(!r)return super.toJSON(e);let n=new Map;r?.onCreate&&r.onCreate(n);for(let i of this.items){let a,o;if(Nl.isPair(i)?(a=ao.toJS(i.key,"",r),o=ao.toJS(i.value,a,r)):a=ao.toJS(i,"",r),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(e,r,n){let i=kl.createPairs(e,r,n),a=new this;return a.items=i.items,a}};pt.tag="tag:yaml.org,2002:omap";var Ym={collection:"seq",identify:t=>t instanceof Map,nodeClass:pt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let r=kl.resolvePairs(t,e),n=[];for(let{key:i}of r.items)Nl.isScalar(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new pt,r)},createNode:(t,e,r)=>pt.from(t,e,r)};oo.YAMLOMap=pt;oo.omap=Ym});var xl=w(co=>{"use strict";var Sl=j();function El({value:t,source:e},r){return e&&(t?Pl:Cl).test.test(e)?e:t?r.options.trueStr:r.options.falseStr}var Pl={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Sl.Scalar(!0),stringify:El},Cl={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Sl.Scalar(!1),stringify:El};co.falseTag=Cl;co.trueTag=Pl});var _l=w(ri=>{"use strict";var Xm=j(),lo=Mt(),Qm={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:lo.stringifyNumber},Zm={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():lo.stringifyNumber(t)}},eg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Xm.Scalar(parseFloat(t.replace(/_/g,""))),r=t.indexOf(".");if(r!==-1){let n=t.substring(r+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:lo.stringifyNumber};ri.float=eg;ri.floatExp=Zm;ri.floatNaN=Qm});var Al=w(Rr=>{"use strict";var Rl=Mt(),_r=t=>typeof t=="bigint"||Number.isInteger(t);function ni(t,e,r,{intAsBigInt:n}){let i=t[0];if((i==="-"||i==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),n){switch(r){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return i==="-"?BigInt(-1)*o:o}let a=parseInt(t,r);return i==="-"?-1*a:a}function uo(t,e,r){let{value:n}=t;if(_r(n)){let i=n.toString(e);return n<0?"-"+r+i.substr(1):r+i}return Rl.stringifyNumber(t)}var tg={identify:_r,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,r)=>ni(t,2,2,r),stringify:t=>uo(t,2,"0b")},rg={identify:_r,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,r)=>ni(t,1,8,r),stringify:t=>uo(t,8,"0")},ng={identify:_r,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,r)=>ni(t,0,10,r),stringify:Rl.stringifyNumber},ig={identify:_r,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,r)=>ni(t,2,16,r),stringify:t=>uo(t,16,"0x")};Rr.int=ng;Rr.intBin=tg;Rr.intHex=ig;Rr.intOct=rg});var po=w(fo=>{"use strict";var oi=P(),ii=Je(),ai=Xe(),ht=class t extends ai.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let r;oi.isPair(e)?r=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?r=new ii.Pair(e.key,null):r=new ii.Pair(e,null),ai.findPair(this.items,r.key)||this.items.push(r)}get(e,r){let n=ai.findPair(this.items,e);return!r&&oi.isPair(n)?oi.isScalar(n.key)?n.key.value:n.key:n}set(e,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let n=ai.findPair(this.items,e);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new ii.Pair(e))}toJSON(e,r){return super.toJSON(e,r,Set)}toString(e,r,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(e,r,n){let{replacer:i}=n,a=new this(e);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof i=="function"&&(o=i.call(r,o,o)),a.items.push(ii.createPair(o,null,n));return a}};ht.tag="tag:yaml.org,2002:set";var ag={collection:"map",identify:t=>t instanceof Set,nodeClass:ht,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,r)=>ht.from(t,e,r),resolve(t,e){if(oi.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new ht,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};fo.YAMLSet=ht;fo.set=ag});var mo=w(si=>{"use strict";var og=Mt();function ho(t,e){let r=t[0],n=r==="-"||r==="+"?t.substring(1):t,i=o=>e?BigInt(o):Number(o),a=n.replace(/_/g,"").split(":").reduce((o,s)=>o*i(60)+i(s),i(0));return r==="-"?i(-1)*a:a}function Tl(t){let{value:e}=t,r=o=>o;if(typeof e=="bigint")r=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return og.stringifyNumber(t);let n="";e<0&&(n="-",e*=r(-1));let i=r(60),a=[e%i];return e<60?a.unshift(0):(e=(e-a[0])/i,a.unshift(e%i),e>=60&&(e=(e-a[0])/i,a.unshift(e))),n+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var sg={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:r})=>ho(t,r),stringify:Tl},cg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>ho(t,!1),stringify:Tl},Il={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Il.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,n,i,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(r,n-1,i,a||0,o||0,s||0,c),u=e[8];if(u&&u!=="Z"){let f=ho(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};si.floatTime=cg;si.intTime=sg;si.timestamp=Il});var $l=w(Ol=>{"use strict";var lg=Dt(),ug=Kn(),fg=Bt(),dg=Pr(),pg=no(),jl=xl(),go=_l(),ci=Al(),hg=qn(),mg=so(),gg=ti(),vg=po(),vo=mo(),wg=[lg.map,fg.seq,dg.string,ug.nullTag,jl.trueTag,jl.falseTag,ci.intBin,ci.intOct,ci.int,ci.intHex,go.floatNaN,go.floatExp,go.float,pg.binary,hg.merge,mg.omap,gg.pairs,vg.set,vo.intTime,vo.floatTime,vo.timestamp];Ol.schema=wg});var zl=w(bo=>{"use strict";var Ml=Dt(),yg=Kn(),ql=Bt(),bg=Pr(),Ng=Ja(),wo=Xa(),yo=Za(),kg=hl(),Sg=vl(),Wl=no(),Ar=qn(),Fl=so(),Hl=ti(),Ll=$l(),Vl=po(),li=mo(),Dl=new Map([["core",kg.schema],["failsafe",[Ml.map,ql.seq,bg.string]],["json",Sg.schema],["yaml11",Ll.schema],["yaml-1.1",Ll.schema]]),Bl={binary:Wl.binary,bool:Ng.boolTag,float:wo.float,floatExp:wo.floatExp,floatNaN:wo.floatNaN,floatTime:li.floatTime,int:yo.int,intHex:yo.intHex,intOct:yo.intOct,intTime:li.intTime,map:Ml.map,merge:Ar.merge,null:yg.nullTag,omap:Fl.omap,pairs:Hl.pairs,seq:ql.seq,set:Vl.set,timestamp:li.timestamp},Eg={"tag:yaml.org,2002:binary":Wl.binary,"tag:yaml.org,2002:merge":Ar.merge,"tag:yaml.org,2002:omap":Fl.omap,"tag:yaml.org,2002:pairs":Hl.pairs,"tag:yaml.org,2002:set":Vl.set,"tag:yaml.org,2002:timestamp":li.timestamp};function Pg(t,e,r){let n=Dl.get(e);if(n&&!t)return r&&!n.includes(Ar.merge)?n.concat(Ar.merge):n.slice();let i=n;if(!i)if(Array.isArray(t))i=[];else{let a=Array.from(Dl.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)i=i.concat(a);else typeof t=="function"&&(i=t(i.slice()));return r&&(i=i.concat(Ar.merge)),i.reduce((a,o)=>{let s=typeof o=="string"?Bl[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Bl).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},[])}bo.coreKnownTags=Eg;bo.getTags=Pg});var So=w(Gl=>{"use strict";var No=P(),Cg=Dt(),xg=Bt(),_g=Pr(),ui=zl(),Rg=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,ko=class t{constructor({compat:e,customTags:r,merge:n,resolveKnownTags:i,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?ui.getTags(e,"compat"):e?ui.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=i?ui.coreKnownTags:{},this.tags=ui.getTags(r,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,No.MAP,{value:Cg.map}),Object.defineProperty(this,No.SCALAR,{value:_g.string}),Object.defineProperty(this,No.SEQ,{value:xg.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Rg:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Gl.Schema=ko});var Kl=w(Ul=>{"use strict";var Ag=P(),Eo=kr(),Tr=wr();function Tg(t,e){let r=[],n=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(r.push(c),n=!0):t.directives.docStart&&(n=!0)}n&&r.push("---");let i=Eo.createStringifyContext(t,e),{commentString:a}=i.options;if(t.commentBefore){r.length!==1&&r.unshift("");let c=a(t.commentBefore);r.unshift(Tr.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(Ag.isNode(t.contents)){if(t.contents.spaceBefore&&n&&r.push(""),t.contents.commentBefore){let u=a(t.contents.commentBefore);r.push(Tr.indentComment(u,""))}i.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Eo.stringify(t.contents,i,()=>s=null,c);s&&(l+=Tr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Eo.stringify(t.contents,i));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
|
|
58
|
+
`)?(r.push("..."),r.push(Tr.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(Tr.indentComment(a(c),"")))}return r.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}Ul.stringifyDocument=Tg});var Ir=w(Jl=>{"use strict";var Ig=gr(),qt=An(),ne=P(),jg=Je(),Og=ze(),$g=So(),Lg=Kl(),Po=Cn(),Dg=_a(),Bg=vr(),Co=xa(),xo=class t{constructor(e,r,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ne.NODE_TYPE,{value:ne.DOC});let i=null;typeof r=="function"||Array.isArray(r)?i=r:n===void 0&&r&&(n=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Co.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(t.prototype,{[ne.NODE_TYPE]:{value:ne.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=ne.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Wt(this.contents)&&this.contents.add(e)}addIn(e,r){Wt(this.contents)&&this.contents.addIn(e,r)}createAlias(e,r){if(!e.anchor){let n=Po.anchorNames(this);e.anchor=!r||n.has(r)?Po.findNewAnchor(r||"a",n):r}return new Ig.Alias(e.anchor)}createNode(e,r,n){let i;if(typeof r=="function")e=r.call({"":e},"",e),i=r;else if(Array.isArray(r)){let m=b=>typeof b=="number"||b instanceof String||b instanceof Number,y=r.filter(m).map(String);y.length>0&&(r=r.concat(y)),i=r}else n===void 0&&r&&(n=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:f,setAnchors:d,sourceObjects:h}=Po.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:h},p=Bg.createNode(e,u,v);return s&&ne.isCollection(p)&&(p.flow=!0),d(),p}createPair(e,r,n={}){let i=this.createNode(e,null,n),a=this.createNode(r,null,n);return new jg.Pair(i,a)}delete(e){return Wt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return qt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Wt(this.contents)?this.contents.deleteIn(e):!1}get(e,r){return ne.isCollection(this.contents)?this.contents.get(e,r):void 0}getIn(e,r){return qt.isEmptyPath(e)?!r&&ne.isScalar(this.contents)?this.contents.value:this.contents:ne.isCollection(this.contents)?this.contents.getIn(e,r):void 0}has(e){return ne.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return qt.isEmptyPath(e)?this.contents!==void 0:ne.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,r){this.contents==null?this.contents=qt.collectionFromPath(this.schema,[e],r):Wt(this.contents)&&this.contents.set(e,r)}setIn(e,r){qt.isEmptyPath(e)?this.contents=r:this.contents==null?this.contents=qt.collectionFromPath(this.schema,Array.from(e),r):Wt(this.contents)&&this.contents.setIn(e,r)}setSchema(e,r={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Co.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Co.Directives({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(n)this.schema=new $g.Schema(Object.assign(n,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:r,mapAsMap:n,maxAliasCount:i,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=Og.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?Dg.applyReviver(o,{"":c},"",c):c}toJSON(e,r){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:r})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let r=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return Lg.stringifyDocument(this,e)}};function Wt(t){if(ne.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Jl.Document=xo});var $r=w(Or=>{"use strict";var jr=class extends Error{constructor(e,r,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=r}},_o=class extends jr{constructor(e,r,n){super("YAMLParseError",e,r,n)}},Ro=class extends jr{constructor(e,r,n){super("YAMLWarning",e,r,n)}},Mg=(t,e)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>e.linePos(s));let{line:n,col:i}=r.linePos[0];r.message+=` at line ${n}, column ${i}`;let a=i-1,o=t.substring(e.lineStarts[n-1],e.lineStarts[n]).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)+"…"),n>1&&/^ *$/.test(o.substring(0,a))){let s=t.substring(e.lineStarts[n-2],e.lineStarts[n-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===n&&c.col>i&&(s=Math.max(1,Math.min(c.col-i,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};
|
|
66
|
-
`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let r of e.start)if(r.type==="newline")return!0;if(e.sep){for(let r of e.sep)if(r.type==="newline")return!0}if(
|
|
67
|
-
`+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||
|
|
68
|
-
`+k.comment:b.comment=k.comment);let S=new
|
|
69
|
-
`+g.comment:l.comment=g.comment),f=g.end;continue}!o&&r.options.strict&&
|
|
70
|
-
`+C:N.comment=C,g.comment=g.comment.substring(C.length+1)}}if(!o&&!S&&!g.found){let C=E?t(r,E,g,i):e(r,g.end,S,null,g,i);l.items.push(C),f=C.range[2]
|
|
71
|
-
`+
|
|
72
|
-
`+m.comment:l.comment=m.comment),l.range=[n.offset,p,m.offset]}else l.range=[n.offset,p,p];return l}
|
|
65
|
+
`}};Or.YAMLError=jr;Or.YAMLParseError=_o;Or.YAMLWarning=Ro;Or.prettifyError=Mg});var Lr=w(Yl=>{"use strict";function qg(t,{flow:e,indicator:r,next:n,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,f="",d="",h=!1,v=!1,p=null,m=null,y=null,b=null,k=null,S=null,E=null;for(let N of t)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),p&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),N.type){case"space":!e&&(r!=="doc-start"||n?.type!=="flow-collection")&&N.source.includes(" ")&&(p=N),u=!0;break;case"comment":{u||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=N.source.substring(1)||" ";f?f+=d+R:f=R,d="",l=!1;break}case"newline":l?f?f+=N.source:(!S||r!=="seq-item-ind")&&(c=!0):d+=N.source,l=!0,h=!0,(m||y)&&(b=N),u=!0;break;case"anchor":m&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=N,E??(E=N.offset),l=!1,u=!1,v=!0;break;case"tag":{y&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),y=N,E??(E=N.offset),l=!1,u=!1,v=!0;break}case r:(m||y)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),S&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${e??"collection"}`),S=N,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(e){k&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=N,l=!1,u=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,u=!1}let g=t[t.length-1],C=g?g.offset+g.source.length:i;return v&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&a(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:f,hasNewline:h,anchor:m,tag:y,newlineAfterProp:b,end:C,start:E??C}}Yl.resolveProps=qg});var fi=w(Xl=>{"use strict";function Ao(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
|
|
66
|
+
`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let r of e.start)if(r.type==="newline")return!0;if(e.sep){for(let r of e.sep)if(r.type==="newline")return!0}if(Ao(e.key)||Ao(e.value))return!0}return!1;default:return!0}}Xl.containsNewline=Ao});var To=w(Ql=>{"use strict";var Wg=fi();function Fg(t,e,r){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===t&&(n.source==="]"||n.source==="}")&&Wg.containsNewline(e)&&r(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ql.flowIndentCheck=Fg});var Io=w(eu=>{"use strict";var Zl=P();function Hg(t,e,r){let{uniqueKeys:n}=t.options;if(n===!1)return!1;let i=typeof n=="function"?n:(a,o)=>a===o||Zl.isScalar(a)&&Zl.isScalar(o)&&a.value===o.value;return e.some(a=>i(a.key,r))}eu.mapIncludes=Hg});var ou=w(au=>{"use strict";var tu=Je(),Vg=Xe(),ru=Lr(),zg=fi(),nu=To(),Gg=Io(),iu="All mapping items must start at the same column";function Ug({composeNode:t,composeEmptyNode:e},r,n,i,a){let o=a?.nodeClass??Vg.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:f,key:d,sep:h,value:v}=u,p=ru.resolveProps(f,{indicator:"explicit-key-ind",next:d??h?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),m=!p.found;if(m){if(d&&(d.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==n.indent&&i(c,"BAD_INDENT",iu)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||zg.containsNewline(d))&&i(d??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==n.indent&&i(c,"BAD_INDENT",iu);r.atKey=!0;let y=p.end,b=d?t(r,d,p,i):e(r,y,f,null,p,i);r.schema.compat&&nu.flowIndentCheck(n.indent,d,i),r.atKey=!1,Gg.mapIncludes(r,s.items,b)&&i(y,"DUPLICATE_KEY","Map keys must be unique");let k=ru.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:b.range[2],onError:i,parentIndent:n.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=k.end,k.found){m&&(v?.type==="block-map"&&!k.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&p.start<k.found.offset-1024&&i(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let S=v?t(r,v,k,i):e(r,c,h,null,k,i);r.schema.compat&&nu.flowIndentCheck(n.indent,v,i),c=S.range[2];let E=new tu.Pair(b,S);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{m&&i(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(b.comment?b.comment+=`
|
|
68
|
+
`+k.comment:b.comment=k.comment);let S=new tu.Pair(b);r.options.keepSourceTokens&&(S.srcToken=u),s.items.push(S)}}return l&&l<c&&i(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}au.resolveBlockMap=Ug});var cu=w(su=>{"use strict";var Kg=Qe(),Jg=Lr(),Yg=To();function Xg({composeNode:t,composeEmptyNode:e},r,n,i,a){let o=a?.nodeClass??Kg.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=n.offset,l=null;for(let{start:u,value:f}of n.items){let d=Jg.resolveProps(u,{indicator:"seq-item-ind",next:f,offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||f)f?.type==="block-seq"?i(d.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let h=f?t(r,f,d,i):e(r,d.end,u,null,d,i);r.schema.compat&&Yg.flowIndentCheck(n.indent,f,i),c=h.range[2],s.items.push(h)}return s.range=[n.offset,c,l??c],s}su.resolveBlockSeq=Xg});var Ft=w(lu=>{"use strict";function Qg(t,e,r,n){let i="";if(t){let a=!1,o="";for(let s of t){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&n(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";i?i+=o+u:i=u,o="";break}case"newline":i&&(o+=c),a=!0;break;default:n(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:i,offset:e}}lu.resolveEnd=Qg});var pu=w(du=>{"use strict";var Zg=P(),ev=Je(),uu=Xe(),tv=Qe(),rv=Ft(),fu=Lr(),nv=fi(),iv=Io(),jo="Block collections are not allowed within flow collections",Oo=t=>t&&(t.type==="block-map"||t.type==="block-seq");function av({composeNode:t,composeEmptyNode:e},r,n,i,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?uu.YAMLMap:tv.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let f=n.offset+n.start.source.length;for(let m=0;m<n.items.length;++m){let y=n.items[m],{start:b,key:k,sep:S,value:E}=y,g=fu.resolveProps(b,{flow:s,indicator:"explicit-key-ind",next:k??S?.[0],offset:f,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!g.found){if(!g.anchor&&!g.tag&&!S&&!E){m===0&&g.comma?i(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<n.items.length-1&&i(g.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),g.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+g.comment:l.comment=g.comment),f=g.end;continue}!o&&r.options.strict&&nv.containsNewline(k)&&i(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)g.comma&&i(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(g.comma||i(g.start,"MISSING_CHAR",`Missing , between ${s} items`),g.comment){let C="";e:for(let N of b)switch(N.type){case"comma":case"space":break;case"comment":C=N.source.substring(1);break e;default:break e}if(C){let N=l.items[l.items.length-1];Zg.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
|
|
70
|
+
`+C:N.comment=C,g.comment=g.comment.substring(C.length+1)}}if(!o&&!S&&!g.found){let C=E?t(r,E,g,i):e(r,g.end,S,null,g,i);l.items.push(C),f=C.range[2],Oo(E)&&i(C.range,"BLOCK_IN_FLOW",jo)}else{r.atKey=!0;let C=g.end,N=k?t(r,k,g,i):e(r,C,b,null,g,i);Oo(k)&&i(N.range,"BLOCK_IN_FLOW",jo),r.atKey=!1;let R=fu.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:E,offset:N.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(R.found){if(!o&&!g.found&&r.options.strict){if(S)for(let $ of S){if($===R.found)break;if($.type==="newline"){i($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}g.start<R.found.offset-1024&&i(R.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]===":"?i(E,"MISSING_CHAR",`Missing space after : in ${s}`):i(R.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let ee=E?t(r,E,R,i):R.found?e(r,R.end,S,null,R,i):null;ee?Oo(E)&&i(ee.range,"BLOCK_IN_FLOW",jo):R.comment&&(N.comment?N.comment+=`
|
|
71
|
+
`+R.comment:N.comment=R.comment);let It=new ev.Pair(N,ee);if(r.options.keepSourceTokens&&(It.srcToken=y),o){let $=l;iv.mapIncludes(r,$.items,N)&&i(C,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(It)}else{let $=new uu.YAMLMap(r.schema);$.flow=!0,$.items.push(It);let pc=(ee??N).range;$.range=[N.range[0],pc[1],pc[2]],l.items.push($)}f=ee?ee.range[2]:R.end}}let d=o?"}":"]",[h,...v]=n.end,p=f;if(h?.source===d)p=h.offset+h.source.length;else{let m=s[0].toUpperCase()+s.substring(1),y=u?`${m} must end with a ${d}`:`${m} in block collection must be sufficiently indented and end with a ${d}`;i(f,u?"MISSING_CHAR":"BAD_INDENT",y),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let m=rv.resolveEnd(v,p,r.options.strict,i);m.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+m.comment:l.comment=m.comment),l.range=[n.offset,p,m.offset]}else l.range=[n.offset,p,p];return l}du.resolveFlowCollection=av});var mu=w(hu=>{"use strict";var ov=P(),sv=j(),cv=Xe(),lv=Qe(),uv=ou(),fv=cu(),dv=pu();function $o(t,e,r,n,i,a){let o=r.type==="block-map"?uv.resolveBlockMap(t,e,r,n,a):r.type==="block-seq"?fv.resolveBlockSeq(t,e,r,n,a):dv.resolveFlowCollection(t,e,r,n,a),s=o.constructor;return i==="!"||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function pv(t,e,r,n,i){let a=n.tag,o=a?e.directives.tagName(a.source,d=>i(a,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:h}=n,v=d&&a?d.offset>a.offset?d:a:d??a;v&&(!h||h.offset<v.offset)&&i(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===cv.YAMLMap.tagName&&s==="map"||o===lv.YAMLSeq.tagName&&s==="seq")return $o(t,e,r,i,o);let c=e.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=e.schema.knownTags[o];if(d?.collection===s)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?i(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):i(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),$o(t,e,r,i,o)}let l=$o(t,e,r,i,o,c),u=c.resolve?.(l,d=>i(a,"TAG_RESOLVE_FAILED",d),e.options)??l,f=ov.isNode(u)?u:new sv.Scalar(u);return f.range=l.range,f.tag=o,c?.format&&(f.format=c.format),f}hu.composeCollection=pv});var Do=w(gu=>{"use strict";var Lo=j();function hv(t,e,r){let n=e.offset,i=mv(e,t.options.strict,r);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let a=i.mode===">"?Lo.Scalar.BLOCK_FOLDED:Lo.Scalar.BLOCK_LITERAL,o=e.source?gv(e.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")s=p;else break}if(s===0){let p=i.chomp==="+"&&o.length>0?`
|
|
73
73
|
`.repeat(Math.max(1,o.length-1)):"",m=n+i.length;return e.source&&(m+=e.source.length),{value:p,type:a,comment:i.comment,range:[n,m,m]}}let c=e.indent+i.indent,l=e.offset+i.length,u=0;for(let p=0;p<s;++p){let[m,y]=o[p];if(y===""||y==="\r")i.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&r(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=m.length),u=p,c===0&&!t.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+y.length+1}for(let p=o.length-1;p>=s;--p)o[p][0].length>c&&(s=p+1);let f="",d="",h=!1;for(let p=0;p<u;++p)f+=o[p][0].slice(c)+`
|
|
74
|
-
`;for(let p=u;p<s;++p){let[m,y]=o[p];l+=m.length+y.length+1;let b=y[y.length-1]==="\r";if(b&&(y=y.slice(0,-1)),y&&m.length<c){let S=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;r(l-y.length-(b?2:1),"BAD_INDENT",S),m=""}a===
|
|
74
|
+
`;for(let p=u;p<s;++p){let[m,y]=o[p];l+=m.length+y.length+1;let b=y[y.length-1]==="\r";if(b&&(y=y.slice(0,-1)),y&&m.length<c){let S=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;r(l-y.length-(b?2:1),"BAD_INDENT",S),m=""}a===Lo.Scalar.BLOCK_LITERAL?(f+=d+m.slice(c)+y,d=`
|
|
75
75
|
`):m.length>c||y[0]===" "?(d===" "?d=`
|
|
76
76
|
`:!h&&d===`
|
|
77
77
|
`&&(d=`
|
|
@@ -84,85 +84,85 @@ ${l}
|
|
|
84
84
|
`+o[p][0].slice(c);f[f.length-1]!==`
|
|
85
85
|
`&&(f+=`
|
|
86
86
|
`);break;default:f+=`
|
|
87
|
-
`}let v=n+i.length+e.source.length;return{value:f,type:a,comment:i.comment,range:[n,v,v]}}function
|
|
87
|
+
`}let v=n+i.length+e.source.length;return{value:f,type:a,comment:i.comment,range:[n,v,v]}}function mv({offset:t,props:e},r,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=e[0],a=i[0],o=0,s="",c=-1;for(let d=1;d<i.length;++d){let h=i[d];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=t+d)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",f=i.length;for(let d=1;d<e.length;++d){let h=e[d];switch(h.type){case"space":l=!0;case"newline":f+=h.source.length;break;case"comment":r&&!l&&n(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=h.source.length,u=h.source.substring(1);break;case"error":n(h,"UNEXPECTED_TOKEN",h.message),f+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;n(h,"UNEXPECTED_TOKEN",v);let p=h.source;p&&typeof p=="string"&&(f+=p.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:f}}function gv(t){let e=t.split(/\n( *)/),r=e[0],n=r.match(/^( *)/),a=[n?.[1]?[n[1],r.slice(n[1].length)]:["",r]];for(let o=1;o<e.length;o+=2)a.push([e[o],e[o+1]]);return a}gu.resolveBlockScalar=hv});var Mo=w(wu=>{"use strict";var Bo=j(),vv=Ft();function wv(t,e,r){let{offset:n,type:i,source:a,end:o}=t,s,c,l=(d,h,v)=>r(n+d,h,v);switch(i){case"scalar":s=Bo.Scalar.PLAIN,c=yv(a,l);break;case"single-quoted-scalar":s=Bo.Scalar.QUOTE_SINGLE,c=bv(a,l);break;case"double-quoted-scalar":s=Bo.Scalar.QUOTE_DOUBLE,c=Nv(a,l);break;default:return r(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+a.length,n+a.length]}}let u=n+a.length,f=vv.resolveEnd(o,u,e,r);return{value:c,type:s,comment:f.comment,range:[n,u,f.offset]}}function yv(t,e){let r="";switch(t[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${t[0]}`;break}case"@":case"`":{r=`reserved character ${t[0]}`;break}}return r&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),vu(t)}function bv(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),vu(t.slice(1,-1)).replace(/''/g,"'")}function vu(t){let e,r;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
89
|
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(t);if(!n)return t;let i=n[1],a=" ",o=e.lastIndex;for(r.lastIndex=o;n=r.exec(t);)n[1]===""?a===`
|
|
90
90
|
`?i+=a:a=`
|
|
91
|
-
`:(i+=a+n[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,n=s.exec(t),i+a+(n?.[1]??"")}function
|
|
91
|
+
`:(i+=a+n[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,n=s.exec(t),i+a+(n?.[1]??"")}function Nv(t,e){let r="";for(let n=1;n<t.length-1;++n){let i=t[n];if(!(i==="\r"&&t[n+1]===`
|
|
92
92
|
`))if(i===`
|
|
93
|
-
`){let{fold:a,offset:o}=
|
|
93
|
+
`){let{fold:a,offset:o}=kv(t,n);r+=a,n=o}else if(i==="\\"){let a=t[++n],o=Sv[a];if(o)r+=o;else if(a===`
|
|
94
94
|
`)for(a=t[n+1];a===" "||a===" ";)a=t[++n+1];else if(a==="\r"&&t[n+1]===`
|
|
95
|
-
`)for(a=t[++n+1];a===" "||a===" ";)a=t[++n+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=
|
|
95
|
+
`)for(a=t[++n+1];a===" "||a===" ";)a=t[++n+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=Ev(t,n+1,s,e),n+=s}else{let s=t.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(i===" "||i===" "){let a=n,o=t[n+1];for(;o===" "||o===" ";)o=t[++n+1];o!==`
|
|
96
96
|
`&&!(o==="\r"&&t[n+2]===`
|
|
97
|
-
`)&&(r+=n>a?t.slice(a,n+1):i)}else r+=i}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),r}function
|
|
97
|
+
`)&&(r+=n>a?t.slice(a,n+1):i)}else r+=i}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),r}function kv(t,e){let r="",n=t[e+1];for(;(n===" "||n===" "||n===`
|
|
98
98
|
`||n==="\r")&&!(n==="\r"&&t[e+2]!==`
|
|
99
99
|
`);)n===`
|
|
100
100
|
`&&(r+=`
|
|
101
|
-
`),e+=1,n=t[e+1];return r||(r=" "),{fold:r,offset:e}}var
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),e+=1,n=t[e+1];return r||(r=" "),{fold:r,offset:e}}var Sv={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Ev(t,e,r,n){let i=t.substr(e,r),o=i.length===r&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let s=t.substr(e-2,r+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}wu.resolveFlowScalar=wv});var Nu=w(bu=>{"use strict";var mt=P(),yu=j(),Pv=Do(),Cv=Mo();function xv(t,e,r,n){let{value:i,type:a,comment:o,range:s}=e.type==="block-scalar"?Pv.resolveBlockScalar(t,e,n):Cv.resolveFlowScalar(e,t.options.strict,n),c=r?t.directives.tagName(r.source,f=>n(r,"TAG_RESOLVE_FAILED",f)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[mt.SCALAR]:c?l=_v(t.schema,i,c,r,n):e.type==="scalar"?l=Rv(t,i,e,n):l=t.schema[mt.SCALAR];let u;try{let f=l.resolve(i,d=>n(r??e,"TAG_RESOLVE_FAILED",d),t.options);u=mt.isScalar(f)?f:new yu.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);n(r??e,"TAG_RESOLVE_FAILED",d),u=new yu.Scalar(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function _v(t,e,r,n,i){if(r==="!")return t[mt.SCALAR];let a=[];for(let s of t.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(e))return s;let o=t.knownTags[r];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),t[mt.SCALAR])}function Rv({atKey:t,directives:e,schema:r},n,i,a){let o=r.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(n))||r[mt.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(n))??r[mt.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}bu.composeScalar=xv});var Su=w(ku=>{"use strict";function Av(t,e,r){if(e){r??(r=e.length);for(let n=r-1;n>=0;--n){let i=e[n];switch(i.type){case"space":case"comment":case"newline":t-=i.source.length;continue}for(i=e[++n];i?.type==="space";)t+=i.source.length,i=e[++n];break}}return t}ku.emptyScalarPosition=Av});var Cu=w(Wo=>{"use strict";var Tv=gr(),Iv=P(),jv=mu(),Eu=Nu(),Ov=Ft(),$v=Su(),Lv={composeNode:Pu,composeEmptyNode:qo};function Pu(t,e,r,n){let i=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(e.type){case"alias":l=Dv(t,e,n),(s||c)&&n(e,"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=Eu.composeScalar(t,e,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=jv.composeCollection(Lv,t,e,r,n),s&&(l.anchor=s.source.substring(1))}catch(f){let d=f instanceof Error?f.message:String(f);n(e,"RESOURCE_EXHAUSTION",d)}break;default:{let f=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",f),u=!1}}return l??(l=qo(t,e.offset,void 0,null,r,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),i&&t.options.stringKeys&&(!Iv.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&u&&(l.srcToken=e),l}function qo(t,e,r,n,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:$v.emptyScalarPosition(e,r,n),indent:-1,source:""},f=Eu.composeScalar(t,u,s,l);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(f.spaceBefore=!0),a&&(f.comment=a,f.range[2]=c),f}function Dv({options:t},{offset:e,source:r,end:n},i){let a=new Tv.Alias(r.substring(1));a.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&i(e+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+r.length,s=Ov.resolveEnd(n,o,t.strict,i);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}Wo.composeEmptyNode=qo;Wo.composeNode=Pu});var Ru=w(_u=>{"use strict";var Bv=Ir(),xu=Cu(),Mv=Ft(),qv=Lr();function Wv(t,e,{offset:r,start:n,value:i,end:a},o){let s=Object.assign({_directives:e},t),c=new Bv.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=qv.resolveProps(n,{indicator:"doc-start",next:i??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?xu.composeNode(l,i,u,o):xu.composeEmptyNode(l,u.end,n,null,u,o);let f=c.contents.range[2],d=Mv.resolveEnd(a,f,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,f,d.offset],c}_u.composeDoc=Wv});var Ho=w(Iu=>{"use strict";var Fv=Nn("process"),Hv=xa(),Vv=Ir(),Dr=$r(),Au=P(),zv=Ru(),Gv=Ft();function Br(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:r}=t;return[e,e+(typeof r=="string"?r.length:1)]}function Tu(t){let e="",r=!1,n=!1;for(let i=0;i<t.length;++i){let a=t[i];switch(a[0]){case"#":e+=(e===""?"":n?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.substring(1)||" "),r=!0,n=!1;break;case"%":t[i+1]?.[0]!=="#"&&(i+=1),r=!1;break;default:r||(n=!0),r=!1}}return{comment:e,afterEmptyLine:n}}var
|
|
106
|
-
${n}`:n;else if(i||e.directives.docStart||!a)e.commentBefore=n;else if(
|
|
105
|
+
`)+(a.substring(1)||" "),r=!0,n=!1;break;case"%":t[i+1]?.[0]!=="#"&&(i+=1),r=!1;break;default:r||(n=!0),r=!1}}return{comment:e,afterEmptyLine:n}}var Fo=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,n,i,a)=>{let o=Br(r);a?this.warnings.push(new Dr.YAMLWarning(o,n,i)):this.errors.push(new Dr.YAMLParseError(o,n,i))},this.directives=new Hv.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,r){let{comment:n,afterEmptyLine:i}=Tu(this.prelude);if(n){let a=e.contents;if(r)e.comment=e.comment?`${e.comment}
|
|
106
|
+
${n}`:n;else if(i||e.directives.docStart||!a)e.commentBefore=n;else if(Au.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Au.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${n}
|
|
107
107
|
${s}`:n}else{let o=a.commentBefore;a.commentBefore=o?`${n}
|
|
108
|
-
${o}`:n}}if(r){for(let a=0;a<this.errors.length;++a)e.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)e.warnings.push(this.warnings[a])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
109
|
-
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new
|
|
108
|
+
${o}`:n}}if(r){for(let a=0;a<this.errors.length;++a)e.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)e.warnings.push(this.warnings[a])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Tu(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,r=!1,n=-1){for(let i of e)yield*this.next(i);yield*this.end(r,n)}*next(e){switch(Fv.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(r,n,i)=>{let a=Br(e);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let r=zv.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let r=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new Dr.YAMLParseError(Br(e),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new Dr.YAMLParseError(Br(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let r=Gv.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
|
|
109
|
+
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Dr.YAMLParseError(Br(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),i=new Vv.Document(void 0,n);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,r,r],this.decorate(i,!1),yield i}}};Iu.Composer=Fo});var $u=w(di=>{"use strict";var Uv=Do(),Kv=Mo(),Jv=$r(),ju=Nr();function Yv(t,e=!0,r){if(t){let n=(i,a,o)=>{let s=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(r)r(s,a,o);else throw new Jv.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Kv.resolveFlowScalar(t,e,n);case"block-scalar":return Uv.resolveBlockScalar({options:{strict:e}},t,n)}}return null}function Xv(t,e){let{implicitKey:r=!1,indent:n,inFlow:i=!1,offset:a=-1,type:o="PLAIN"}=e,s=ju.stringifyString({type:o,value:t},{implicitKey:r,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
111
|
`),u=s.substring(0,l),f=s.substring(l+1)+`
|
|
112
|
-
`,d=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:n,props:d,source:f}}case'"':return{type:"double-quoted-scalar",offset:a,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:n,source:s,end:c};default:return{type:"scalar",offset:a,indent:n,source:s,end:c}}}function
|
|
112
|
+
`,d=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return Ou(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:n,props:d,source:f}}case'"':return{type:"double-quoted-scalar",offset:a,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:n,source:s,end:c};default:return{type:"scalar",offset:a,indent:n,source:s,end:c}}}function Qv(t,e,r={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:a=!1,type:o}=r,s="indent"in t?t.indent:null;if(n&&typeof s=="number"&&(s+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.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=ju.stringifyString({type:o,value:e},{implicitKey:i||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Zv(t,c);break;case'"':Vo(t,c,"double-quoted-scalar");break;case"'":Vo(t,c,"single-quoted-scalar");break;default:Vo(t,c,"scalar")}}function Zv(t,e){let r=e.indexOf(`
|
|
114
114
|
`),n=e.substring(0,r),i=e.substring(r+1)+`
|
|
115
|
-
`;if(t.type==="block-scalar"){let a=t.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=n,t.source=i}else{let{offset:a}=t,o="indent"in t?t.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:n}];
|
|
116
|
-
`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:i})}}function
|
|
117
|
-
`};delete t.items,Object.assign(t,{type:r,source:e,end:[i]});break}default:{let n="indent"in t?t.indent:-1,i="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:r,indent:n,source:e,end:i})}}}
|
|
115
|
+
`;if(t.type==="block-scalar"){let a=t.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=n,t.source=i}else{let{offset:a}=t,o="indent"in t?t.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:n}];Ou(s,"end"in t?t.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:i})}}function Ou(t,e){if(e)for(let r of e)switch(r.type){case"space":case"comment":t.push(r);break;case"newline":return t.push(r),!0}return!1}function Vo(t,e,r){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=r,t.source=e;break;case"block-scalar":{let n=t.props.slice(1),i=e.length;t.props[0].type==="block-scalar-header"&&(i-=t.props[0].source.length);for(let a of n)a.offset+=i;delete t.props,Object.assign(t,{type:r,source:e,end:n});break}case"block-map":case"block-seq":{let i={type:"newline",offset:t.offset+e.length,indent:t.indent,source:`
|
|
117
|
+
`};delete t.items,Object.assign(t,{type:r,source:e,end:[i]});break}default:{let n="indent"in t?t.indent:-1,i="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:r,indent:n,source:e,end:i})}}}di.createScalarToken=Xv;di.resolveAsScalar=Yv;di.setScalarValue=Qv});var Du=w(Lu=>{"use strict";var ew=t=>"type"in t?hi(t):pi(t);function hi(t){switch(t.type){case"block-scalar":{let e="";for(let r of t.props)e+=hi(r);return e+t.source}case"block-map":case"block-seq":{let e="";for(let r of t.items)e+=pi(r);return e}case"flow-collection":{let e=t.start.source;for(let r of t.items)e+=pi(r);for(let r of t.end)e+=r.source;return e}case"document":{let e=pi(t);if(t.end)for(let r of t.end)e+=r.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let r of t.end)e+=r.source;return e}}}function pi({start:t,key:e,sep:r,value:n}){let i="";for(let a of t)i+=a.source;if(e&&(i+=hi(e)),r)for(let a of r)i+=a.source;return n&&(i+=hi(n)),i}Lu.stringify=ew});var Wu=w(qu=>{"use strict";var zo=Symbol("break visit"),tw=Symbol("skip children"),Bu=Symbol("remove item");function gt(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Mu(Object.freeze([]),t,e)}gt.BREAK=zo;gt.SKIP=tw;gt.REMOVE=Bu;gt.itemAtPath=(t,e)=>{let r=t;for(let[n,i]of e){let a=r?.[n];if(a&&"items"in a)r=a.items[i];else return}return r};gt.parentCollection=(t,e)=>{let r=gt.itemAtPath(t,e.slice(0,-1)),n=e[e.length-1][0],i=r?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function Mu(t,e,r){let n=r(e,t);if(typeof n=="symbol")return n;for(let i of["key","value"]){let a=e[i];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Mu(Object.freeze(t.concat([[i,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===zo)return zo;s===Bu&&(a.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(e,t))}}return typeof n=="function"?n(e,t):n}qu.visit=gt});var mi=w(J=>{"use strict";var Go=$u(),rw=Du(),nw=Wu(),Uo="\uFEFF",Ko="",Jo="",Yo="",iw=t=>!!t&&"items"in t,aw=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function ow(t){switch(t){case Uo:return"<BOM>";case Ko:return"<DOC>";case Jo:return"<FLOW_END>";case Yo:return"<SCALAR>";default:return JSON.stringify(t)}}function sw(t){switch(t){case Uo:return"byte-order-mark";case Ko:return"doc-mode";case Jo:return"flow-error-end";case Yo: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(t[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}
|
|
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(t[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}J.createScalarToken=Go.createScalarToken;J.resolveAsScalar=Go.resolveAsScalar;J.setScalarValue=Go.setScalarValue;J.stringify=rw.stringify;J.visit=nw.visit;J.BOM=Uo;J.DOCUMENT=Ko;J.FLOW_END=Jo;J.SCALAR=Yo;J.isCollection=iw;J.isScalar=aw;J.prettyToken=ow;J.tokenType=sw});var Zo=w(Hu=>{"use strict";var Mr=mi();function fe(t){switch(t){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var Fu=new Set("0123456789ABCDEFabcdef"),cw=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),gi=new Set(",[]{}"),lw=new Set(` ,[]{}
|
|
121
|
+
\r `),Xo=t=>!t||lw.has(t),Qo=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(e,r=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!r;let n=this.next??"stream";for(;n&&(r||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,r=this.buffer[e];for(;r===" "||r===" ";)r=this.buffer[++e];return!r||r==="#"||r===`
|
|
122
122
|
`?!0:r==="\r"?this.buffer[e+1]===`
|
|
123
123
|
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let r=this.buffer[e];if(this.indentNext>0){let n=0;for(;r===" ";)r=this.buffer[++n+e];if(r==="\r"){let i=this.buffer[n+e+1];if(i===`
|
|
124
124
|
`||!i&&!this.atEnd)return e+n+1}return r===`
|
|
125
|
-
`||n>=this.indentNext||!r&&!this.atEnd?e+n:-1}if(r==="-"||r==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&
|
|
126
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){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 e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===
|
|
125
|
+
`||n>=this.indentNext||!r&&!this.atEnd?e+n:-1}if(r==="-"||r==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&fe(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
126
|
+
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){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 e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Mr.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let r=e.length,n=e.indexOf("#");for(;n!==-1;){let a=e[n-1];if(a===" "||a===" "){r=n-1;break}else n=e.indexOf("#",n+1)}for(;;){let a=e[r-1];if(a===" "||a===" ")r-=1;else break}let i=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-r),yield*this.pushNewline(),"stream"}return yield Mr.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&fe(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!fe(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&fe(r)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(e[r]){case"#":yield*this.pushCount(e.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Xo),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,r,n=-1;do e=yield*this.pushNewline(),e>0?(r=yield*this.pushSpaces(!1),this.indentValue=n=r):r=0,r+=yield*this.pushSpaces(!0);while(e+r>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&fe(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Mr.FLOW_END,yield*this.parseLineStart();let a=0;for(;i[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),i[a]){case void 0:return"flow";case"#":return yield*this.pushCount(i.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(Xo),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||fe(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 e=this.charAt(0),r=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let n=this.buffer.substring(0,r),i=n.indexOf(`
|
|
127
127
|
`,this.pos);if(i!==-1){for(;i!==-1;){let a=this.continueScalar(i+1);if(a===-1)break;i=n.indexOf(`
|
|
128
|
-
`,a)}i!==-1&&(r=i-(n[i-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let r=this.buffer[++e];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>
|
|
128
|
+
`,a)}i!==-1&&(r=i-(n[i-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let r=this.buffer[++e];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>fe(r)||r==="#")}*parseBlockScalar(){let e=this.pos-1,r=0,n;e:for(let a=this.pos;n=this.buffer[a];++a)switch(n){case" ":r+=1;break;case`
|
|
129
129
|
`:e=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
130
|
`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(e+1);if(a===-1)break;e=this.buffer.indexOf(`
|
|
131
131
|
`,a)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let i=e+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
|
|
132
132
|
`;)n=this.buffer[++i];e=i-1}else if(!this.blockScalarKeep)do{let a=e-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
-
`&&a>=this.pos&&a+1+r>s)e=a;else break}while(!0);return yield
|
|
133
|
+
`&&a>=this.pos&&a+1+r>s)e=a;else break}while(!0);return yield Mr.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,r=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let a=this.buffer[n+1];if(fe(a)||e&&gi.has(a))break;r=n}else if(fe(i)){let a=this.buffer[n+1];if(i==="\r"&&(a===`
|
|
134
134
|
`?(n+=1,i=`
|
|
135
|
-
`,a=this.buffer[n+1]):r=n),a==="#"||e&&
|
|
136
|
-
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&
|
|
135
|
+
`,a=this.buffer[n+1]):r=n),a==="#"||e&&gi.has(a))break;if(i===`
|
|
136
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&gi.has(i))break;r=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Mr.SCALAR,yield*this.pushToIndex(r+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,r){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(r&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Xo),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,n=this.charAt(1);if(fe(n)||r&&gi.has(n)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,r=this.buffer[e];for(;!fe(r)&&r!==">";)r=this.buffer[++e];return yield*this.pushToIndex(r===">"?e+1:e,!1)}else{let e=this.pos+1,r=this.buffer[e];for(;r;)if(cw.has(r))r=this.buffer[++e];else if(r==="%"&&Fu.has(this.buffer[e+1])&&Fu.has(this.buffer[e+2]))r=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
137
137
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let r=this.pos-1,n;do n=this.buffer[++r];while(n===" "||e&&n===" ");let i=r-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=r),i}*pushUntil(e){let r=this.pos,n=this.buffer[r];for(;!e(n);)n=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let r=this.pos-1,n;do n=this.buffer[++r];while(n===" "||e&&n===" ");let i=r-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=r),i}*pushUntil(e){let r=this.pos,n=this.buffer[r];for(;!e(n);)n=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Hu.Lexer=Qo});var ts=w(Vu=>{"use strict";var es=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let r=0,n=this.lineStarts.length;for(;r<n;){let a=r+n>>1;this.lineStarts[a]<e?r=a+1:n=a}if(this.lineStarts[r]===e)return{line:r+1,col:1};if(r===0)return{line:0,col:e};let i=this.lineStarts[r-1];return{line:r,col:e-i+1}}}};Vu.LineCounter=es});var ns=w(Ju=>{"use strict";var uw=Nn("process"),zu=mi(),fw=Zo();function Ze(t,e){for(let r=0;r<t.length;++r)if(t[r].type===e)return!0;return!1}function Gu(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Ku(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function vi(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function Ht(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function wi(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let r=0;r<e.length;++r)t.push(e[r])}function Uu(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!Ze(e.start,"explicit-key-ind")&&!Ze(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Ku(e.value)?e.value.end?wi(e.value.end,e.sep):e.value.end=e.sep:wi(e.start,e.sep),delete e.sep)}var rs=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new fw.Lexer,this.onNewLine=e}*parse(e,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,r))yield*this.next(n);r||(yield*this.end())}*next(e){if(this.source=e,uw.env.LOG_TOKENS&&console.log("|",zu.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=zu.tokenType(e);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let n=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:e}),this.offset+=e.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 e=this.peek(1);if(this.type==="doc-end"&&e?.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(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let r=e??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let n=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in n?n.indent:0:r.type==="flow-collection"&&n.type==="document"&&(r.indent=0),r.type==="flow-collection"&&Uu(r),n.type){case"document":n.value=r;break;case"block-scalar":n.props.push(r);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=r;else{Object.assign(i,{key:r,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:r}):i.value=r;break}case"flow-collection":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:r,sep:[]}):i.sep?i.value=r:Object.assign(i,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let i=r.items[r.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&Gu(i.start)===-1&&(r.indent===0||i.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(n.type==="document"?n.end=i.start:n.items.push({start:i.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Gu(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let r=vi(this.peek(2)),n=Ht(r),i;e.end?(i=e.end,i.push(this.sourceToken),delete e.end):i=[this.sourceToken];let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
140
|
-
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let r=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)e.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){
|
|
140
|
+
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let r=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)e.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){wi(i,r.start),i.push(this.sourceToken),e.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,i=n&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(i&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||r.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):i||r.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ze(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Ku(r.key)&&!Ze(r.sep,"newline")){let o=Ht(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Ze(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Ht(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||i?e.items.push({start:a,key:null,sep:[this.sourceToken]}):Ze(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);i||r.value?(e.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Ze(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let r=e.items[e.items.length-1];switch(this.type){case"newline":if(r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){wi(i,r.start),i.push(this.sourceToken),e.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=e.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;r.value||Ze(r.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let r=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?e.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?e.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!r||r.value?e.items.push({start:[],key:i,sep:[]}):r.sep?this.stack.push(i):Object.assign(r,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=vi(n),a=Ht(i);Uu(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let r=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
142
|
-
`,r)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=gi(e),n=Ft(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=gi(e),n=Ft(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,r){return this.type!=="comment"||this.indent<=r?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){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:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ju.Parser=ns});var Zu=w(Wr=>{"use strict";var Uu=Vo(),sw=Tr(),Mr=Or(),cw=qa(),lw=P(),uw=rs(),Yu=is();function Xu(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new uw.LineCounter||null,prettyErrors:e}}function fw(t,e={}){let{lineCounter:r,prettyErrors:n}=Xu(e),i=new Yu.Parser(r?.addNewLine),a=new Uu.Composer(e),o=Array.from(a.compose(i.parse(t)));if(n&&r)for(let s of o)s.errors.forEach(Mr.prettifyError(t,r)),s.warnings.forEach(Mr.prettifyError(t,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Qu(t,e={}){let{lineCounter:r,prettyErrors:n}=Xu(e),i=new Yu.Parser(r?.addNewLine),a=new Uu.Composer(e),o=null;for(let s of a.compose(i.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Mr.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(o.errors.forEach(Mr.prettifyError(t,r)),o.warnings.forEach(Mr.prettifyError(t,r))),o}function dw(t,e,r){let n;typeof e=="function"?n=e:r===void 0&&e&&typeof e=="object"&&(r=e);let i=Qu(t,r);if(!i)return null;if(i.warnings.forEach(a=>cw.warn(i.options.logLevel,a)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},r))}function pw(t,e,r){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:r===void 0&&e&&(r=e),typeof r=="string"&&(r=r.length),typeof r=="number"){let i=Math.round(r);r=i<1?void 0:i>8?{indent:8}:{indent:i}}if(t===void 0){let{keepUndefined:i}=r??e??{};if(!i)return}return lw.isDocument(t)&&!n?t.toString(r):new sw.Document(t,n,r).toString(r)}Wr.parse=dw;Wr.parseAllDocuments=fw;Wr.parseDocument=Qu;Wr.stringify=pw});var Le=w(x=>{"use strict";var hw=Vo(),mw=Tr(),gw=Eo(),as=Or(),vw=mr(),tt=P(),ww=Ye(),yw=j(),bw=Qe(),Nw=Ze(),kw=hi(),Sw=es(),Ew=rs(),Pw=is(),wi=Zu(),ef=fr();x.Composer=hw.Composer;x.Document=mw.Document;x.Schema=gw.Schema;x.YAMLError=as.YAMLError;x.YAMLParseError=as.YAMLParseError;x.YAMLWarning=as.YAMLWarning;x.Alias=vw.Alias;x.isAlias=tt.isAlias;x.isCollection=tt.isCollection;x.isDocument=tt.isDocument;x.isMap=tt.isMap;x.isNode=tt.isNode;x.isPair=tt.isPair;x.isScalar=tt.isScalar;x.isSeq=tt.isSeq;x.Pair=ww.Pair;x.Scalar=yw.Scalar;x.YAMLMap=bw.YAMLMap;x.YAMLSeq=Nw.YAMLSeq;x.CST=kw;x.Lexer=Sw.Lexer;x.LineCounter=Ew.LineCounter;x.Parser=Pw.Parser;x.parse=wi.parse;x.parseAllDocuments=wi.parseAllDocuments;x.parseDocument=wi.parseDocument;x.stringify=wi.stringify;x.visit=ef.visit;x.visitAsync=ef.visitAsync});import yi from"path";function Rw(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||yi.posix.isAbsolute(r)||yi.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be a project-relative path`);if(r===".")return[];let n=r.replaceAll("\\","/").split("/");if(n.some(i=>i===".."))throw new Error(`${e} must stay inside the project root`);if(n.some(i=>i===""||i==="."))throw new Error(`${e} must not contain empty or dot path segments`);return n}function Ht(t){let e=Rw(t,"native.artifact_root");return e.length===0?".":e.join("/")}function nf(t,e="docs"){let r=t??e;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function zt(t,e,r=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim().replaceAll("\\","/");if(n.length===0||yi.posix.isAbsolute(n)||yi.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be relative to its declared path base`);let i=n.split("/");if(i.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(i.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(n))throw new Error(`${e} cannot contain wildcards`);return i.join("/")}function Vt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function af(t,e,r){let n=t??e;if(n!=="en"&&n!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return n}function ki(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>bi)throw new Error(`${e} exceeds ${bi} characters`);let r=0;for(let n=0;n<t.length;n+=1)t[n]==="?"?r+=1:t[n]==="*"&&(r+=1,t[n+1]==="*"&&(n+=1));if(r>Ni)throw new Error(`${e} contains more than ${Ni} wildcard tokens`);return t}function tf(t,e,r){if(t===void 0)return[...r];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(n=>ki(n,e)))].sort((n,i)=>n.localeCompare(i,"en"))}function os(t,e,r){let n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${r} must be a positive integer`);return n}function Aw(t){if(t===void 0)return{...Ee,include:[...Ee.include],exclude:[...Ee.exclude]};let e=Vt(t,"native.snapshot");return{include:tf(e.include,"native.snapshot.include",Ee.include),exclude:tf(e.exclude,"native.snapshot.exclude",Ee.exclude),max_files:os(e.max_files,Ee.max_files,"native.snapshot.max_files"),max_total_bytes:os(e.max_total_bytes,Ee.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:os(e.max_duration_ms,Ee.max_duration_ms,"native.snapshot.max_duration_ms")}}function Tw(t){if(t===void 0)return;let e=Vt(t,"native.pending_root_move"),r=e.id,n=e.from_artifact_root,i=e.to_artifact_root,a=e.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof i!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let s=Vt(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:Ht(n),toArtifactRoot:Ht(i),stage:a,...o?{cleanup:o}:{}}}function Iw(t,e={}){let r=Vt(t,"native"),n=r.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let i=r.clarification_mode??"batch";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??rf;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Tw(r.pending_root_move);return{artifact_root:Ht(n),language:af(r.language,"en","native.language"),clarification_mode:i,archive_confirmation:a,max_verify_failures:o,snapshot:Aw(r.snapshot),...s?{pending_root_move:s}:{}}}function jw(t){let e=Vt(t,"classic"),r=e.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let n=e.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let i=e.auto_transition??!0;if(typeof i!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:nf(e.artifact_layout),language:af(e.language,"zh-CN","classic.language"),context_compression:r,review_mode:n,auto_transition:i}}function Ow(t){let r=Vt(t,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((n,i)=>zt(n,`hook.allow_paths[${i}]`)))]}}function $w(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function Lw(t,e,r,n,i,a){let o=t.schema!==void 0;if(!(o||t.default_workflow!==void 0||t.workflows!==void 0||!a.allowPartialProject&&t.native!==void 0)||a.allowPartialProject&&!o)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let c=t.workflows??[t.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(l.includes("native")&&!r)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:l,ambient_resume:i,...e?{hook:e}:{},...r?{native:r}:{},...n?{classic:n}:{}}}function Gt(t,e={}){let r=(0,ss.parseDocument)(t,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let n=r.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let i=n,a=$w(i.ambient_resume),o=i.hook===void 0?void 0:Ow(i.hook),s=i.native===void 0?void 0:Iw(i.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),c=i.classic===void 0?void 0:jw(i.classic),l=Lw(i,o,s,c,a,{allowPartialProject:e.allowPartialProject??!1});return{value:i,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}var ss,qr,bi,Ni,rf,Cw,xw,_w,Ee,Pe=L(()=>{"use strict";ss=ze(Le(),1),qr=64*1024,bi=1024,Ni=64,rf=5,Cw=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],xw=["**/.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"],_w=[...Cw,...xw].sort((t,e)=>t.localeCompare(e,"en")),Ee={include:["**/*"],exclude:[..._w],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function rt(t){return t!==0&&t!==0n&&t!=="0"}function ie(t,e){return rt(t.dev)&&rt(e.dev)&&rt(t.ino)&&rt(e.ino)}function R(t,e){let r=rt(t.dev)&&rt(e.dev);if(r&&t.dev!==e.dev)return!1;let n=rt(t.ino)&&rt(e.ino);return n&&t.ino!==e.ino?!1:r&&n?!0:t.birthtime===e.birthtime}var zr=L(()=>{"use strict"});import{constants as Ei,promises as wt}from"fs";function ds(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function cf(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Gr(t){return{dev:t.dev,ino:t.ino,birthtime:ds(t)}}function Pi(t,e){let r=Gr(t),n=Gr(e);return ie(r,n)?R(r,n):R(r,n)&&ds(t)===ds(e)&&cf(t)===cf(e)&&t.size===e.size}async function Yt(t,e,r={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let n=r.label??"file",i=r.bigint===!0,a=await wt.lstat(t,{bigint:i});if(!a.isFile()||a.isSymbolicLink())throw new Ce("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new Ce("too-large",`${n} exceeds ${e} bytes`);let o=await wt.realpath(t);await r.verify?.("pre-open",{realPath:o,identity:Gr(a)});let s=process.platform==="win32"?Ei.O_RDONLY:Ei.O_RDONLY|Ei.O_NOFOLLOW|Ei.O_NONBLOCK,c;try{c=await wt.open(t,s)}catch(l){throw l.code==="ELOOP"?new Ce("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:i}),wt.lstat(t,{bigint:i}),wt.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!Pi(a,l)||!Pi(a,u))throw new Ce("changed",`${n} changed while opening`);await r.verify?.("post-open",{realPath:f,identity:Gr(l)}),await r.hooks?.afterOpen?.();let d=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let b=e+1-h,{bytesRead:k}=await c.read(v,0,Math.min(v.length,b),null);if(k===0)break;if(h+=k,h>e)throw new Ce("too-large",`${n} exceeds ${e} bytes`);d.push(Buffer.from(v.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[p,m,y]=await Promise.all([c.stat({bigint:i}),wt.lstat(t,{bigint:i}),wt.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||y!==o||!Pi(a,p)||!Pi(a,m))throw new Ce("changed",`${n} changed while reading`);return await r.verify?.("post-read",{realPath:y,identity:Gr(p)}),{bytes:Buffer.concat(d,h),stat:p,realPath:y}}finally{await c.close()}}var Ce,Ci=L(()=>{"use strict";zr();Ce=class extends Error{reason;constructor(e,r,n){super(r,n),this.name="RaceSafeReadError",this.reason=e}}});import{promises as xi}from"fs";import nt from"path";function Vw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function ps(t,e){let r=nt.relative(t,e);return r===""||!nt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${nt.sep}`)}async function lf(t,e){let r=nt.resolve(t),n=await xi.lstat(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return xi.realpath(r)}async function uf(t,e,r,n){let i=t;for(let a=0;a<r.length;a++){i=nt.join(i,r[a]);let o;try{o=await xi.lstat(i)}catch(u){if(Vw(u))return{exists:!1,kind:"missing"};throw u}let s=nt.relative(t,i).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${n.label} ancestor ${s} must be a real directory`);if(c&&(n.expected==="file"&&!o.isFile()||n.expected==="directory"&&!o.isDirectory()||n.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let l=await xi.realpath(i);if(!ps(e,l))throw new Error(`${n.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 Y(t,e,r){let n=zt(e,r.label),i=nt.resolve(t),a=await lf(i,r.label),o=n.split("/"),s=nt.resolve(i,...o);if(!ps(i,s))throw new Error(`${r.label} must stay inside the project root`);let c=await uf(i,a,o,r);return{projectRoot:i,target:s,relative:n,exists:c.exists,kind:c.kind}}async function ae(t,e,r,n){let i=await Y(t,e,{label:n.label,expected:"file"});if(!i.exists){let o=new Error(`${n.label} does not exist`);throw o.code="ENOENT",o}let a=await lf(i.projectRoot,n.label);return Yt(i.target,r,{...n,verify:async(o,s)=>{if(!ps(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await uf(i.projectRoot,a,i.relative.split("/"),{label:n.label,expected:"file"})}})}var xe=L(()=>{"use strict";Ci();Pe()});import{createHash as zw}from"crypto";function Gw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function yt(t,e={}){return(await Jr(t,e)).document}async function Kw(t){try{return(await ae(t,Kr,qr,{label:Kr})).bytes}catch(e){if(Gw(e))return null;throw e}}function Jw(t){return t?{exists:!0,sha256:zw("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Jr(t,e={}){let r=await Kw(t);return{document:r?Gt(r.toString("utf8"),e):null,identity:Jw(r)}}async function Ur(t){return(await yt(t))?.config??null}var Kr,it=L(()=>{"use strict";Pe();xe();Kr=".comet/config.yaml"});import{randomUUID as Uw}from"crypto";import{constants as Yw,promises as O}from"fs";import M from"path";async function hs(t,e){try{return await O.link(t,e),{linked:!0}}catch(r){let n=r.code;if(n!=="ENOTSUP"&&n!=="EOPNOTSUPP")throw r}return await O.copyFile(t,e,Yw.COPYFILE_EXCL),{linked:!1}}function Xt(t,e){let r=M.relative(t,e);return r===""||!M.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${M.sep}`)}function Ri(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Xw(t,e){return R(t,Ri(e))}function _i(t,e){let r=Ri(t),n=Ri(e);return ie(r,n)?R(r,n):R(r,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Ai(t){let e=await O.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await O.realpath(t),...Ri(e)}}async function at(t){for(let e of t){let r=await O.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!Xw(e,r)||await O.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function Qw(t,e){let r=M.resolve(t),n=M.resolve(e);if(!Xt(r,n))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let i=[await Ai(r)],a=M.relative(r,n).split(M.sep).filter(Boolean),o=r;for(let s of a){await at(i),o=M.join(o,s);try{await O.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Ai(o);if(!Xt(i[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);i.push(c)}return await at(i),i}async function Zw(t,e){let r=M.resolve(t),n=M.resolve(e);if(!Xt(r,n))throw new Error(`Contained file parent is outside its managed root: ${e}`);let i=[await Ai(r)],a=M.relative(r,n).split(M.sep).filter(Boolean),o=r;for(let s of a){o=M.join(o,s);try{let c=await Ai(o);if(!Xt(i[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);i.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await at(i),i}async function ff(t){let e;try{e=await O.open(t,"r"),await e.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await e?.close()}}async function ey(t,e,r){let n=M.dirname(t),i=await Qw(r.containedRoot,n),a=M.join(n,`.${M.basename(t)}.${Uw()}.tmp`),o,s;try{await r.beforeTemporaryOpen?.(),o=await O.open(a,"wx"),s=await o.stat();let[c,l]=await Promise.all([O.lstat(a),O.realpath(a)]);if(await at(i),!c.isFile()||c.isSymbolicLink()||!_i(s,c)||!Xt(i[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!_i(s,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await r.beforeCommit?.(),await at(i);let u=await O.lstat(a);if(!u.isFile()||u.isSymbolicLink()||!_i(u,s))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(await hs(a,t),await O.unlink(a)):await O.rename(a,t),await ff(n)}catch(c){await o?.close();try{await at(i),await O.rm(a,{force:!0})}catch{}throw c}}async function _e(t,e,r){await ey(t,e,r)}async function ms(t,e){let r=M.dirname(t),n=await Zw(e.containedRoot,r);if(!n)return!1;let i,a;try{i=await O.lstat(t),a=await O.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!i.isFile()||i.isSymbolicLink()||!Xt(n[0].realPath,a))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await at(n);let[o,s]=await Promise.all([O.lstat(t),O.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!_i(i,o)||s!==a)throw new Error("Contained file removal target changed before removal");return await O.unlink(t),await at(n),await ff(r),!0}var ot=L(()=>{"use strict";zr()});var bC,gs=L(()=>{"use strict";ot();it();xe();bC=16*1024});var Ii=L(()=>{"use strict";ot();Pe();it();xe();gs()});async function Pf(t){if(Xr!==null)return t();Xr={entries:new Map};try{return await t()}finally{Xr=null}}function Cf(t,e){let r=t;for(let n of e)r+="\0"+(typeof n=="string"?n:JSON.stringify(n));return r}function X(t,e){return(...r)=>{let n=Xr;if(n===null)return e(...r);let i=Cf(`async:${t}`,r),a=n.entries.get(i);if(a)return a.value;let o=e(...r).catch(s=>{throw n.entries.delete(i),s});return n.entries.set(i,{value:o}),o}}function ks(t,e){return(...r)=>{let n=Xr;if(n===null)return e(...r);let i=Cf(`sync:${t}`,r),a=n.entries.get(i);if(a)return a.value;let o=e(...r);return n.entries.set(i,{value:o}),o}}var Xr,Be=L(()=>{"use strict";Xr=null});import z from"path";function Af(t,e){let r=z.relative(t,e);return r===""||!z.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${z.sep}`)}function Py(t,e){let r=z.isAbsolute(e)?z.resolve(e):z.resolve(t,e),n=z.relative(z.resolve(t),r);return n===""||z.isAbsolute(n)||n===".."||n.startsWith(`..${z.sep}`)?null:n.replaceAll("\\","/")}function Tf(t){return process.platform==="win32"?t.toLowerCase():t}async function er(t,e,r=[]){let n=z.isAbsolute(e)?z.resolve(e):z.resolve(t,e),i=z.resolve(t);if(!Af(i,n)||r.some(c=>Af(z.resolve(c),n)))return null;let a=Py(t,e);if(!a)return null;let s=(await Ey(t)).allow_paths.find(c=>{let l=Tf(a),u=Tf(c);return l===u||l.startsWith(`${u}/`)});return s?`${a} (configured Hook allow path: ${s})`:null}var Ey,Li=L(()=>{"use strict";Be();it();Ey=X("hookWritePolicy",async t=>(await Ur(t))?.hook??{allow_paths:[]})});var Wi=L(()=>{"use strict"});var Lf=L(()=>{"use strict"});var _s=L(()=>{"use strict";Wi()});var Df=L(()=>{"use strict";Wi();_s()});var Vy,Mf=L(()=>{"use strict";Vy=ze(Le(),1);ot();Pe();xe()});var xx,Wf=L(()=>{"use strict";ot();xe();xx=4*1024*1024});var qf=L(()=>{"use strict";Wi();ot();Lf();Df();Pe();Mf();xe();it();Ii();Wf();Li();gs();_s()});import{TextDecoder as Gy}from"util";function Ff(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Ky(t,e){try{return new Gy("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e} is not valid UTF-8`,{cause:r})}}async function Rs(t,e,r,n,i={}){try{let a=await ae(t,e,r,{label:n,hooks:i.hooks});return{result:a,text:Ky(a,n)}}catch(a){let o=a.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw a}}async function Hf(t,e,r,n,i={}){return(await Rs(t,e,r,n,i))?.text??null}async function Vf(t,e,r,n,i,a={}){if(Buffer.byteLength(r,"utf8")>n)throw new Error(`${i} exceeds ${n} bytes`);let o=await Rs(t,e,n,i),s=await Y(t,e,{label:i,expected:"file"});await _e(s.target,r,{containedRoot:s.projectRoot,beforeCommit:async()=>{await a.beforeCommit?.();let c=await Rs(t,e,n,i);if(!(!o&&!c)){if(!o||!c)throw new Error(`${i} changed before commit`);if(o.result.realPath!==c.result.realPath||!R(Ff(o.result.stat),Ff(c.result.stat))||o.text!==c.text)throw new Error(`${i} changed before commit`)}}})}async function zf(t,e,r,n={}){let i=await Y(t,e,{label:r,expected:"file"});return i.exists?ms(i.target,{containedRoot:i.projectRoot,beforeRemove:n.beforeRemove}):!1}var Gf=L(()=>{"use strict";qf();zr()});var Xf={};Xp(Xf,{RUN_STATE_FILE:()=>qi,applyRunStateToDocument:()=>Jf,readRunState:()=>As,removeRunState:()=>Yf,runStateFromDocument:()=>rn,writeRunState:()=>Ts});import Jy from"path";function tn(t,e){let r=t[e];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return r}function en(t,e){let r=tn(t,e);if(Jy.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return r}function Uy(t){let e=t.run_retries??"{}",r;try{r=typeof e=="string"?JSON.parse(e):e}catch(n){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:n})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let n of Object.values(r))if(!Number.isInteger(n)||Number(n)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function rn(t){if(!t.run_id)return null;let e=tn(t,"run_id"),r=tn(t,"skill"),n=tn(t,"skill_version"),i=tn(t,"skill_hash"),a=en(t,"pending_ref"),o=en(t,"trajectory_ref"),s=en(t,"context_ref"),c=en(t,"artifacts_ref"),l=en(t,"checkpoint_ref"),u=Number(t.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:r,skillVersion:n,skillHash:i,orchestration:t.orchestration,currentStep:Kf(t,"current_step"),iteration:u,pending:Kf(t,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:Uy(t)}}function Jf(t,e){e?t.run_id=e.runId:delete t.run_id}function Yy(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function Xy(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return rn(e)}async function As(t,e={}){let r=await Hf(t,qi,Uf,"Run state",e);if(r===null)return null;let n=JSON.parse(r);return Xy(n)}async function Ts(t,e,r={}){await Vf(t,qi,JSON.stringify(Yy(e),null,2),Uf,"Run state",r)}async function Yf(t,e={}){await zf(t,qi,"Run state",e)}var Kf,qi,Uf,nn=L(()=>{"use strict";Gf();Kf=(t,e)=>{let r=t[e];return r==null?null:String(r)};qi=".comet/run-state.json",Uf=256*1024});import zp from"path";import{realpathSync as Hp}from"fs";import{promises as Vp}from"fs";import{fileURLToPath as gE,pathToFileURL as vE}from"url";Pe();import{existsSync as of,promises as gt}from"fs";import _ from"path";import Dw from"os";var us=".comet/config.yaml",Bw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function cs(t){try{return await gt.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Mw(t){try{let e=await gt.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Jt(t,e){let r=_.relative(t,e);return r===""||!_.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_.sep}`)}async function Kt(t){let e=[],r=t;for(;!await cs(r);){let i=_.dirname(r);if(i===r)break;e.push(_.basename(r)),r=i}let n=await gt.realpath(r);return _.resolve(n,...e.reverse())}async function ls(t){try{return(await gt.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Fr(t){let e=_.resolve(t);try{(await gt.stat(e)).isDirectory()||(e=_.dirname(e))}catch(i){if(i.code!=="ENOENT")throw i}let r=e,n=_.resolve(Dw.homedir());for(;;){if(!(e===n&&r!==n)){let o=_.join(e,...us.split("/")),s=e===r||await Mw(o);if(await cs(o)&&s)return e}if(await cs(_.join(e,".git")))return e;let a=_.dirname(e);if(a===e)return r;e=a}}function fs(t){return Ht(t)}async function Ww(t,e){let r=fs(e),n=_.resolve(t,...r.split("/")),i=await gt.realpath(t),a=await Kt(n);if(!Jt(i,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function Hr(t,e){let r=fs(e),n=await Ww(t,r),i=_.join(n,"comet");if(await ls(i))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Kt(n),Kt(i)]);if(!Jt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=_.resolve(t),c=_.join(s,".comet","runtime","native");if(await ls(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([gt.realpath(s),Kt(c)]);if(!Jt(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:_.join(t,...us.split("/")),artifactRoot:n,artifactRootRef:r,nativeRoot:i,specsDir:_.join(i,"specs"),changesDir:_.join(i,"changes"),archiveDir:_.join(i,"archive"),runtimeDir:c,changesRuntimeDir:_.join(c,"changes"),locksDir:_.join(c,"locks"),transactionsDir:_.join(c,"transactions")}}function sf(t){if(!Bw.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Si(t,e){sf(e);let r=_.join(t.changesRuntimeDir,e);if(!pe(t.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function qw(t,e){sf(e);let r=_.join(t.changesDir,e,"runtime");if(!pe(t.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function vt(t,e){let r=Si(t,e);if(of(r))return r;let n=qw(t,e);return of(n)?n:r}function Ut(t,e){let r=_.resolve(e);if(pe(t.runtimeDir,r))return t.runtimeDir;if(pe(t.nativeRoot,r))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function pe(t,e){return Jt(_.resolve(t),_.resolve(e))}async function F(t,e){let r=_.resolve(t),n=_.resolve(e);if(!Jt(r,n))throw new Error(`Path is outside the Native root: ${e}`);if(await ls(r))throw new Error(`Native root must not be a symbolic link: ${t}`);let[i,a]=await Promise.all([Kt(r),Kt(n)]);if(!Jt(i,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}import{promises as hf}from"fs";import I from"path";import{promises as Fw}from"fs";async function Vr(t){try{return await Fw.access(t),!0}catch(e){if(Hw(e))return!1;throw e}}function Hw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}Pe();it();Ii();xe();var st=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},pf=".comet/config.yaml";function mf(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function gf(t){await Y(t,pf,{label:pf,expected:"file"})}function vf(t,e){let r=I.resolve(t),n=e==="docs"?I.join(r,"docs"):r,i=I.join(n,"openspec"),a=I.join(r,"docs","superpowers");return{projectRoot:r,artifactLayout:e,openSpecBase:n,openSpecRoot:i,changesDir:I.join(i,"changes"),archiveDir:I.join(i,"changes","archive"),specsDir:I.join(i,"specs"),superpowersRoot:a,superpowersSpecsDir:I.join(a,"specs"),superpowersPlansDir:I.join(a,"plans"),superpowersReportsDir:I.join(a,"reports")}}async function ay(t){await gf(t);let e=await yt(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new st;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new st("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function oy(t,e){return vf(t,e??await ay(t))}async function sy(t){try{return await hf.lstat(t),!0}catch(e){if(mf(e))return!1;throw e}}async function cy(t,e){let r=await oy(t,e),n=r.artifactLayout==="legacy"?"docs":"legacy",i=vf(t,n).openSpecRoot,[a,o]=await Promise.all([Y(r.projectRoot,H(r.projectRoot,r.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),sy(i)]),s=a.exists;return{paths:r,configuredRootExists:s,alternateRoot:i,alternateRootExists:o,dualRoots:s&&o}}async function ly(t){let e=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let r of e){let n=H(t.projectRoot,r);await Y(t.projectRoot,n,{label:`Classic managed physical path ${n}`,expected:"directory"})}}async function De(t,e){let r=await cy(t,e);if(await ly(r.paths),!r.configuredRootExists){let n=H(r.paths.projectRoot,r.paths.openSpecRoot),i=H(r.paths.projectRoot,r.alternateRoot);throw new st(`Configured Classic OpenSpec root is missing: ${n} (alternate ${i} is ${r.alternateRootExists?"present":"missing"})`)}return r.paths}async function ji(t,e){let r=I.join(I.resolve(t),".comet","classic-root-move.json");if(await Vr(r))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let n=await De(t,e);if(!await Vr(n.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${H(n.projectRoot,n.openSpecRoot)}`);return n}async function wf(t){let e=I.resolve(t),r=null;try{(await hf.lstat(e)).isDirectory()||(e=I.dirname(e))}catch(n){if(!mf(n))throw n}for(;;){I.basename(e)==="openspec"&&(r=I.dirname(e));let n=I.join(e,".comet","config.yaml"),i=!1;if(await Vr(n))try{await gf(e);let o=(await yt(e))?.value;i=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(i||await Vr(I.join(e,".git")))return e;let a=I.dirname(e);if(a===e)return r??I.resolve(t);e=a}}function H(t,e){return I.relative(I.resolve(t),e).replaceAll("\\","/")}import{readFileSync as uy}from"fs";import yf from"path";var fy=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),dy=new Set(["glob","grep","listfiles","read","readfile","search","view"]),Nf=["file_path","filePath","path","target_file","targetFile"],kf=["file_paths","filePaths","paths","files","targets"],Sf=["operations","edits"],py=["patch","diff","patchText","patch_text","changes"],ys=new Set(["claude","codex","windsurf","github-copilot","gemini","amazon-q","qwen","kiro","codebuddy","workbuddy","qoder","trae","trae-cn"]);function bs(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function bf(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function hy(t){for(let e of["tool_name","toolName","tool","name"]){let r=t[e];if(typeof r=="string"&&r.trim())return r.trim()}return null}function my(t){for(let e of["cwd","working_directory","workspaceRoot"]){let r=t[e];if(!(typeof r!="string"||!r.trim()||!yf.isAbsolute(r.trim())))return yf.resolve(r.trim())}}function gy(t){if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return t;try{return JSON.parse(e)}catch{return t}}function vy(t){for(let e of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(t[e]!==void 0)return gy(t[e]);return t}function ws(t){let e=[],r=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let n of r)for(let i of t.matchAll(n)){let a=i[1]?.trim();a&&a!=="/dev/null"&&e.push(a)}return e}function bt(t,e){if(typeof e=="string"){let r=e.trim();r&&t.push(r);return}if(Array.isArray(e)){for(let r of e)bt(t,r);return}if(bs(e)){for(let r of Nf)bt(t,e[r]);for(let r of kf)bt(t,e[r]);for(let r of Sf)bt(t,e[r])}}function wy(t,e){let r=[],n=[e,t].filter(bs);for(let i of n){for(let a of Nf)bt(r,i[a]);for(let a of kf)bt(r,i[a]);for(let a of Sf)bt(r,i[a]);for(let a of py){let o=i[a];typeof o=="string"&&r.push(...ws(o))}}return typeof e=="string"&&r.push(...ws(e)),[...new Set(r)]}function Yr(t,e){if(e?.trim())return{intent:"write",targets:[e.trim()],toolName:null};if(!t.trim())return{intent:"unknown",targets:[],toolName:null};let r;try{r=JSON.parse(t)}catch{let o=ws(t);return o.length>0?{intent:"write",targets:[...new Set(o)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!bs(r))return{intent:"unknown",targets:[],toolName:null};let n=hy(r),i=wy(r,vy(r)),a=my(r);return n&&fy.has(bf(n))?{intent:i.length>0?"write":"unknown",targets:i,toolName:n,...a?{cwd:a}:{}}:n&&dy.has(bf(n))?{intent:"non-write",targets:[],toolName:n,...a?{cwd:a}:{}}:n?{intent:"unknown",targets:i,toolName:n,...a?{cwd:a}:{}}:{intent:i.length>0?"write":"unknown",targets:i,toolName:null,...a?{cwd:a}:{}}}function Ns(){let t=process.env.FILE_PATH;if(t?.trim()||process.stdin.isTTY)return Yr("",t);try{return Yr(uy(0,"utf8"),t)}catch{return Yr("",t)}}function Ef(t,e){return ys.has(t)?t==="github-copilot"?{exitCode:0,stdout:e.allowed?`{}
|
|
142
|
+
`,r)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=vi(e),n=Ht(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=vi(e),n=Ht(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,r){return this.type!=="comment"||this.indent<=r?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){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:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ju.Parser=rs});var ef=w(Wr=>{"use strict";var Yu=Ho(),dw=Ir(),qr=$r(),pw=qa(),hw=P(),mw=ts(),Xu=ns();function Qu(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new mw.LineCounter||null,prettyErrors:e}}function gw(t,e={}){let{lineCounter:r,prettyErrors:n}=Qu(e),i=new Xu.Parser(r?.addNewLine),a=new Yu.Composer(e),o=Array.from(a.compose(i.parse(t)));if(n&&r)for(let s of o)s.errors.forEach(qr.prettifyError(t,r)),s.warnings.forEach(qr.prettifyError(t,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Zu(t,e={}){let{lineCounter:r,prettyErrors:n}=Qu(e),i=new Xu.Parser(r?.addNewLine),a=new Yu.Composer(e),o=null;for(let s of a.compose(i.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new qr.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(o.errors.forEach(qr.prettifyError(t,r)),o.warnings.forEach(qr.prettifyError(t,r))),o}function vw(t,e,r){let n;typeof e=="function"?n=e:r===void 0&&e&&typeof e=="object"&&(r=e);let i=Zu(t,r);if(!i)return null;if(i.warnings.forEach(a=>pw.warn(i.options.logLevel,a)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},r))}function ww(t,e,r){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:r===void 0&&e&&(r=e),typeof r=="string"&&(r=r.length),typeof r=="number"){let i=Math.round(r);r=i<1?void 0:i>8?{indent:8}:{indent:i}}if(t===void 0){let{keepUndefined:i}=r??e??{};if(!i)return}return hw.isDocument(t)&&!n?t.toString(r):new dw.Document(t,n,r).toString(r)}Wr.parse=vw;Wr.parseAllDocuments=gw;Wr.parseDocument=Zu;Wr.stringify=ww});var $e=w(x=>{"use strict";var yw=Ho(),bw=Ir(),Nw=So(),is=$r(),kw=gr(),et=P(),Sw=Je(),Ew=j(),Pw=Xe(),Cw=Qe(),xw=mi(),_w=Zo(),Rw=ts(),Aw=ns(),yi=ef(),tf=dr();x.Composer=yw.Composer;x.Document=bw.Document;x.Schema=Nw.Schema;x.YAMLError=is.YAMLError;x.YAMLParseError=is.YAMLParseError;x.YAMLWarning=is.YAMLWarning;x.Alias=kw.Alias;x.isAlias=et.isAlias;x.isCollection=et.isCollection;x.isDocument=et.isDocument;x.isMap=et.isMap;x.isNode=et.isNode;x.isPair=et.isPair;x.isScalar=et.isScalar;x.isSeq=et.isSeq;x.Pair=Sw.Pair;x.Scalar=Ew.Scalar;x.YAMLMap=Pw.YAMLMap;x.YAMLSeq=Cw.YAMLSeq;x.CST=xw;x.Lexer=_w.Lexer;x.LineCounter=Rw.LineCounter;x.Parser=Aw.Parser;x.parse=yi.parse;x.parseAllDocuments=yi.parseAllDocuments;x.parseDocument=yi.parseDocument;x.stringify=yi.stringify;x.visit=tf.visit;x.visitAsync=tf.visitAsync});import Vt from"path";function $w(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||Vt.posix.isAbsolute(r)||Vt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be a project-relative path`);if(r===".")return[];let n=r.replaceAll("\\","/").split("/");if(n.some(i=>i===".."))throw new Error(`${e} must stay inside the project root`);if(n.some(i=>i===""||i==="."))throw new Error(`${e} must not contain empty or dot path segments`);return n}function zt(t){let e=$w(t,"native.artifact_root");return e.length===0?".":e.join("/")}function of(t,e="docs"){let r=t??e;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Gt(t,e,r=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim().replaceAll("\\","/");if(n.length===0||Vt.posix.isAbsolute(n)||Vt.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be relative to its declared path base`);let i=n.split("/");if(i.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(i.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(n))throw new Error(`${e} cannot contain wildcards`);return i.join("/")}function tt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function sf(t,e,r){let n=t??e;if(n!=="en"&&n!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return n}function ki(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>bi)throw new Error(`${e} exceeds ${bi} characters`);let r=0;for(let n=0;n<t.length;n+=1)t[n]==="?"?r+=1:t[n]==="*"&&(r+=1,t[n+1]==="*"&&(n+=1));if(r>Ni)throw new Error(`${e} contains more than ${Ni} wildcard tokens`);return t}function nf(t,e,r){if(t===void 0)return[...r];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(n=>ki(n,e)))].sort((n,i)=>n.localeCompare(i,"en"))}function as(t,e,r){let n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${r} must be a positive integer`);return n}function Lw(t){if(t===void 0)return{...Se,include:[...Se.include],exclude:[...Se.exclude]};let e=tt(t,"native.snapshot");return{include:nf(e.include,"native.snapshot.include",Se.include),exclude:nf(e.exclude,"native.snapshot.exclude",Se.exclude),max_files:as(e.max_files,Se.max_files,"native.snapshot.max_files"),max_total_bytes:as(e.max_total_bytes,Se.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:as(e.max_duration_ms,Se.max_duration_ms,"native.snapshot.max_duration_ms")}}function Dw(t){if(t===void 0)return;let e=tt(t,"native.pending_root_move"),r=e.id,n=e.from_artifact_root,i=e.to_artifact_root,a=e.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof i!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let s=tt(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:zt(n),toArtifactRoot:zt(i),stage:a,...o?{cleanup:o}:{}}}function Bw(t){if(t===void 0)return;let e=tt(t,"native.finish");if(e.pull_request===void 0)return{};let r=tt(e.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let n=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Vt.posix.isAbsolute(n[0])||Vt.win32.isAbsolute(n[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let i=r.timeout_ms??Tw;if(!Number.isSafeInteger(i)||i<1||i>rf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${rf}`);return{pull_request:{provider:"repository-command",command:n,timeout_ms:i}}}function Mw(t,e={}){let r=tt(t,"native"),n=r.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let i=r.clarification_mode??"batch";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??af;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Dw(r.pending_root_move),c=Bw(r.finish);return{artifact_root:zt(n),language:sf(r.language,"en","native.language"),clarification_mode:i,archive_confirmation:a,max_verify_failures:o,snapshot:Lw(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function qw(t){let e=tt(t,"classic"),r=e.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let n=e.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let i=e.auto_transition??!0;if(typeof i!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:of(e.artifact_layout),language:sf(e.language,"zh-CN","classic.language"),context_compression:r,review_mode:n,auto_transition:i}}function Ww(t){let r=tt(t,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((n,i)=>Gt(n,`hook.allow_paths[${i}]`)))]}}function Fw(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function Hw(t,e,r,n,i,a){let o=t.schema!==void 0;if(!(o||t.default_workflow!==void 0||t.workflows!==void 0||!a.allowPartialProject&&t.native!==void 0)||a.allowPartialProject&&!o)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let c=t.workflows??[t.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(l.includes("native")&&!r)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:l,ambient_resume:i,...e?{hook:e}:{},...r?{native:r}:{},...n?{classic:n}:{}}}function Ut(t,e={}){let r=(0,os.parseDocument)(t,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let n=r.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let i=n,a=Fw(i.ambient_resume),o=i.hook===void 0?void 0:Ww(i.hook),s=i.native===void 0?void 0:Mw(i.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),c=i.classic===void 0?void 0:qw(i.classic),l=Hw(i,o,s,c,a,{allowPartialProject:e.allowPartialProject??!1});return{value:i,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}var os,Fr,bi,Ni,af,Tw,rf,Iw,jw,Ow,Se,Ee=L(()=>{"use strict";os=Ve($e(),1),Fr=64*1024,bi=1024,Ni=64,af=5,Tw=12e4,rf=6e5,Iw=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/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/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],jw=["**/.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"],Ow=[...Iw,...jw].sort((t,e)=>t.localeCompare(e,"en")),Se={include:["**/*"],exclude:[...Ow],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function rt(t){return t!==0&&t!==0n&&t!=="0"}function nt(t,e){return rt(t.dev)&&rt(e.dev)&&rt(t.ino)&&rt(e.ino)}function A(t,e){let r=rt(t.dev)&&rt(e.dev);if(r&&t.dev!==e.dev)return!1;let n=rt(t.ino)&&rt(e.ino);return n&&t.ino!==e.ino?!1:r&&n?!0:t.birthtime===e.birthtime}var Gr=L(()=>{"use strict"});import{constants as Ei,promises as yt}from"fs";function fs(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function uf(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Ur(t){return{dev:t.dev,ino:t.ino,birthtime:fs(t)}}function Pi(t,e){let r=Ur(t),n=Ur(e);return nt(r,n)?A(r,n):A(r,n)&&fs(t)===fs(e)&&uf(t)===uf(e)&&t.size===e.size}async function Xt(t,e,r={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let n=r.label??"file",i=r.bigint===!0,a=await yt.lstat(t,{bigint:i});if(!a.isFile()||a.isSymbolicLink())throw new Pe("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new Pe("too-large",`${n} exceeds ${e} bytes`);let o=await yt.realpath(t);await r.verify?.("pre-open",{realPath:o,identity:Ur(a)});let s=process.platform==="win32"?Ei.O_RDONLY:Ei.O_RDONLY|Ei.O_NOFOLLOW|Ei.O_NONBLOCK,c;try{c=await yt.open(t,s)}catch(l){throw l.code==="ELOOP"?new Pe("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:i}),yt.lstat(t,{bigint:i}),yt.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!Pi(a,l)||!Pi(a,u))throw new Pe("changed",`${n} changed while opening`);await r.verify?.("post-open",{realPath:f,identity:Ur(l)}),await r.hooks?.afterOpen?.();let d=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let b=e+1-h,{bytesRead:k}=await c.read(v,0,Math.min(v.length,b),null);if(k===0)break;if(h+=k,h>e)throw new Pe("too-large",`${n} exceeds ${e} bytes`);d.push(Buffer.from(v.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[p,m,y]=await Promise.all([c.stat({bigint:i}),yt.lstat(t,{bigint:i}),yt.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||y!==o||!Pi(a,p)||!Pi(a,m))throw new Pe("changed",`${n} changed while reading`);return await r.verify?.("post-read",{realPath:y,identity:Ur(p)}),{bytes:Buffer.concat(d,h),stat:p,realPath:y}}finally{await c.close()}}var Pe,Ci=L(()=>{"use strict";Gr();Pe=class extends Error{reason;constructor(e,r,n){super(r,n),this.name="RaceSafeReadError",this.reason=e}}});import{promises as xi}from"fs";import it from"path";function Xw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function ds(t,e){let r=it.relative(t,e);return r===""||!it.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${it.sep}`)}async function ff(t,e){let r=it.resolve(t),n=await xi.lstat(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return xi.realpath(r)}async function df(t,e,r,n){let i=t;for(let a=0;a<r.length;a++){i=it.join(i,r[a]);let o;try{o=await xi.lstat(i)}catch(u){if(Xw(u))return{exists:!1,kind:"missing"};throw u}let s=it.relative(t,i).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${n.label} ancestor ${s} must be a real directory`);if(c&&(n.expected==="file"&&!o.isFile()||n.expected==="directory"&&!o.isDirectory()||n.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let l=await xi.realpath(i);if(!ds(e,l))throw new Error(`${n.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 Y(t,e,r){let n=Gt(e,r.label),i=it.resolve(t),a=await ff(i,r.label),o=n.split("/"),s=it.resolve(i,...o);if(!ds(i,s))throw new Error(`${r.label} must stay inside the project root`);let c=await df(i,a,o,r);return{projectRoot:i,target:s,relative:n,exists:c.exists,kind:c.kind}}async function ie(t,e,r,n){let i=await Y(t,e,{label:n.label,expected:"file"});if(!i.exists){let o=new Error(`${n.label} does not exist`);throw o.code="ENOENT",o}let a=await ff(i.projectRoot,n.label);return Xt(i.target,r,{...n,verify:async(o,s)=>{if(!ds(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await df(i.projectRoot,a,i.relative.split("/"),{label:n.label,expected:"file"})}})}var Ce=L(()=>{"use strict";Ci();Ee()});import{createHash as Qw}from"crypto";function Zw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function bt(t,e={}){return(await Jr(t,e)).document}async function ey(t){try{return(await ie(t,Kr,Fr,{label:Kr})).bytes}catch(e){if(Zw(e))return null;throw e}}function ty(t){return t?{exists:!0,sha256:Qw("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Jr(t,e={}){let r=await ey(t);return{document:r?Ut(r.toString("utf8"),e):null,identity:ty(r)}}async function Yr(t){return(await bt(t))?.config??null}var Kr,at=L(()=>{"use strict";Ee();Ce();Kr=".comet/config.yaml"});import{randomUUID as ry}from"crypto";import{constants as ny,promises as O}from"fs";import M from"path";async function hs(t,e){try{return await O.link(t,e),{linked:!0}}catch(r){let n=r.code;if(n!=="ENOTSUP"&&n!=="EOPNOTSUPP")throw r}return await O.copyFile(t,e,ny.COPYFILE_EXCL),{linked:!1}}function Qt(t,e){let r=M.relative(t,e);return r===""||!M.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${M.sep}`)}function _i(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function iy(t,e){return A(t,_i(e))}function ps(t,e){return A(_i(t),_i(e))}function pf(t,e){return ps(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Ri(t){let e=await O.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await O.realpath(t),..._i(e)}}async function ot(t){for(let e of t){let r=await O.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!iy(e,r)||await O.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function ay(t,e){let r=M.resolve(t),n=M.resolve(e);if(!Qt(r,n))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let i=[await Ri(r)],a=M.relative(r,n).split(M.sep).filter(Boolean),o=r;for(let s of a){await ot(i),o=M.join(o,s);try{await O.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Ri(o);if(!Qt(i[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);i.push(c)}return await ot(i),i}async function oy(t,e){let r=M.resolve(t),n=M.resolve(e);if(!Qt(r,n))throw new Error(`Contained file parent is outside its managed root: ${e}`);let i=[await Ri(r)],a=M.relative(r,n).split(M.sep).filter(Boolean),o=r;for(let s of a){o=M.join(o,s);try{let c=await Ri(o);if(!Qt(i[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);i.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await ot(i),i}async function hf(t){let e;try{e=await O.open(t,"r"),await e.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await e?.close()}}async function sy(t,e,r){let n=M.dirname(t),i=await ay(r.containedRoot,n),a=M.join(n,`.${M.basename(t)}.${ry()}.tmp`),o,s,c;try{await r.beforeTemporaryOpen?.(),o=await O.open(a,"wx"),s=await o.stat();let[l,u]=await Promise.all([O.lstat(a),O.realpath(a)]);if(await ot(i),!l.isFile()||l.isSymbolicLink()||!ps(s,l)||!Qt(i[0].realPath,u))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),c=await o.stat(),!ps(s,c))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await r.beforeCommit?.(),await ot(i);let f=await O.lstat(a);if(!f.isFile()||f.isSymbolicLink()||!c||!pf(f,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(await hs(a,t),await O.unlink(a)):await O.rename(a,t),await hf(n)}catch(l){await o?.close();try{await ot(i),await O.rm(a,{force:!0})}catch{}throw l}}async function xe(t,e,r){await sy(t,e,r)}async function ms(t,e){let r=M.dirname(t),n=await oy(e.containedRoot,r);if(!n)return!1;let i,a;try{i=await O.lstat(t),a=await O.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!i.isFile()||i.isSymbolicLink()||!Qt(n[0].realPath,a))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await ot(n);let[o,s]=await Promise.all([O.lstat(t),O.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!pf(i,o)||s!==a)throw new Error("Contained file removal target changed before removal");return await O.unlink(t),await ot(n),await hf(r),!0}var st=L(()=>{"use strict";Gr()});var _C,gs=L(()=>{"use strict";st();at();Ce();_C=16*1024});var Ti=L(()=>{"use strict";st();Ee();at();Ce();gs()});async function _f(t){if(Qr!==null)return t();Qr={entries:new Map};try{return await t()}finally{Qr=null}}function Rf(t,e){let r=t;for(let n of e)r+="\0"+(typeof n=="string"?n:JSON.stringify(n));return r}function X(t,e){return(...r)=>{let n=Qr;if(n===null)return e(...r);let i=Rf(`async:${t}`,r),a=n.entries.get(i);if(a)return a.value;let o=e(...r).catch(s=>{throw n.entries.delete(i),s});return n.entries.set(i,{value:o}),o}}function Ss(t,e){return(...r)=>{let n=Qr;if(n===null)return e(...r);let i=Rf(`sync:${t}`,r),a=n.entries.get(i);if(a)return a.value;let o=e(...r);return n.entries.set(i,{value:o}),o}}var Qr,De=L(()=>{"use strict";Qr=null});import z from"path";function jf(t,e){let r=z.relative(t,e);return r===""||!z.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${z.sep}`)}function Iy(t,e){let r=z.isAbsolute(e)?z.resolve(e):z.resolve(t,e),n=z.relative(z.resolve(t),r);return n===""||z.isAbsolute(n)||n===".."||n.startsWith(`..${z.sep}`)?null:n.replaceAll("\\","/")}function Of(t){return process.platform==="win32"?t.toLowerCase():t}async function tr(t,e,r=[]){let n=z.isAbsolute(e)?z.resolve(e):z.resolve(t,e),i=z.resolve(t);if(!jf(i,n)||r.some(c=>jf(z.resolve(c),n)))return null;let a=Iy(t,e);if(!a)return null;let s=(await Ty(t)).allow_paths.find(c=>{let l=Of(a),u=Of(c);return l===u||l.startsWith(`${u}/`)});return s?`${a} (configured Hook allow path: ${s})`:null}var Ty,$i=L(()=>{"use strict";De();at();Ty=X("hookWritePolicy",async t=>(await Yr(t))?.hook??{allow_paths:[]})});var Mi=L(()=>{"use strict"});var Mf=L(()=>{"use strict"});var Rs=L(()=>{"use strict";Mi()});var qf=L(()=>{"use strict";Mi();Rs()});var Xy,Ff=L(()=>{"use strict";Xy=Ve($e(),1);st();Ee();Ce()});var Dx,Hf=L(()=>{"use strict";st();Ce();Dx=4*1024*1024});var Vf=L(()=>{"use strict";Mi();st();Mf();qf();Ee();Ff();Ce();at();Ti();Hf();$i();gs();Rs()});import{TextDecoder as Zy}from"util";function zf(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function eb(t,e){try{return new Zy("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e} is not valid UTF-8`,{cause:r})}}async function As(t,e,r,n,i={}){try{let a=await ie(t,e,r,{label:n,hooks:i.hooks});return{result:a,text:eb(a,n)}}catch(a){let o=a.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw a}}async function Gf(t,e,r,n,i={}){return(await As(t,e,r,n,i))?.text??null}async function Uf(t,e,r,n,i,a={}){if(Buffer.byteLength(r,"utf8")>n)throw new Error(`${i} exceeds ${n} bytes`);let o=await As(t,e,n,i),s=await Y(t,e,{label:i,expected:"file"});await xe(s.target,r,{containedRoot:s.projectRoot,beforeCommit:async()=>{await a.beforeCommit?.();let c=await As(t,e,n,i);if(!(!o&&!c)){if(!o||!c)throw new Error(`${i} changed before commit`);if(o.result.realPath!==c.result.realPath||!A(zf(o.result.stat),zf(c.result.stat))||o.text!==c.text)throw new Error(`${i} changed before commit`)}}})}async function Kf(t,e,r,n={}){let i=await Y(t,e,{label:r,expected:"file"});return i.exists?ms(i.target,{containedRoot:i.projectRoot,beforeRemove:n.beforeRemove}):!1}var Jf=L(()=>{"use strict";Vf();Gr()});var ed={};rh(ed,{RUN_STATE_FILE:()=>qi,applyRunStateToDocument:()=>Xf,readRunState:()=>Ts,removeRunState:()=>Zf,runStateFromDocument:()=>nn,writeRunState:()=>Is});import tb from"path";function rn(t,e){let r=t[e];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return r}function tn(t,e){let r=rn(t,e);if(tb.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return r}function rb(t){let e=t.run_retries??"{}",r;try{r=typeof e=="string"?JSON.parse(e):e}catch(n){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:n})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let n of Object.values(r))if(!Number.isInteger(n)||Number(n)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function nn(t){if(!t.run_id)return null;let e=rn(t,"run_id"),r=rn(t,"skill"),n=rn(t,"skill_version"),i=rn(t,"skill_hash"),a=tn(t,"pending_ref"),o=tn(t,"trajectory_ref"),s=tn(t,"context_ref"),c=tn(t,"artifacts_ref"),l=tn(t,"checkpoint_ref"),u=Number(t.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:r,skillVersion:n,skillHash:i,orchestration:t.orchestration,currentStep:Yf(t,"current_step"),iteration:u,pending:Yf(t,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:rb(t)}}function Xf(t,e){e?t.run_id=e.runId:delete t.run_id}function nb(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function ib(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return nn(e)}async function Ts(t,e={}){let r=await Gf(t,qi,Qf,"Run state",e);if(r===null)return null;let n=JSON.parse(r);return ib(n)}async function Is(t,e,r={}){await Uf(t,qi,JSON.stringify(nb(e),null,2),Qf,"Run state",r)}async function Zf(t,e={}){await Kf(t,qi,"Run state",e)}var Yf,qi,Qf,an=L(()=>{"use strict";Jf();Yf=(t,e)=>{let r=t[e];return r==null?null:String(r)};qi=".comet/run-state.json",Qf=256*1024});import Yp from"path";import{realpathSync as Kp}from"fs";import{promises as Jp}from"fs";import{fileURLToPath as EE,pathToFileURL as PE}from"url";Ee();import{existsSync as cf,promises as vt}from"fs";import _ from"path";import Vw from"os";var ls=".comet/config.yaml",zw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function ss(t){try{return await vt.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Gw(t){try{let e=await vt.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Jt(t,e){let r=_.relative(t,e);return r===""||!_.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_.sep}`)}async function Kt(t){let e=[],r=t;for(;!await ss(r);){let i=_.dirname(r);if(i===r)break;e.push(_.basename(r)),r=i}let n=await vt.realpath(r);return _.resolve(n,...e.reverse())}async function cs(t){try{return(await vt.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Hr(t){let e=_.resolve(t);try{(await vt.stat(e)).isDirectory()||(e=_.dirname(e))}catch(i){if(i.code!=="ENOENT")throw i}let r=e,n=_.resolve(Vw.homedir());for(;;){if(!(e===n&&r!==n)){let o=_.join(e,...ls.split("/")),s=e===r||await Gw(o);if(await ss(o)&&s)return e}if(await ss(_.join(e,".git")))return e;let a=_.dirname(e);if(a===e)return r;e=a}}function us(t){return zt(t)}async function Uw(t,e){let r=us(e),n=_.resolve(t,...r.split("/")),i=await vt.realpath(t),a=await Kt(n);if(!Jt(i,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function Vr(t,e){let r=us(e),n=await Uw(t,r),i=_.join(n,"comet");if(await cs(i))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Kt(n),Kt(i)]);if(!Jt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=_.resolve(t),c=_.join(s,".comet","runtime","native");if(await cs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([vt.realpath(s),Kt(c)]);if(!Jt(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:_.join(t,...ls.split("/")),artifactRoot:n,artifactRootRef:r,nativeRoot:i,specsDir:_.join(i,"specs"),changesDir:_.join(i,"changes"),archiveDir:_.join(i,"archive"),runtimeDir:c,changesRuntimeDir:_.join(c,"changes"),locksDir:_.join(c,"locks"),transactionsDir:_.join(c,"transactions")}}function lf(t){if(!zw.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Si(t,e){lf(e);let r=_.join(t.changesRuntimeDir,e);if(!de(t.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Kw(t,e){lf(e);let r=_.join(t.changesDir,e,"runtime");if(!de(t.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function wt(t,e){let r=Si(t,e);if(cf(r))return r;let n=Kw(t,e);return cf(n)?n:r}function Yt(t,e){let r=_.resolve(e);if(de(t.runtimeDir,r))return t.runtimeDir;if(de(t.nativeRoot,r))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function de(t,e){return Jt(_.resolve(t),_.resolve(e))}async function F(t,e){let r=_.resolve(t),n=_.resolve(e);if(!Jt(r,n))throw new Error(`Path is outside the Native root: ${e}`);if(await cs(r))throw new Error(`Native root must not be a symbolic link: ${t}`);let[i,a]=await Promise.all([Kt(r),Kt(n)]);if(!Jt(i,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}import{promises as vf}from"fs";import I from"path";import{promises as Jw}from"fs";async function zr(t){try{return await Jw.access(t),!0}catch(e){if(Yw(e))return!1;throw e}}function Yw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}Ee();at();Ti();Ce();var ct=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},gf=".comet/config.yaml";function wf(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function yf(t){await Y(t,gf,{label:gf,expected:"file"})}function bf(t,e){let r=I.resolve(t),n=e==="docs"?I.join(r,"docs"):r,i=I.join(n,"openspec"),a=I.join(r,"docs","superpowers");return{projectRoot:r,artifactLayout:e,openSpecBase:n,openSpecRoot:i,changesDir:I.join(i,"changes"),archiveDir:I.join(i,"changes","archive"),specsDir:I.join(i,"specs"),superpowersRoot:a,superpowersSpecsDir:I.join(a,"specs"),superpowersPlansDir:I.join(a,"plans"),superpowersReportsDir:I.join(a,"reports")}}async function dy(t){await yf(t);let e=await bt(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new ct;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new ct("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function py(t,e){return bf(t,e??await dy(t))}async function hy(t){try{return await vf.lstat(t),!0}catch(e){if(wf(e))return!1;throw e}}async function my(t,e){let r=await py(t,e),n=r.artifactLayout==="legacy"?"docs":"legacy",i=bf(t,n).openSpecRoot,[a,o]=await Promise.all([Y(r.projectRoot,H(r.projectRoot,r.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),hy(i)]),s=a.exists;return{paths:r,configuredRootExists:s,alternateRoot:i,alternateRootExists:o,dualRoots:s&&o}}async function gy(t){let e=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let r of e){let n=H(t.projectRoot,r);await Y(t.projectRoot,n,{label:`Classic managed physical path ${n}`,expected:"directory"})}}async function Le(t,e){let r=await my(t,e);if(await gy(r.paths),!r.configuredRootExists){let n=H(r.paths.projectRoot,r.paths.openSpecRoot),i=H(r.paths.projectRoot,r.alternateRoot);throw new ct(`Configured Classic OpenSpec root is missing: ${n} (alternate ${i} is ${r.alternateRootExists?"present":"missing"})`)}return r.paths}async function Ii(t,e){let r=I.join(I.resolve(t),".comet","classic-root-move.json");if(await zr(r))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let n=await Le(t,e);if(!await zr(n.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${H(n.projectRoot,n.openSpecRoot)}`);return n}async function Nf(t){let e=I.resolve(t),r=null;try{(await vf.lstat(e)).isDirectory()||(e=I.dirname(e))}catch(n){if(!wf(n))throw n}for(;;){I.basename(e)==="openspec"&&(r=I.dirname(e));let n=I.join(e,".comet","config.yaml"),i=!1;if(await zr(n))try{await yf(e);let o=(await bt(e))?.value;i=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(i||await zr(I.join(e,".git")))return e;let a=I.dirname(e);if(a===e)return r??I.resolve(t);e=a}}function H(t,e){return I.relative(I.resolve(t),e).replaceAll("\\","/")}import{readFileSync as vy}from"fs";import kf from"path";function ws(t){return t.charCodeAt(0)===65279?t.slice(1):t}var wy=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","searchreplace","strreplaceeditor","write","writefile","writefiletool"]),yy=new Set(["glob","grep","listfiles","read","readfile","search","view"]),Ef=["file_path","filePath","path","target_file","targetFile"],Pf=["file_paths","filePaths","paths","files","targets"],Cf=["operations","edits"],by=["patch","diff","patchText","patch_text","changes"],bs=new Set(["claude","codex","windsurf","github-copilot","gemini","amazon-q","qwen","kiro","codebuddy","workbuddy","qoder","trae","trae-cn","grok"]);function Ns(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Sf(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Ny(t){for(let e of["tool_name","toolName","tool","name"]){let r=t[e];if(typeof r=="string"&&r.trim())return r.trim()}return null}function ky(t){for(let e of["cwd","working_directory","workspaceRoot"]){let r=t[e];if(!(typeof r!="string"||!r.trim()||!kf.isAbsolute(r.trim())))return kf.resolve(r.trim())}}function Sy(t){if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return t;try{return JSON.parse(e)}catch{return t}}function Ey(t){for(let e of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(t[e]!==void 0)return Sy(t[e]);return t}function ys(t){let e=[],r=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let n of r)for(let i of t.matchAll(n)){let a=i[1]?.trim();a&&a!=="/dev/null"&&e.push(a)}return e}function Nt(t,e){if(typeof e=="string"){let r=e.trim();r&&t.push(r);return}if(Array.isArray(e)){for(let r of e)Nt(t,r);return}if(Ns(e)){for(let r of Ef)Nt(t,e[r]);for(let r of Pf)Nt(t,e[r]);for(let r of Cf)Nt(t,e[r])}}function Py(t,e){let r=[],n=[e,t].filter(Ns);for(let i of n){for(let a of Ef)Nt(r,i[a]);for(let a of Pf)Nt(r,i[a]);for(let a of Cf)Nt(r,i[a]);for(let a of by){let o=i[a];typeof o=="string"&&r.push(...ys(o))}}return typeof e=="string"&&r.push(...ys(e)),[...new Set(r)]}function Xr(t,e){if(e?.trim())return{intent:"write",targets:[e.trim()],toolName:null};if(!t.trim())return{intent:"unknown",targets:[],toolName:null};let r;try{r=JSON.parse(ws(t))}catch{let o=ys(t);return o.length>0?{intent:"write",targets:[...new Set(o)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!Ns(r))return{intent:"unknown",targets:[],toolName:null};let n=Ny(r),i=Py(r,Ey(r)),a=ky(r);return n&&wy.has(Sf(n))?{intent:i.length>0?"write":"unknown",targets:i,toolName:n,...a?{cwd:a}:{}}:n&&yy.has(Sf(n))?{intent:"non-write",targets:[],toolName:n,...a?{cwd:a}:{}}:n?{intent:"unknown",targets:i,toolName:n,...a?{cwd:a}:{}}:{intent:i.length>0?"write":"unknown",targets:i,toolName:null,...a?{cwd:a}:{}}}function ks(){let t=process.env.FILE_PATH;if(t?.trim()||process.stdin.isTTY)return Xr("",t);try{return Xr(vy(0,"utf8"),t)}catch{return Xr("",t)}}function xf(t,e){return bs.has(t)?t==="github-copilot"?{exitCode:0,stdout:e.allowed?`{}
|
|
143
143
|
`:`${JSON.stringify({permissionDecision:"deny",permissionDecisionReason:e.reason})}
|
|
144
144
|
`,stderr:""}:e.allowed?{exitCode:0,stdout:"",stderr:""}:{exitCode:2,stdout:"",stderr:`${e.reason}
|
|
145
145
|
`}:{exitCode:64,stdout:"",stderr:`Unsupported Comet Hook platform: ${t}
|
|
146
|
-
`}}
|
|
147
|
-
Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function Oi(t){let e=Ss(t);if(e)throw new Error(e)}function Ny(t,e){return{label:H(t,e),directory:e}}async function ky(t,e,r){let n=Ny(t,e);if(!(await Qt(t,e,{label:r,expected:"directory"})).exists)return{change:n,exists:!1,stateExists:!1};let a=await Qt(t,_f.join(e,".comet.yaml"),{label:`${r} state`,expected:"file"});return{change:n,exists:!0,stateExists:a.exists}}async function Zt(t,e=process.cwd()){Oi(t);let r=await De(e),n=await ky(r.projectRoot,_f.join(r.changesDir,t),`Classic active change ${t}`);return{...n.change,exists:n.exists,stateExists:n.stateExists}}import{promises as Es}from"fs";import te from"path";function Rf(t,e){let r=te.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${te.sep}`)&&!te.isAbsolute(r)}async function Sy(t){let e=te.resolve(t),r=te.parse(e).root,n=[],i=e;for(;i&&i!==r;)try{let a=await Es.realpath(i);return te.join(a,...n.reverse())}catch(a){let o=a.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw a;n.push(te.basename(i)),i=te.dirname(i)}try{let a=await Es.realpath(r);return te.join(a,...n.reverse())}catch{return null}}async function $i(t,e){let r=te.resolve(t),n=await Es.realpath(r),i=[],a=[];for(let o of e){let s=te.isAbsolute(o)?te.resolve(o):te.resolve(r,o),c=await Sy(s);((c?Rf(n,c):Rf(r,s))?i:a).push(o)}return{projectTargets:i,externalTargets:a}}Li();var Ps=ze(Le(),1);Be();import{execFileSync as If}from"child_process";import{randomUUID as Cy}from"crypto";import{promises as Zr}from"fs";import jf from"path";function xy(t){try{let e=If("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var _y=ks("liveGitBranch",t=>xy(t));function Ry(t){try{return If("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var Ay=ks("isGitWorkTree",t=>Ry(t)),Ty=["current","branch","worktree"];function Of(t){return Ty.includes(t)}function Iy(t){return Of(t.isolation)?t.boundBranch===null&&t.currentBranch===null&&t.gitWorkTree===!1?{status:"not-applicable"}:t.boundBranch===null?t.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:t.currentBranch}:t.currentBranch===t.boundBranch?{status:"ok"}:{status:"drift",boundBranch:t.boundBranch,currentBranch:t.currentBranch}:{status:"not-applicable"}}async function Di(t,e){let r=jf.join(t,".comet.yaml"),n=(0,Ps.parseDocument)(await Zr.readFile(r,"utf8"),{uniqueKeys:!1});if(n.errors.length>0)throw new Error(`Invalid .comet.yaml: ${n.errors[0].message}`);let i=n.toJS()??{},a=typeof i.isolation=="string"?i.isolation:null,o=typeof i.bound_branch=="string"&&i.bound_branch!==""?i.bound_branch:null,s=Of(a),c=_y(e.cwd),l=s&&o===null&&c===null?Ay(e.cwd):!0,u=Iy({isolation:a,boundBranch:o,currentBranch:c,gitWorkTree:l});return u.status==="needs-heal"&&e.heal?(await jy(t,u.branch),{status:"healed",branch:u.branch,bindingRequired:s,currentBranch:c}):{...u,bindingRequired:s,currentBranch:c}}async function jy(t,e){let r=jf.join(t,".comet.yaml"),n=(0,Ps.parseDocument)(await Zr.readFile(r,"utf8"),{uniqueKeys:!1});n.set("bound_branch",e);let i=`${r}.${Cy()}.tmp`;try{await Zr.writeFile(i,n.toString(),"utf8"),await Zr.rename(i,r)}catch(a){throw await Zr.rm(i,{force:!0}),a}}function Oy(t){return t??"detached HEAD"}function Bi(t,e,r){return`change '${t}' is bound to branch '${e}', but current branch is '${Oy(r)}'`}function Mi(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}Ci();import $y from"path";var Cs="comet.selection.v2",Ly=16*1024;function xs(t){return $y.join(t,".comet","current-change.json")}function Dy(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function $f(t){return t===null||typeof t=="string"}function By(t){let e;try{e=JSON.parse(t)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!Dy(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!$f(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Cs,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==Cs)throw new Error(`current change selection schema must be ${Cs}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!$f(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function tr(t){let e;try{let n=xs(t),{bytes:i}=await Yt(n,Ly,{label:"current change selection"});e=i.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...By(e)}}Be();var Vi=ze(Le(),1);ot();xe();import Hi from"path";nn();var js=["full","hotfix","tweak"],Qf=1,ed=["open","design","build","verify","archive"],Qy=["en","zh-CN"],Zy=["off","beta"],eb=["subagent-driven-development","executing-plans","direct"],tb=["plan-ready"],rb=["confirmed"],nb=["tdd","direct"],ib=["off","standard","thorough"],ab=["current","branch","worktree"],ob=["light","full"],sb=["pending","pass","fail"],cb=["pending","handled"],lb=["pending","confirmed"],Os=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],ub=["run_id"],td=new Set([...Os,...ub]),fb=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Zf(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function rr(t,e){let r=t[e];if(r==null||r==="")return null;if(typeof r!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return r}function G(t,e,r,n=!0){let i=t[e];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="string"||!r.includes(i))throw new Error(`Invalid Classic state: ${e} must be one of ${r.join(", ")}${n?" or null":""}`);return i}function Is(t,e,r=!0){let n=t[e];if(n==null||n===""){if(r)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof n!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return n}function db(t,e,r=0){let n=t[e];if(n==null||n==="")return r;if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return n}function Fi(t,e){let r=rr(t,e);if(r===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return r}function pb(t,e){let r=rr(t,e);if(r!==null&&!/^[a-f0-9]{64}$/u.test(r))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return r}function hb(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==Qf)throw new Error(`Invalid Classic state: classic_migration must be ${Qf}`);return e}function mb(t){if(!Os.some(r=>Zf(t,r)))return null;for(let r of fb)if(!Zf(t,r))return null;return{workflow:G(t,"workflow",js,!1),language:G(t,"language",Qy),phase:G(t,"phase",ed,!1),contextCompression:G(t,"context_compression",Zy),buildMode:G(t,"build_mode",eb),buildPause:G(t,"build_pause",tb),subagentDispatch:G(t,"subagent_dispatch",rb),tddMode:G(t,"tdd_mode",nb),reviewMode:G(t,"review_mode",ib),isolation:G(t,"isolation",ab),boundBranch:rr(t,"bound_branch"),verifyMode:G(t,"verify_mode",ob),autoTransition:Is(t,"auto_transition"),baseRef:rr(t,"base_ref"),designDoc:Fi(t,"design_doc"),plan:Fi(t,"plan"),verifyResult:G(t,"verify_result",sb,!1),verifyFailures:db(t,"verify_failures"),verificationReport:Fi(t,"verification_report"),branchStatus:G(t,"branch_status",cb),createdAt:rr(t,"created_at"),verifiedAt:rr(t,"verified_at"),archiveConfirmation:G(t,"archive_confirmation",lb),archived:Is(t,"archived",!1),directOverride:Is(t,"direct_override"),handoffContext:Fi(t,"handoff_context"),handoffHash:pb(t,"handoff_hash"),classicProfile:G(t,"classic_profile",js),classicMigration:hb(t)}}function rd(t,e){let r=e??null;if(r===null&&e===void 0&&t.run_id&&t.skill)try{r=rn(t)}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(i.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:n})}return{classic:mb(t),run:r,unknownKeys:Object.keys(t).filter(n=>!td.has(n))}}function nd(t){let e=t.workflow,r=t.phase,n=t.archived,i=t.design_doc;return{workflow:typeof e=="string"&&js.includes(e)?e:null,phase:typeof r=="string"&&ed.includes(r)?r:null,archived:n===!0,designDoc:typeof i=="string"&&i!==""?i:null,unknownKeys:Object.keys(t).filter(a=>!td.has(a))}}nn();var gb=2*1024*1024;function an(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function vb(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let r of e)t.delete(r)}function wb(t){let e=!1;for(let r of["build_command","verify_command"])t.has(r)&&(t.delete(r),e=!0);return e}async function id(t){let e;try{e=(await ae(Hi.dirname(t),Hi.basename(t),gb,{label:"Classic state document"})).bytes.toString("utf8")}catch(n){if(n.code!=="ENOENT")throw n;return new Vi.Document({})}let r=(0,Vi.parseDocument)(e);if(r.errors.length>0)throw new Error(`Invalid Classic state document: ${r.errors[0].message}`);return an(r),r}async function zi(t,e={}){let r=e.migrate!==!1,n=Hi.join(t,".comet.yaml"),i=await id(n),a=an(i),o=wb(i);o&&(a=an(i));let s=await As(t);if(!s&&a.run_id&&a.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(nn(),Xf));s=c(a),s&&r&&(await Ts(t,s),vb(i),o=!0)}return o&&r&&await _e(n,i.toString(),{containedRoot:t}),rd(an(i),s)}async function ad(t){let e=await id(Hi.join(t,".comet.yaml"));return nd(an(e))}var Sb=ze(Le(),1);var x_=8*1024*1024;import{execFileSync as yb}from"child_process";import on from"path";function nr(t,e){return yb("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function bb(t,e){let r=on.normalize(t),n=on.normalize(e);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function ir(t){try{let e=on.resolve(nr(t,["rev-parse","--show-toplevel"])),n=nr(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),i=n?on.resolve(n.slice(9)):e,a=null;try{a=nr(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!bb(e,i),currentWorktreeRoot:e,primaryWorktreeRoot:i,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function od(t){try{nr(t,["rev-parse","--is-inside-work-tree"]);let e=nr(t,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],n=null;for(let i of e)i.startsWith("worktree ")?(n&&r.push(n),n={root:on.resolve(i.slice(9)),branch:null,detached:!1}):n&&i.startsWith("branch refs/heads/")?n.branch=i.slice(18):n&&i==="detached"&&(n.detached=!0);return n&&r.push(n),r}catch{return[]}}function Gi(t){return od(t).map(e=>e.root)}function $s(t,e){try{let r=nr(t,["rev-parse","--verify",`${e}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var xb=X("readCometCurrentSelection",t=>tr(t));async function _b(t,e){Oi(e);let r=await Zt(e,t);if(!r.stateExists)throw new Error(`Cannot select current change '${e}': active change state not found`);let n=await zi(r.directory,{migrate:!1});if(!n.classic)throw new Error(`Cannot select current change '${e}': Classic state is incomplete`);if(n.classic.archived)throw new Error(`Cannot select current change '${e}': change is archived`);return r.directory}async function Ki(t){let e;try{e=await xb(t)}catch(a){return{status:"stale",reason:a instanceof Error?a.message:String(a)}}if(e.status==="missing")return{status:"missing"};if(e.selection.workflow!=="classic")return{status:"stale",reason:`current change '${e.selection.change}' belongs to Native, not Classic`};let r=e.selection,n;try{n=await _b(t,r.change)}catch(a){return{status:"stale",reason:a instanceof Error?a.message:String(a)}}let i=await Di(n,{heal:!1,cwd:t});return i.status==="drift"?{status:"stale",reason:Bi(r.change,i.boundBranch,i.currentBranch)}:i.status==="unbound-detached"?{status:"stale",reason:Mi(r.change)}:i.status==="ok"?{status:"selected",selection:r}:r.branch!==null&&i.currentBranch!==r.branch?{status:"stale",reason:`current change '${r.change}' was selected on branch '${r.branch}', current branch is '${i.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:r}}import Nt from"node:path";async function sd(t,e){if(!e||e==="null")return{status:"missing",recordedPath:null};let r=await De(t),n=Nt.resolve(t,e),i=Nt.relative(r.superpowersPlansDir,n);return Nt.isAbsolute(e)||!i||i.startsWith(`..${Nt.sep}`)||Nt.isAbsolute(i)||i.includes(Nt.sep)||Nt.extname(i).toLowerCase()!==".md"?{status:"broken",recordedPath:e}:await xf(t,e,{label:`Classic build plan ${e}`,expected:"file"})?{status:"ready",recordedPath:e}:{status:"broken",recordedPath:e}}function he(t,e){return{exitCode:t,stderr:e+`
|
|
148
|
-
`}}function
|
|
149
|
-
`))}function
|
|
150
|
-
`))}function
|
|
151
|
-
`))}function
|
|
152
|
-
`))}function
|
|
153
|
-
`))}function
|
|
154
|
-
`))}async function
|
|
155
|
-
`))}let i=await
|
|
156
|
-
`,r)}
|
|
157
|
-
`,"utf8"),await r.sync(),_d(await r.stat({bigint:!0}))}finally{await r.close()}}async function vN(t,e){let r=await F(t.runtimeDir,t.locksDir);await se.mkdir(r,{recursive:!0});let n=await F(t.runtimeDir,K.join(r,xd));await se.mkdir(n,{recursive:!0});let i=Ad(e),a=K.join(n,`.${i.id}.tmp`),o=K.join(n,`${i.id}.claim`);try{let s=await Td(a,i);await se.rename(a,o);let c=await We(o);if(!c||!Ws(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.runtimeDir,locksDir:r,owner:i,identity:c.identity}}finally{await se.rm(a,{force:!0})}}async function wN(t){let e=K.dirname(t.file),r=!1,n=K.basename(t.file);for(let i of await se.readdir(e,{withFileTypes:!0})){if(!i.isFile()||i.isSymbolicLink()||!i.name.endsWith(".claim"))continue;let a=K.join(e,i.name);if(K.resolve(a)!==K.resolve(t.file))try{let o=await We(a),s=Rd(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Fs(o,e);continue}i.name<n&&(r=!0)}catch{i.name<n&&(r=!0)}}return r}async function Id(t){let e=await We(t.file);if(e){if(e.owner.id!==t.owner.id||!qs(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await Fs(e,K.dirname(t.file))}}async function yN(t,e){let r=Date.now()+dN;for(;;){let n=await vN(t,e);if(!await wN(n))return n;if(await Id(n),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(i=>setTimeout(i,2+Math.floor(Math.random()*7)))}}async function bN(t){let e=Qi.get(t)??Promise.resolve(),r,n=new Promise(a=>{r=a}),i=e.then(()=>n);return Qi.set(t,i),await e,()=>{r(),Qi.get(t)===i&&Qi.delete(t)}}async function jd(t,e,r){let n=K.resolve(t.locksDir),i=Ed.getStore();if(i?.has(n))return r();let a=await bN(n);try{let o=await yN(t,e),s=new Map(i??[]);return s.set(n,o),await Ed.run(s,async()=>{try{return await r()}finally{await Id(o)}})}finally{a()}}async function Od(t,e,r){return jd(t,`acquire ${e}`,async()=>{let n=await F(t.runtimeDir,t.locksDir);await se.mkdir(n,{recursive:!0});let i=await F(t.runtimeDir,K.join(n,pN(e))),a=Ad(r),o=await Td(i,a);return{file:i,nativeRoot:t.runtimeDir,locksDir:n,owner:a,identity:o}})}async function $d(t){await We(t.file)&&await jd({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${K.basename(t.file)}`,async()=>{let e=await We(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!qs(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let r=K.join(t.locksDir,xd);await Fs(e,r)})}function NN(t){try{return process.kill(t,0),!0}catch(e){let r=e.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function Ld(t){return Rd(await We(t))}import tk from"node:path";var VR=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),zR=Object.freeze({maxCriteria:1024});var ta=ze(Le(),1);import{promises as EN}from"node:fs";var dn="comet.native.v4",pn="comet.native.local-execution.v4";var PN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,CN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xN=/^A[1-9][0-9]*$/u,_N=/^[a-f0-9]{64}$/u,RN=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),ea=class extends Error{constructor(r,n){super(`Native state version conflict: expected ${r}, got ${n}`);this.expectedStateVersion=r;this.actualStateVersion=n;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Q(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Z(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function q(t,e,r){if(typeof t!="string"||!r?.empty&&t.length===0)throw new Error(`${e} must be ${r?.empty?"a string":"a non-empty string"}`);return t}function Vs(t,e){return t===null?null:q(t,e)}function AN(t,e){let r=q(t,e);if(!_N.test(r))throw new Error(`${e} must be a SHA-256 hash`);return r}function ar(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function T(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function TN(t,e){return t===null?null:T(t,e,Number.MIN_SAFE_INTEGER)}function W(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function Ae(t,e,r){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((n,i)=>r(n,i))}function ra(t,e){return Ae(t,e,(r,n)=>q(r,`${e}[${n}]`))}function Et(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function or(t,e){let r=q(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO date or timestamp`);return r}function zs(t,e,r=!1){let n=q(t,e);if(n.includes("\\")||n.startsWith("/")||/^[A-Za-z]:/u.test(n)||n.split("/").includes("..")||!r&&(n==="."||n.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return n}function we(t,e){let r=Q(t,e);return Z(r,new Set(["text","truncated"]),e),{text:q(r.text,`${e}.text`,{empty:!0}),truncated:ar(r.truncated,`${e}.truncated`)}}function IN(t,e){let r=`Native spec_changes[${e}]`,n=Q(t,r);Z(n,new Set(["capability","operation","source"]),r);let i=q(n.capability,`${r}.capability`);if(!CN.test(i))throw new Error(`${r}.capability is invalid`);let a=W(n.operation,["create","modify","remove"],`${r}.operation`),o=n.source===null?null:zs(n.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:i,operation:a,source:o}}function jN(t){let e="Native workspace",r=Q(t,e);Z(r,new Set(["isolation","change_branch","target_branch","finish"]),e);let n=W(r.isolation,["current","branch","worktree"],`${e}.isolation`),i=Vs(r.change_branch,`${e}.change_branch`),a=Vs(r.target_branch,`${e}.target_branch`),o=r.finish===null?null:W(r.finish,["merge","push","pull-request","keep"],`${e}.finish`);if(n==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(n==="current"&&i===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(n!=="current"&&(i===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:n,change_branch:i,target_branch:a,finish:o}}function ON(t){let e="Native loop",r=Q(t,e);Z(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),e);let n=ra(r.previous_unresolved_ids,`${e}.previous_unresolved_ids`);return Et(n,`${e}.previous_unresolved_ids`),{stage:W(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:T(r.goal_cycle,`${e}.goal_cycle`,1),iteration:T(r.iteration,`${e}.iteration`),attempt:T(r.attempt,`${e}.attempt`),retry_epoch:T(r.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:T(r.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:T(r.no_progress_count,`${e}.no_progress_count`),execution_failure_count:T(r.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:n,next_action:Vs(r.next_action,`${e}.next_action`)}}function $N(t,e){let r=`Native acceptance[${e}]`,n=Q(t,r);Z(n,new Set(["id","source","text","result","reason"]),r);let i=q(n.id,`${r}.id`);if(!xN.test(i))throw new Error(`${r}.id must use A1, A2, ...`);return{id:i,source:zs(n.source,`${r}.source`),text:q(n.text,`${r}.text`),result:W(n.result,["pending","passed","failed","blocked"],`${r}.result`),reason:n.reason===null?null:we(n.reason,`${r}.reason`)}}function LN(t,e){let r=`Native builder_handoff.checks[${e}]`,n=Q(t,r);return Z(n,new Set(["name","result","note"]),r),{name:we(n.name,`${r}.name`),result:W(n.result,["passed","failed","not-run"],`${r}.result`),note:n.note===null?null:we(n.note,`${r}.note`)}}function DN(t){let e="Native builder_handoff",r=Q(t,e);Z(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),e);let n=ra(r.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);return Et(n,`${e}.addressed_acceptance_ids`),{candidate_id:q(r.candidate_id,`${e}.candidate_id`),identity_provider:q(r.identity_provider,`${e}.identity_provider`),builder_execution_ref:q(r.builder_execution_ref,`${e}.builder_execution_ref`),iteration:T(r.iteration,`${e}.iteration`,1),summary:we(r.summary,`${e}.summary`),addressed_acceptance_ids:n,checks:Ae(r.checks,`${e}.checks`,LN),checks_truncated:ar(r.checks_truncated,`${e}.checks_truncated`),known_limits:Ae(r.known_limits,`${e}.known_limits`,(i,a)=>we(i,`${e}.known_limits[${a}]`)),known_limits_truncated:ar(r.known_limits_truncated,`${e}.known_limits_truncated`),submitted_at:or(r.submitted_at,`${e}.submitted_at`)}}function BN(t,e){let r=`Native blockers[${e}]`,n=Q(t,r);Z(n,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let i=ra(n.acceptance_ids,`${r}.acceptance_ids`);return Et(i,`${r}.acceptance_ids`),{owner:W(n.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:we(n.reason,`${r}.reason`),acceptance_ids:i,resolution_action:W(n.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function MN(t,e){let r=`Native verification.checks[${e}]`,n=Q(t,r);return Z(n,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:q(n.id,`${r}.id`),name:we(n.name,`${r}.name`),argv_display:Ae(n.argv_display,`${r}.argv_display`,(i,a)=>we(i,`${r}.argv_display[${a}]`)),argv_truncated:ar(n.argv_truncated,`${r}.argv_truncated`),cwd_ref:zs(n.cwd_ref,`${r}.cwd_ref`,!0),status:W(n.status,["passed","failed","interrupted"],`${r}.status`),exit_code:TN(n.exit_code,`${r}.exit_code`),duration_ms:T(n.duration_ms,`${r}.duration_ms`)}}function WN(t){let e="Native verification",r=Q(t,e);Z(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let n=Ae(r.checks,`${e}.checks`,MN);Et(n.map(a=>a.id),`${e}.checks IDs`);let i=q(r.identity_provider,`${e}.identity_provider`);return{candidate_id:q(r.candidate_id,`${e}.candidate_id`),identity_provider:i,verifier_execution_ref:q(r.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:T(r.iteration,`${e}.iteration`,1),attempt:T(r.attempt,`${e}.attempt`,1),assurance:r.assurance===void 0?i==="skill-coordinated"?"skill-coordinated":"host-attested":W(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:W(r.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:n,summary:we(r.summary,`${e}.summary`),risks:Ae(r.risks,`${e}.risks`,(a,o)=>we(a,`${e}.risks[${o}]`)),risks_truncated:ar(r.risks_truncated,`${e}.risks_truncated`),completed_at:or(r.completed_at,`${e}.completed_at`)}}function Dd(t,e){let r=`Native history[${e}]`,n=Q(t,r);Z(n,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let i=ra(n.unresolved_ids,`${r}.unresolved_ids`);return Et(i,`${r}.unresolved_ids`),{goal_cycle:T(n.goal_cycle,`${r}.goal_cycle`,1),iteration:T(n.iteration,`${r}.iteration`),attempt:T(n.attempt,`${r}.attempt`),outcome:W(n.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:i,summary:we(n.summary,`${r}.summary`),completed_at:or(n.completed_at,`${r}.completed_at`)}}function qN(t){let e="Native history_overflow.outcome_counts",r=Q(t,e),n=["pass","fail","blocked","execution-error","recovery"];return Z(r,new Set(n),e),{pass:T(r.pass,`${e}.pass`),fail:T(r.fail,`${e}.fail`),blocked:T(r.blocked,`${e}.blocked`),"execution-error":T(r["execution-error"],`${e}.execution-error`),recovery:T(r.recovery,`${e}.recovery`)}}function FN(t){let e="Native history_overflow",r=Q(t,e);Z(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let n=T(r.dropped_entries,`${e}.dropped_entries`),i=r.first_dropped_at===null?null:or(r.first_dropped_at,`${e}.first_dropped_at`),a=r.last_dropped_at===null?null:or(r.last_dropped_at,`${e}.last_dropped_at`);if(n===0&&(i!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(n>0&&(i===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=qN(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==n)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:n,first_dropped_at:i,last_dropped_at:a,outcome_counts:o}}function HN(t){let e=new Set(t.acceptance.map(r=>r.id));for(let r of t.loop.previous_unresolved_ids)if(!e.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of t.blockers)for(let n of r.acceptance_ids)if(!e.has(n))throw new Error(`Native blocker references unknown ID ${n}`);if(t.builder_handoff&&!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let n=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,i=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!n&&!i)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function VN(t){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let r=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(r!==null&&t.loop.stage!==r)throw new Error(`Native status ${t.status} requires loop stage ${r}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(n=>n.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(n=>n.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function Te(t){let e=Q(t,"Native portable state");if(Z(e,RN,"Native portable state"),e.schema!==dn)throw new Error(`Native portable state schema must be ${dn}`);let r=q(e.name,"Native state name");if(!PN.test(r))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let n=Ae(e.spec_changes,"Native spec_changes",IN);Et(n.map(s=>s.capability),"Native spec change capabilities");let i=Ae(e.acceptance,"Native acceptance",$N);Et(i.map(s=>s.id),"Native acceptance IDs");let a=Ae(e.history,"Native history",Dd);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:dn,name:r,language:W(e.language,["en","zh-CN"],"Native state language"),phase:W(e.phase,["shape","build","verify","archive"],"Native state phase"),status:W(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:T(e.state_version,"Native state_version",1),brief:"brief.md",...e.children_contract_hash===void 0?{}:{children_contract_hash:AN(e.children_contract_hash,"Native children contract hash")},spec_changes:n,workspace:jN(e.workspace),loop:ON(e.loop),acceptance:i,builder_handoff:e.builder_handoff===null?null:DN(e.builder_handoff),blockers:Ae(e.blockers,"Native blockers",BN),verification:e.verification===null?null:WN(e.verification),history:a,history_overflow:FN(e.history_overflow),verification_result:W(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:W(e.verification_report,["verification.md"],"Native verification_report"),archived:ar(e.archived,"Native archived"),created_at:or(e.created_at,"Native created_at")};return HN(o),VN(o),o}function na(t,e){let r=Te(t),n=Dd(e,r.history.length),i=[...r.history,n],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;i.length>50;){let o=i.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return Te({...r,history:i,history_overflow:a})}function zN(t,e){let r=(0,ta.parseDocument)(t,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${e} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function hn(t){let e=await EN.readFile(t,"utf8");return Te(zN(e,"Native portable state"))}async function Bd(t,e,r={}){let n=Te(e);await Me(t,(0,ta.stringify)(n),r)}var Zi=new Map;async function GN(t,e){let r=Zi.get(t)??Promise.resolve(),n,i=new Promise(o=>{n=o}),a=r.then(()=>i);Zi.set(t,a),await r;try{return await e()}finally{n(),Zi.get(t)===a&&Zi.delete(t)}}async function Md(t){return GN(t.file,async()=>{let e=T(t.expectedStateVersion,"Native expected state version",1),r=Te(t.next);if(r.state_version!==e+1)throw new Error("Native CAS next state_version must increment exactly once");let n=await hn(t.file);if(n.state_version===r.state_version&&JSON.stringify(n)===JSON.stringify(r))return n;if(n.state_version!==e)throw new ea(e,n.state_version);return await Bd(t.file,r,{...t.containedRoot?{containedRoot:t.containedRoot}:{},beforeCommit:async()=>{let i=await hn(t.file);if(i.state_version!==e)throw new ea(e,i.state_version)}}),r})}function KN(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function mn(t,e=16384){if(typeof t!="string")throw new Error("Native portable text must be a string");if(KN(e),Buffer.byteLength(t,"utf8")<=e)return{text:t,truncated:!1};let r="",n=0;for(let i of t){let a=Buffer.byteLength(i,"utf8");if(n+a>e)break;r+=i,n+=a}return{text:r,truncated:!0}}var qe="comet.native.v3",Fe="comet.native.v2",He="comet.native.v1";var Wd="comet.native.portable-migration.v1",JN=new Set(["schema","id","change","fromSchema","status","createdAt"]),UN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,YN=/^[a-z0-9][a-z0-9-]{7,127}$/u,XN=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),QN=new Set([He,Fe,qe]);function ZN(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ek(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let r=new Date(t);if(Number.isNaN(r.valueOf())||r.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function qd(t){let e=ZN(t,"Native portable migration transaction"),r=Object.keys(e).filter(n=>!JN.has(n));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(e.schema!==Wd)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!YN.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!UN.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!QN.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!XN.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Wd,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:ek(e.createdAt,"Native portable migration transaction createdAt")}}var Hd="comet.native.archive-transaction.v4",Vd="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",rk=new RegExp(`^portable-archive-(${Vd})\\.json$`,"u"),nk=new RegExp(`^portable-migration-(${Vd})\\.json$`,"u"),ik=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,ak=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ok=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),sk=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ck=new Set(["capability","operation","source","content"]),zd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Gd(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Kd(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(Object.keys(t).length!==e.size)throw new Error(`${r} fields are invalid`)}function lk(t,e){let r=`Native portable Archive spec_changes[${e}]`,n=Gd(t,r);if(Kd(n,ck,r),typeof n.capability!="string"||!zd.test(n.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(n.operation)))throw new Error(`${r}.operation is invalid`);let i=n.operation;if(i==="remove"){if(n.source!==null||n.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:n.capability,operation:i,source:null,content:null}}if(typeof n.source!="string"||n.source.length===0||n.source.includes("\\")||n.source.startsWith("/")||/^[A-Za-z]:/u.test(n.source)||n.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${i} source is invalid`);if(typeof n.content!="string")throw new Error(`${r}.${i} content is invalid`);return{capability:n.capability,operation:i,source:n.source,content:n.content}}function uk(t){let e=Gd(t,"Native portable Archive transaction");if(Kd(e,sk,"Native portable Archive transaction"),e.schema!==Hd)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!ik.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!zd.test(e.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(e.start_state_version)||Number(e.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof e.archive_ref!="string"||!ak.test(e.archive_ref)||!e.archive_ref.endsWith(`-${e.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof e.status!="string"||!ok.has(e.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=e.spec_changes.map(lk);if(new Set(r.map(({capability:i})=>i)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(e.next_spec_index)||Number(e.next_spec_index)<0||Number(e.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof e.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let n=new Date(e.created_at);if(Number.isNaN(n.valueOf())||n.toISOString()!==e.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Hd,id:e.id,change:e.change,start_state_version:Number(e.start_state_version),archive_ref:e.archive_ref,status:e.status,next_spec_index:Number(e.next_spec_index),spec_changes:r,created_at:e.created_at}}function Js(t){let e=rk.exec(t);if(e)return{kind:"archive",change:e[1]};let r=nk.exec(t);return r?{kind:"migration",change:r[1]}:null}async function Jd(t,e){let r=Js(e);if(!r)return null;let n=await ct({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),i=JSON.parse(n.text),a=tk.join(t.transactionsDir,e);if(r.kind==="archive"){let s=uk(i);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=qd(i);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function Ud(t){return t.kind==="archive"||t.journal.status!=="committed"}import Ve from"path";import{TextDecoder as yk}from"util";import{createHash as fk}from"node:crypto";import{constants as ia,promises as ye}from"node:fs";import be from"node:path";import{TextDecoder as dk}from"node:util";function oa(t,e){let r=be.relative(t,e);return r===""||!be.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${be.sep}`)}function pk(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function hk(t,e){return R({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function mk(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function aa(t,e){return R({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Us(t,e){let r=await ye.lstat(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await ye.realpath(t),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function gk(t,e,r){let n=be.resolve(t),i=be.resolve(e);if(!oa(n,i))throw new Error(`${r} is outside its managed root`);let a=[await Us(n,r)],o=n;for(let s of be.relative(n,i).split(be.sep).filter(Boolean)){await Pt(a,r),o=be.join(o,s);let c=await Us(o,r);if(!oa(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Pt(a,r),a}async function Pt(t,e){for(let r of t){let n=await ye.lstat(r.path);if(!n.isDirectory()||n.isSymbolicLink()||!hk(r,n)||await ye.realpath(r.path)!==r.realPath)throw new Error(`${e} parent changed during I/O: ${r.path}`)}}async function vk(t,e,r){let n=[],i=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-i,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(i+=s,i>e)throw new Error(`${r} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,i)}async function Ys(t){let e=pk(t.maxBytes),r=be.resolve(t.file),n=await gk(t.root,be.dirname(r),t.label),i=await Promise.all((t.forbiddenRoots??[]).map(u=>Us(be.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Pt(n,t.label);let a=await ye.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=mk(a),s=await ye.realpath(r);if(!oa(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(i.some(u=>oa(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?ia.O_RDONLY:ia.O_RDONLY|ia.O_NOFOLLOW|ia.O_NONBLOCK,l=await ye.open(r,c);try{let u=await l.stat();await t.hooks?.afterOpen?.();let[f,d]=await Promise.all([ye.lstat(r),ye.realpath(r)]);if(await Pt(n,t.label),await Pt(i,t.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!aa(o,u)||!aa(o,f))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let h=await vk(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([l.stat(),ye.lstat(r),ye.realpath(r)]);if(await Pt(n,t.label),await Pt(i,t.label),!p.isFile()||p.isSymbolicLink()||m!==s||!aa(o,v)||!aa(o,p))throw new Error(`${t.label} changed while reading`);return{bytes:h,hash:fk("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Yd(t){let e=await Ys(t),r;try{r=new dk("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t.label} is not valid UTF-8`,{cause:n})}return{...e,text:r}}var bk=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Nk=new Set(["id","type","source","target","staged","backup"]),kk=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Sk=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Qd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Ek=256*1024,$A=1024*1024,LA=16*1024;var DA=64*1024*1024;var Pk=new yk("utf-8",{fatal:!0});function ca(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function la(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function Zd(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function Xs(t,e){if(typeof t!="string"||t.length===0||Ve.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function sa(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function Xd(t,e){if(Xs(t,e),t.includes("\\")||t!==Ve.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function Ck(t,e){let r=ca(t,`transaction operations[${e}]`);if(la(r,Nk,`transaction operations[${e}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${e}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);Xs(r.target,`transaction operation ${r.id} target`);for(let n of["source","staged","backup"])r[n]!==void 0&&Xs(r[n],`transaction operation ${r.id} ${n}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function xk(t){let e=ca(t,"Native Archive transaction journal");if(la(e,kk,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!Qd.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!Zd(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(sa(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=e.operations.map((s,c)=>{let l=ca(s,`Archive transaction operations[${c}]`);if(la(l,Sk,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Xd(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Xd(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&sa(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(sa(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);sa(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=r.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let i=`runtime/transactions/${e.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${i}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${i}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:r}}function _k(t){let e=ca(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return xk(e);if(la(e,bk,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!Qd.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!Ve.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!Ve.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!Zd(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let r=e.operations.map(Ck),n=r.map(i=>i.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:r}}function Rk(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return Ve.join(t.transactionsDir,e)}function Ak(t,e){let r=Rk(t,e);return{directory:r,journal:Ve.join(r,"transaction.json"),events:Ve.join(r,"events.jsonl"),staged:Ve.join(r,"staged"),backups:Ve.join(r,"backups")}}async function Tk(t,e){let r=Ak(t,e);return await Promise.all(Object.values(r).map(n=>F(t.runtimeDir,n))),r}async function ep(t,e,r={}){let n=await Tk(t,e),i=await Ys({root:t.runtimeDir,file:n.journal,maxBytes:Ek,label:`Native transaction journal ${e}`,hooks:r.hooks}),a=JSON.parse(Pk.decode(i.bytes)),o=_k(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function Ok(t,e,r){let n;try{n=await Ik.readdir(t.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return!1;throw i}for(let i of n)if(!(!i.isDirectory()||i.isSymbolicLink()))try{let a=await ep(t,i.name);if(a.id!==e&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let i of n)if(Js(i.name))try{let a=await Jd(t,i.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Ud(a))return!0}catch{return!0}return!1}async function $k(t,e){let r=Date.now()+5e3,n=jk.join(t.locksDir,"root-move.lock");for(;;)try{return await Od(t,"root-move",e)}catch(i){if(i.cause?.code!=="EEXIST")throw i;let o=await Ld(n);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw i;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function Ct(t,e,r,n){let i=await $k(t,e);try{if(await Xi(t.projectRoot),await Ok(t,n?.allowedTransactionId,n?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await $d(i)}}import Zs from"path";import{createHash as Lk}from"crypto";function tp(t){return Lk("sha256").update(t).digest("hex")}var nT={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Bk=1e3,Mk=8*1024*1024,Wk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qk=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),Fk=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),Hk=new Set(["schema","include","exclude","hash"]),Vk=new Set(["provider","gitSelection","physicalSelection","projection"]),zk=new Set(["provider","selection"]),Gk=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Kk=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),Jk=new Set(["schema","status","before","after"]),Uk=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Yk=new Set(["path","hash","size","type","gitObjectId"]),Xk=new Set(["path","size","type","reason"]),Qk=new Set(["ref","hash","count"]),Zk=new Set(["change-created","legacy-migration","explicit"]),eS=new Set(["file","directory","other"]),tS=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"]),fa=/^[a-f0-9]{64}$/u,rS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var iT=64*1024,aT=64*1024;var oT={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},sT={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function ua(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}var cT=(1n<<256n)-1n;function nS(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function iS(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
158
|
-
`)}function
|
|
159
|
-
${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function Qs(t,e,r){let n=new Set(e),i=[...e];for(;i.length>0;){if(r&&!r())return null;let a=i.pop(),o=t[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),i.push(a+1))}return n}function oS(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function rp(t){let e=Yi(t,"Native snapshot pattern"),r=[];for(let n=0;n<e.length;n+=1){let i=e[n];i==="*"&&e[n+1]==="*"?(n+=1,e[n+1]==="/"?(n+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):i==="*"?r.push({kind:"star"}):i==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:i})}return(n,i)=>{let a=i?oS(i):void 0;if(a&&!a())return!1;let o=Qs(r,new Set([0]),a);if(o===null)return!1;for(let s of n){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Qs(r,c,a),o===null||o.size===0)return!1}return Qs(r,o,a)?.has(r.length)??!1}}function sS(t){if(t===void 0)return;let e=[...new Set(t.include.map(i=>Yi(i,"include")))].sort((i,a)=>i.localeCompare(a,"en")),r=[...new Set(t.exclude.map(i=>Yi(i,"exclude")))].sort((i,a)=>i.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let n=aS(e,r);if("hash"in t&&t.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:r,hash:n},includeMatchers:e.map(rp),excludeMatchers:r.map(rp),excludedDirectoryPrefixes:r.flatMap(i=>{if(!i.endsWith("/**"))return[];let a=i.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((i,a)=>i.localeCompare(a,"en"))}}function ce(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function le(t,e,r){let n=Object.keys(t).find(i=>!e.has(i));if(n)throw new Error(`${r} contains unknown field: ${n}`)}function cr(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ie(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function ap(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let r=Zs.posix.normalize(t);if(r!==t||Zs.posix.isAbsolute(t)||r===".."||r.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function cS(t,e){let r=ce(t,`Native snapshot entry ${e}`);le(r,Yk,`Native snapshot entry ${e}`);let n=ap(r.path,`Native snapshot entry ${e} path`);if(typeof r.hash!="string"||!fa.test(r.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let i={path:n,hash:r.hash,size:Ie(r.size,`Native snapshot entry ${e} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!rS.test(r.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);i.gitObjectId=r.gitObjectId}return i}function lS(t,e){let r=ce(t,`Native snapshot omission ${e}`);if(le(r,Xk,`Native snapshot omission ${e}`),!eS.has(r.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!tS.has(r.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:ap(r.path,`Native snapshot omission ${e} path`),size:r.size===null?null:Ie(r.size,`Native snapshot omission ${e} size`),type:r.type,reason:r.reason}}function uS(t){let e=ce(t,"Native snapshot omission overflow");if(le(e,Qk,"Native snapshot omission overflow"),typeof e.hash!="string"||!fa.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:e.hash,count:cr(e.count,"Native snapshot omission overflow count")}}function sr(t,e){let r=ce(t,e);if(le(r,Kk,e),typeof r.hash!="string"||!fa.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let n=Ie(r.recordCount,`${e} recordCount`),i=Ie(r.storedRecordCount,`${e} storedRecordCount`),a=Ie(r.stdoutBytes,`${e} stdoutBytes`);if(i>n||!r.overflow&&i!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,recordCount:n,storedRecordCount:i,stdoutBytes:a,overflow:r.overflow}}function np(t){let e=ce(t,"Native Git selection evidence");if(le(e,Gk,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=sr(e.stageBefore,"Native Git selection stageBefore"),n=sr(e.combined,"Native Git selection combined"),i=sr(e.stageAfter,"Native Git selection stageAfter"),a=sr(e.finalStageBefore,"Native Git selection finalStageBefore"),o=sr(e.finalCombined,"Native Git selection finalCombined"),s=sr(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,n,i,a,o,s].some(f=>f.overflow),l=!ua(r,i)||!ua(i,a)||!ua(n,o)||!ua(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:n,stageAfter:i,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function ip(t,e){let r=ce(t,e);if(le(r,Uk,e),typeof r.hash!="string"||!fa.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${e} flags are invalid`);let n=Ie(r.visitedNodeCount,`${e} visitedNodeCount`),i=Ie(r.recordCount,`${e} recordCount`),a=Ie(r.storedRecordCount,`${e} storedRecordCount`),o=Ie(r.encodedBytes,`${e} encodedBytes`);if(a>i||!r.overflow&&a!==i)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:n,recordCount:i,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function fS(t){let e=ce(t,"Native physical selection evidence");if(le(e,Jk,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=ip(e.before,"Native physical selection before"),n=ip(e.after,"Native physical selection after"),i=r.overflow||n.overflow,a=r.unstable||n.unstable||!nS(r,n);if(!i&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=i&&a?"overflow-and-changed":i?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:n}}function dS(t){let e=ce(t,"Native content snapshot manifest");if(le(e,qk,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Zk.has(e.origin))throw new Error("Native content snapshot origin is invalid");let r;if(e.capture!==void 0){let g=ce(e.capture,"Native content snapshot capture");if(le(g,Vk,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let C=g.gitSelection===void 0?void 0:np(g.gitSelection),N=g.physicalSelection===void 0?void 0:fS(g.physicalSelection),A=null;if(g.projection!==void 0){let ee=ce(g.projection,"Native content snapshot projection");if(le(ee,zk,"Native content snapshot projection"),ee.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");A={provider:"git",...ee.selection===void 0?{}:{selection:np(ee.selection)}}}if(g.provider==="git"){if(N||A)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...C?{gitSelection:C}:{}}}else{if(C)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&A)throw new Error("Native physical-tree capture cannot combine selection and projection");r=A?{provider:"physical-tree",projection:A}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=ce(e.limits,"Native content snapshot limits");le(n,Fk,"Native content snapshot limits");let i={maxFiles:cr(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:cr(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:cr(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:cr(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:cr(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let g=ce(e.policy,"Native snapshot policy");if(le(g,Hk,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=sS({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(cS),s=e.omitted.map(lS),c=Ie(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:uS(e.omissionOverflow);if(o.length>i.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>i.maxFileBytes)||o.reduce((g,C)=>g+C.size,0)>i.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Bk||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let f=s.filter(g=>g.reason==="git-enumeration-limit"),d=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...f,...d])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(f.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(f.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(g=>g.reason==="physical-enumeration-limit"),y=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...m,...y])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,k=b?.status==="overflow"||b?.status==="overflow-and-changed",S=b?.status==="changed"||b?.status==="overflow-and-changed";if(k!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:e.origin,...r?{capture:r}:{},createdAt:e.createdAt,complete:e.complete,limits:i,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(iS(E)>i.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function pS(t,e){if(!Wk.test(e))throw new Error(`Invalid Native change name: ${e}`);return Zs.join(vt(t,e),"baseline-manifest.json")}async function op(t,e){let r=pS(t,e),n=Ut(t,r);await F(n,r);try{let i=await Yd({root:n,file:r,maxBytes:Mk,label:"Native baseline snapshot manifest"});return dS(JSON.parse(i.text))}catch(i){if(i.code==="ENOENT")return null;throw i}}nn();var NT={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import{createHash as mS}from"node:crypto";import{promises as da}from"node:fs";import lt from"node:path";var gn=/^[a-f0-9]{64}$/u,sp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,gS=16*1024,tc=process.platform;function up(t,e){let r=lt.relative(t,e);return lt.isAbsolute(r)||r===".."||r.startsWith(`..${lt.sep}`)?null:r.replaceAll("\\","/")||"."}function fp(t){return Array.from(t).some(e=>{let r=e.codePointAt(0)??0;return r<=31||r===127})}function dp(t,e){if(t.length===0||fp(t)||t.includes("\\")||lt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let r=lt.posix.normalize(t);if(r!==t||r===".."||r.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return r}function rc(t,e){return mS("sha256").update(`${t}
|
|
160
|
-
${e}`).digest("hex")}async function
|
|
146
|
+
`}}De();import{promises as Ui,readFileSync as cR}from"fs";import re from"path";De();import Tf from"path";st();Ee();Ce();import Zr from"path";var tx=2*1024*1024;function xy(t,e,r){let n=Zr.resolve(t),i=Zr.isAbsolute(e)?Zr.resolve(e):Zr.resolve(n,e),a=Zr.relative(n,i).replaceAll("\\","/");return{root:n,relative:Gt(a,r),target:i}}async function Zt(t,e,r){let n=xy(t,e,r.label);return Y(n.root,n.relative,r)}async function Af(t,e,r){return(await Zt(t,e,{label:r.label,expected:r.expected??"any"})).exists}function Es(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}'
|
|
147
|
+
Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function ji(t){let e=Es(t);if(e)throw new Error(e)}function _y(t,e){return{label:H(t,e),directory:e}}async function Ry(t,e,r){let n=_y(t,e);if(!(await Zt(t,e,{label:r,expected:"directory"})).exists)return{change:n,exists:!1,stateExists:!1};let a=await Zt(t,Tf.join(e,".comet.yaml"),{label:`${r} state`,expected:"file"});return{change:n,exists:!0,stateExists:a.exists}}async function er(t,e=process.cwd()){ji(t);let r=await Le(e),n=await Ry(r.projectRoot,Tf.join(r.changesDir,t),`Classic active change ${t}`);return{...n.change,exists:n.exists,stateExists:n.stateExists}}import{promises as Ps}from"fs";import te from"path";function If(t,e){let r=te.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${te.sep}`)&&!te.isAbsolute(r)}async function Ay(t){let e=te.resolve(t),r=te.parse(e).root,n=[],i=e;for(;i&&i!==r;)try{let a=await Ps.realpath(i);return te.join(a,...n.reverse())}catch(a){let o=a.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw a;n.push(te.basename(i)),i=te.dirname(i)}try{let a=await Ps.realpath(r);return te.join(a,...n.reverse())}catch{return null}}async function Oi(t,e){let r=te.resolve(t),n=await Ps.realpath(r),i=[],a=[];for(let o of e){let s=te.isAbsolute(o)?te.resolve(o):te.resolve(r,o),c=await Ay(s);((c?If(n,c):If(r,s))?i:a).push(o)}return{projectTargets:i,externalTargets:a}}$i();var Cs=Ve($e(),1);De();import{execFileSync as $f}from"child_process";import{randomUUID as jy}from"crypto";import{promises as en}from"fs";import Lf from"path";function Oy(t){try{let e=$f("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var $y=Ss("liveGitBranch",t=>Oy(t));function Ly(t){try{return $f("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var Dy=Ss("isGitWorkTree",t=>Ly(t)),By=["current","branch","worktree"];function Df(t){return By.includes(t)}function My(t){return Df(t.isolation)?t.boundBranch===null&&t.currentBranch===null&&t.gitWorkTree===!1?{status:"not-applicable"}:t.boundBranch===null?t.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:t.currentBranch}:t.currentBranch===t.boundBranch?{status:"ok"}:{status:"drift",boundBranch:t.boundBranch,currentBranch:t.currentBranch}:{status:"not-applicable"}}async function Li(t,e){let r=Lf.join(t,".comet.yaml"),n=(0,Cs.parseDocument)(await en.readFile(r,"utf8"),{uniqueKeys:!1});if(n.errors.length>0)throw new Error(`Invalid .comet.yaml: ${n.errors[0].message}`);let i=n.toJS()??{},a=typeof i.isolation=="string"?i.isolation:null,o=typeof i.bound_branch=="string"&&i.bound_branch!==""?i.bound_branch:null,s=Df(a),c=$y(e.cwd),l=s&&o===null&&c===null?Dy(e.cwd):!0,u=My({isolation:a,boundBranch:o,currentBranch:c,gitWorkTree:l});return u.status==="needs-heal"&&e.heal?(await qy(t,u.branch),{status:"healed",branch:u.branch,bindingRequired:s,currentBranch:c}):{...u,bindingRequired:s,currentBranch:c}}async function qy(t,e){let r=Lf.join(t,".comet.yaml"),n=(0,Cs.parseDocument)(await en.readFile(r,"utf8"),{uniqueKeys:!1});n.set("bound_branch",e);let i=`${r}.${jy()}.tmp`;try{await en.writeFile(i,n.toString(),"utf8"),await en.rename(i,r)}catch(a){throw await en.rm(i,{force:!0}),a}}function Wy(t){return t??"detached HEAD"}function Di(t,e,r){return`change '${t}' is bound to branch '${e}', but current branch is '${Wy(r)}'`}function Bi(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}Ci();import Fy from"path";var xs="comet.selection.v2",Hy=16*1024;function _s(t){return Fy.join(t,".comet","current-change.json")}function Vy(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Bf(t){return t===null||typeof t=="string"}function zy(t){let e;try{e=JSON.parse(t)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!Vy(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!Bf(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:xs,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==xs)throw new Error(`current change selection schema must be ${xs}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!Bf(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function rr(t){let e;try{let n=_s(t),{bytes:i}=await Xt(n,Hy,{label:"current change selection"});e=i.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...zy(e)}}De();var Hi=Ve($e(),1);st();Ce();import Fi from"path";an();var Os=["full","hotfix","tweak"],td=1,nd=["open","design","build","verify","archive"],ab=["en","zh-CN"],ob=["off","beta"],sb=["subagent-driven-development","executing-plans","direct"],cb=["plan-ready"],lb=["confirmed"],ub=["tdd","direct"],fb=["off","standard","thorough"],db=["current","branch","worktree"],pb=["light","full"],hb=["pending","pass","fail"],mb=["pending","handled"],gb=["pending","confirmed"],$s=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],vb=["run_id"],id=new Set([...$s,...vb]),wb=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function rd(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function nr(t,e){let r=t[e];if(r==null||r==="")return null;if(typeof r!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return r}function G(t,e,r,n=!0){let i=t[e];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="string"||!r.includes(i))throw new Error(`Invalid Classic state: ${e} must be one of ${r.join(", ")}${n?" or null":""}`);return i}function js(t,e,r=!0){let n=t[e];if(n==null||n===""){if(r)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof n!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return n}function yb(t,e,r=0){let n=t[e];if(n==null||n==="")return r;if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return n}function Wi(t,e){let r=nr(t,e);if(r===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return r}function bb(t,e){let r=nr(t,e);if(r!==null&&!/^[a-f0-9]{64}$/u.test(r))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return r}function Nb(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==td)throw new Error(`Invalid Classic state: classic_migration must be ${td}`);return e}function kb(t){if(!$s.some(r=>rd(t,r)))return null;for(let r of wb)if(!rd(t,r))return null;return{workflow:G(t,"workflow",Os,!1),language:G(t,"language",ab),phase:G(t,"phase",nd,!1),contextCompression:G(t,"context_compression",ob),buildMode:G(t,"build_mode",sb),buildPause:G(t,"build_pause",cb),subagentDispatch:G(t,"subagent_dispatch",lb),tddMode:G(t,"tdd_mode",ub),reviewMode:G(t,"review_mode",fb),isolation:G(t,"isolation",db),boundBranch:nr(t,"bound_branch"),verifyMode:G(t,"verify_mode",pb),autoTransition:js(t,"auto_transition"),baseRef:nr(t,"base_ref"),designDoc:Wi(t,"design_doc"),plan:Wi(t,"plan"),verifyResult:G(t,"verify_result",hb,!1),verifyFailures:yb(t,"verify_failures"),verificationReport:Wi(t,"verification_report"),branchStatus:G(t,"branch_status",mb),createdAt:nr(t,"created_at"),verifiedAt:nr(t,"verified_at"),archiveConfirmation:G(t,"archive_confirmation",gb),archived:js(t,"archived",!1),directOverride:js(t,"direct_override"),handoffContext:Wi(t,"handoff_context"),handoffHash:bb(t,"handoff_hash"),classicProfile:G(t,"classic_profile",Os),classicMigration:Nb(t)}}function ad(t,e){let r=e??null;if(r===null&&e===void 0&&t.run_id&&t.skill)try{r=nn(t)}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(i.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:n})}return{classic:kb(t),run:r,unknownKeys:Object.keys(t).filter(n=>!id.has(n))}}function od(t){let e=t.workflow,r=t.phase,n=t.archived,i=t.design_doc;return{workflow:typeof e=="string"&&Os.includes(e)?e:null,phase:typeof r=="string"&&nd.includes(r)?r:null,archived:n===!0,designDoc:typeof i=="string"&&i!==""?i:null,unknownKeys:Object.keys(t).filter(a=>!id.has(a))}}an();var Sb=2*1024*1024;function on(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function Eb(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let r of e)t.delete(r)}function Pb(t){let e=!1;for(let r of["build_command","verify_command"])t.has(r)&&(t.delete(r),e=!0);return e}async function sd(t){let e;try{e=(await ie(Fi.dirname(t),Fi.basename(t),Sb,{label:"Classic state document"})).bytes.toString("utf8")}catch(n){if(n.code!=="ENOENT")throw n;return new Hi.Document({})}let r=(0,Hi.parseDocument)(e);if(r.errors.length>0)throw new Error(`Invalid Classic state document: ${r.errors[0].message}`);return on(r),r}async function Vi(t,e={}){let r=e.migrate!==!1,n=Fi.join(t,".comet.yaml"),i=await sd(n),a=on(i),o=Pb(i);o&&(a=on(i));let s=await Ts(t);if(!s&&a.run_id&&a.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(an(),ed));s=c(a),s&&r&&(await Is(t,s),Eb(i),o=!0)}return o&&r&&await xe(n,i.toString(),{containedRoot:t}),ad(on(i),s)}async function cd(t){let e=await sd(Fi.join(t,".comet.yaml"));return od(on(e))}var Ab=Ve($e(),1);var D_=8*1024*1024;import{execFileSync as Cb}from"child_process";import sn from"path";function ir(t,e){return Cb("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function xb(t,e){let r=sn.normalize(t),n=sn.normalize(e);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function ar(t){try{let e=sn.resolve(ir(t,["rev-parse","--show-toplevel"])),n=ir(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),i=n?sn.resolve(n.slice(9)):e,a=null;try{a=ir(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!xb(e,i),currentWorktreeRoot:e,primaryWorktreeRoot:i,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ld(t){try{ir(t,["rev-parse","--is-inside-work-tree"]);let e=ir(t,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],n=null;for(let i of e)i.startsWith("worktree ")?(n&&r.push(n),n={root:sn.resolve(i.slice(9)),branch:null,detached:!1}):n&&i.startsWith("branch refs/heads/")?n.branch=i.slice(18):n&&i==="detached"&&(n.detached=!0);return n&&r.push(n),r}catch{return[]}}function zi(t){return ld(t).map(e=>e.root)}function Ls(t,e){try{let r=ir(t,["rev-parse","--verify",`${e}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var Ob=X("readCometCurrentSelection",t=>rr(t));async function $b(t,e){ji(e);let r=await er(e,t);if(!r.stateExists)throw new Error(`Cannot select current change '${e}': active change state not found`);let n=await Vi(r.directory,{migrate:!1});if(!n.classic)throw new Error(`Cannot select current change '${e}': Classic state is incomplete`);if(n.classic.archived)throw new Error(`Cannot select current change '${e}': change is archived`);return r.directory}async function Gi(t){let e;try{e=await Ob(t)}catch(a){return{status:"stale",reason:a instanceof Error?a.message:String(a)}}if(e.status==="missing")return{status:"missing"};if(e.selection.workflow!=="classic")return{status:"stale",reason:`current change '${e.selection.change}' belongs to Native, not Classic`};let r=e.selection,n;try{n=await $b(t,r.change)}catch(a){return{status:"stale",reason:a instanceof Error?a.message:String(a)}}let i=await Li(n,{heal:!1,cwd:t});return i.status==="drift"?{status:"stale",reason:Di(r.change,i.boundBranch,i.currentBranch)}:i.status==="unbound-detached"?{status:"stale",reason:Bi(r.change)}:i.status==="ok"?{status:"selected",selection:r}:r.branch!==null&&i.currentBranch!==r.branch?{status:"stale",reason:`current change '${r.change}' was selected on branch '${r.branch}', current branch is '${i.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:r}}import kt from"node:path";async function ud(t,e){if(!e||e==="null")return{status:"missing",recordedPath:null};let r=await Le(t),n=kt.resolve(t,e),i=kt.relative(r.superpowersPlansDir,n);return kt.isAbsolute(e)||!i||i.startsWith(`..${kt.sep}`)||kt.isAbsolute(i)||i.includes(kt.sep)||kt.extname(i).toLowerCase()!==".md"?{status:"broken",recordedPath:e}:await Af(t,e,{label:`Classic build plan ${e}`,expected:"file"})?{status:"ready",recordedPath:e}:{status:"broken",recordedPath:e}}function pe(t,e){return{exitCode:t,stderr:e+`
|
|
148
|
+
`}}function _e(t){return pe(0,`[COMET-HOOK] allowed: ${t}`)}function ln(t){return t.replaceAll("\\","/").replace(/\/+/gu,"/")}function St(t){let e=ln(t);return process.platform==="win32"?e.toLowerCase():e}function fd(t,e){let r=ln(re.relative(e,t));return r===""?"":r.startsWith("../")||r===".."||re.isAbsolute(r)?null:r}async function Lb(t){let e=re.resolve(t),r=re.parse(e).root,n=[],i=e;for(;i&&i!==r;)try{let a=await Ui.realpath(i);return re.join(a,...n.reverse())}catch(a){let o=a.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw a;n.push(re.basename(i)),i=re.dirname(i)}try{let a=await Ui.realpath(r);return re.join(a,...n.reverse())}catch{return null}}async function Db(t,e){let r=re.isAbsolute(t)?t:re.resolve(e,t),n=ln(r),i=fd(r,e);if(i!==null)return i;try{let a=await Lb(r),o=await Ui.realpath(e);if(a){let s=fd(a,o);if(s!==null)return s;n=ln(a)}}catch{if(!re.isAbsolute(t))return ln(t).replace(/^\.\//u,"")}return n.replace(/^\.\//u,"")}async function md(t){try{let e=await Vi(t,{migrate:!1}),r=Array.from(new Set(e.unknownKeys)).sort();if(r.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${r.join(", ")}`);if(!e.classic)throw new Error("Classic state projection is unavailable");return{changeDir:t,phase:e.classic.phase,classic:e.classic,archived:e.classic.archived}}catch(e){let r=await cd(t);return r.phase?{changeDir:t,phase:r.phase,classic:null,archived:r.archived,invalidState:e instanceof Error&&e.message.includes("unknown field")}:null}}async function Bb(t){let e=(await Le(t)).changesDir,r=[];if(!(await Zt(t,e,{label:"Classic changes directory",expected:"directory"})).exists)return r;for(let i of(await Ui.readdir(e,{withFileTypes:!0})).sort((a,o)=>a.name.localeCompare(o.name))){if(i.name==="archive"||Es(i.name))continue;let a=await er(i.name,t);if(!a.exists||!a.stateExists)continue;let o=await md(a.directory);!o||o.archived||r.push(o)}return r}var un=X("classicActiveChanges",t=>Bb(t)),gd=X("classicPlanReadiness",ud);async function vd(t){return(await un(t)).map(e=>({workflow:"classic",name:he(e),phase:e.phase}))}function wd(t,e){return`${H(t,e.superpowersRoot)}/`}function yd(t,e){return St(t).startsWith(St(e))}function Mb(t,e){return[{prefix:`${H(t,e.superpowersSpecsDir)}/`,field:"designDoc",wireField:"design_doc",phase:"design"},{prefix:`${H(t,e.superpowersPlansDir)}/`,field:"plan",wireField:"plan",phase:"build"},{prefix:`${H(t,e.superpowersReportsDir)}/`,field:"verificationReport",wireField:"verification_report",phase:"verify"}]}function qb(t,e){let r=St(t),n=e.find(a=>r.startsWith(St(a.prefix)));if(!n)return null;let i=r.slice(St(n.prefix).length);return!i||i.includes("/")||!i.endsWith(".md")?null:n}function bd(t,e){return t.classic?.[e.field]??null}function Wb(t,e){return t.classic!==null&&t.phase===e.phase&&!bd(t,e)}async function dd(t,e,r){return Wb(e,r)?!0:r.field!=="plan"||e.phase!=="build"?!1:(await gd(t,e.classic?.plan??null)).status==="broken"}function Nd(t){return t.phase==="design"||t.phase==="build"||t.phase==="verify"}function he(t){return t.changeDir?re.basename(t.changeDir):null}var Fb=new Set(["design","plan","verify","verification","verification-report","report"]);function pd(t){return t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function Hb(t,e){return[e.classic?.designDoc,e.classic?.plan,e.classic?.verificationReport].some(n=>n&&St(n)===St(t))}function Vb(t,e){let n=(t.split("/").at(-1)??t).replace(/\.[^.]+$/u,"");if(n===e)return!0;let i=[...Fb].map(pd).join("|");return new RegExp(`(^|[-_.])${pd(e)}[-_.](${i})$`,"u").test(n)}async function zb(t,e){let r=await un(e),n=r.find(o=>Hb(t,o));if(n)return{governing:n,match:"recorded"};let a=r.filter(Nd).filter(o=>{let s=he(o);return s!==null&&Vb(t,s)}).sort((o,s)=>(he(s)?.length??0)-(he(o)?.length??0))[0];return a?{governing:a,match:"named"}:null}async function hd(t,e,r){let n=await un(t);if(n.length===0)return null;if(r)return n.find(o=>he(o)===r)??{blockedResult:cn(e,`selected change '${r}' is no longer active`)};let i=await Gi(t);if(i.status==="stale")return{blockedResult:cn(e,i.reason)};if(i.status==="selected"){let a=n.find(o=>he(o)===i.selection.change);return a||{blockedResult:cn(e,`selected change '${i.selection.change}' is no longer active`)}}if(n.length===1){let a=n[0];if(a.changeDir!==null){let o=await Li(a.changeDir,{heal:!1,cwd:t}),s=he(a)??"unknown";if(o.status==="drift")return{blockedResult:cn(e,Di(s,o.boundBranch,o.currentBranch))};if(o.status==="unbound-detached")return{blockedResult:cn(e,Bi(s))}}return a}return{blockedResult:tN(e,n.map(a=>he(a)).filter(Boolean))}}async function Gb(t,e,r,n){let i=`${H(e,r.changesDir)}/`;if(t.startsWith(i)){let a=t.slice(i.length),[o]=a.split("/");if(o&&o!=="archive"){let s=await er(o,e);if(s.stateExists){let c=await md(s.directory);return c||{changeDir:s.directory,phase:"open",classic:null,archived:!1}}return{changeDir:s.directory,phase:"open",classic:null,archived:!1}}}if(yd(t,wd(e,r))){let a=await zb(t,e);if(a?.match==="recorded")return{...a.governing,superpowersArtifact:"matched"};let o=qb(t,Mb(e,r));if(a)return o?{...a.governing,superpowersArtifact:await dd(e,a.governing,o)?"matched":"unmatched",superpowersSlot:o}:{...a.governing,superpowersArtifact:"matched"};if(o){let l=await hd(e,t,n);return!l||"blockedResult"in l?l:{...l,superpowersArtifact:await dd(e,l,o)?"matched":"unmatched",superpowersSlot:o}}let s=await un(e),c=n?s.find(l=>he(l)===n)??null:s[0]??null;return c?{...c,superpowersArtifact:"unmatched"}:null}return hd(e,t,n)}function Ub(t){return!t.includes("/")&&t.endsWith(".md")}function Kb(t){return t.startsWith(".comet/")||t.includes("/.comet/")}function Jb(t){return t===".superpowers"||t.startsWith(".superpowers/")}function Yb(t,e,r){if(!t.startsWith(r))return null;let n=t.endsWith("/.comet.yaml")||t.endsWith("/.openspec.yaml"),i=t.endsWith("/proposal.md")||t.endsWith("/design.md")||t.endsWith("/tasks.md"),a=t.includes("/.comet/"),o=t.includes("/specs/");return e==="open"&&(i||n||a||o)?`${t} (phase: open, openspec artifacts)`:e==="design"&&(i||n||a||o)?`${t} (phase: design, handoff/spec)`:e==="build"&&(t.endsWith("/tasks.md")||n||o)?`${t} (phase: build, spec/tasks)`:e==="verify"&&(t.endsWith("/tasks.md")||n)?`${t} (phase: verify, tasks/state)`:e==="archive"&&n?`${t} (phase: archive, state)`:null}function Xb(t,e){let r=e==="open"?[" BLOCKED: source writes are not allowed during open"," This phase does not allow source writes"," ALLOWED: create proposal/design/tasks artifacts and run guard"," NEXT: finish clarification and artifacts, then run guard --apply"]:e==="design"?[" BLOCKED: source writes are not allowed during design"," This phase does not allow source writes"," ALLOWED: run brainstorming, create the Design Doc, and run guard"," NEXT: finish the Design Doc, then run comet guard <change-name> design --apply to enter build"]:[" BLOCKED: source writes are not allowed during archive"," This phase does not allow source writes"," ALLOWED: confirm archive state and run the archive script"];return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e}`,` Target file: ${t}`,"",...r,""].join(`
|
|
149
|
+
`))}function Qb(t){return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," Current phase: build (workflow: full), but design_doc is empty",` Target file: ${t}`,""," BLOCKED: full workflow source writes require a recorded Design Doc"," This phase does not allow source writes until design_doc is recorded"," NEXT: return to design, create/link the Design Doc, then run guard again",""].join(`
|
|
150
|
+
`))}function Zb(t,e,r,n,i){let a=he(e)??"<change-name>",o=r.status==="missing",s=o?"classic-build-plan-missing":"classic-build-plan-broken",c=o?"plan is not recorded":"the recorded plan path does not resolve to a file",l=o?[]:[`RECORDED_PLAN: ${r.recordedPath}`],u=e.changeDir?H(n,e.changeDir):"<classic-change-dir>",f=H(n,i.superpowersPlansDir),d=o?`comet state set ${a} plan <repository-relative-plan-path>`:`comet state set ${a} plan <new-repository-relative-plan-path>`,h=o?["2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${a} design_doc" and read ${u}/tasks.md.`,`4. Create the implementation plan under ${f}/.`,"5. Record the plan path:",` ${d}`]:[`2. Restore the plan file at ${r.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under ${f}/.`,"3. When creating a replacement, record its path:",` ${d}`];return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",`ERROR_CODE: ${s}`,`CHANGE: ${a}`,"WORKFLOW: full","PHASE: build",`TARGET: ${t}`,`STATE: ${c}`,...l,"","BLOCKED: project source writes require a ready Superpowers implementation plan.","","ALLOWED_RECOVERY_WRITES:",`- ${f}/<plan-file>.md`,"- Comet state updates performed by the comet CLI",`- ${u} artifacts allowed by the build phase`,"","RECOVERY:",`1. Invoke /comet-build for ${a} and resume Step 1.`,...h,`${o?"6":"4"}. Verify recovery:`,` comet state check ${a} build --recover`,"","SUCCESS: plan is reported as DONE and recovery advances beyond plan creation.",`RETRY: retry the original Write/Edit for ${t} only after SUCCESS.`,"PROHIBITED: do not treat tasks.md as the implementation plan or write project source before SUCCESS.","If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this check.",""].join(`
|
|
151
|
+
`))}function eN(t,e){let r=e.superpowersSlot,n=r?bd(e,r):null,i=r?e.phase!==r.phase?[` BLOCKED: ${r.wireField} cannot be first-written in phase ${e.phase}`,` Expected phase: ${r.phase}`," NEXT: resume the matching Comet phase or use an already recorded artifact path"]:n?[` BLOCKED: ${r.wireField} is already recorded for this change`,` Recorded path: ${n}`," NEXT: write the recorded artifact or explicitly correct the state path"]:[" BLOCKED: standard Superpowers artifact state is incomplete"," NEXT: validate the active change state, then retry the matching phase"]:[" BLOCKED: unmatched Superpowers artifact"," This docs/superpowers/ path does not match any active change artifact"," NEXT: use a recorded artifact path or a standard phase artifact directory"];return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e.phase}`,` Target file: ${t}`,"",...i,""].join(`
|
|
152
|
+
`))}function tN(t,e){return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: multiple active changes require a current change",` Target file: ${t}`,` Active changes: ${e.join(", ")}`,""," NEXT: run comet state select <change-name>, then retry the source write",""].join(`
|
|
153
|
+
`))}function cn(t,e){return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: current change selection is stale or invalid",` Target file: ${t}`,` Reason: ${e}`,""," NEXT: run comet state select <change-name>, then retry the source write",""].join(`
|
|
154
|
+
`))}async function rN(t,e,r,n=Oi){try{if((await n(t,[e])).projectTargets.length===0)return _e(`${e} (outside guarded project)`)}catch(u){return pe(2,[`[COMET-HOOK] blocked: scope could not be determined safely for ${e}.`,`REASON: ${u instanceof Error?u.message:String(u)}`,"NEXT: verify that the project root is accessible, then retry the write."].join(`
|
|
155
|
+
`))}let i=await Db(e,t),a;try{a=await Ii(t)}catch(u){return pe(2,`[COMET-HOOK] blocked: ${u instanceof Error?u.message:String(u)}`)}if(Kb(i))return _e(`${i} (whitelist: comet config)`);if(Jb(i))return _e(`${i} (whitelist: superpowers workspace)`);if(i==="CLAUDE.md"||i==="CHANGELOG.md"||i==="README.md"||Ub(i))return _e(`${i} (whitelist: root markdown)`);let o=await tr(t,e,[re.join(t,".comet"),a.openSpecRoot,a.superpowersRoot]);if(o)return _e(o);let s;try{s=await Gb(i,t,a,r)}catch(u){return pe(2,`[COMET-HOOK] blocked: ${u instanceof Error?u.message:String(u)}`)}if(!s)return _e("no active comet change");if("blockedResult"in s)return s.blockedResult;if(s.archived)return _e(`${i} (own change archived)`);let c=s.phase,l=Yb(i,c,`${H(t,a.openSpecRoot)}/`);if(l)return _e(l);if(yd(i,wd(t,a))){if(s.superpowersArtifact==="matched"&&Nd(s))return _e(`${i} (phase: ${c}, superpowers)`);if(s.superpowersArtifact==="unmatched")return eN(i,s)}if(s.invalidState)return pe(2,`[COMET-HOOK] blocked: active Classic state is invalid; repair .comet.yaml before writing ${i}`);if(c==="build"&&s.classic?.workflow==="full"&&!s.classic.designDoc)return Qb(i);if(c==="build"&&s.classic?.workflow==="full"){let u=await gd(t,s.classic.plan);if(u.status!=="ready")return Zb(i,s,u,t,a)}return c==="build"||c==="verify"?_e(`${i} (phase: ${c})`):Xb(i,c)}async function kd(t,e,r,n={}){if(r.intent!=="non-write")try{await Ii(t)}catch(s){return{allowed:!1,reason:s instanceof Error?s.message:String(s),workflow:"classic",change:e}}let i;try{i=await un(t)}catch(s){return{allowed:!1,reason:s instanceof Error?s.message:String(s),workflow:"classic",change:e}}let a=i.find(s=>he(s)===e);if(!a)return{allowed:!1,reason:`Selected Classic change ${e} is missing or archived; resume /comet-classic before retrying`,workflow:"classic",change:e};if(r.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(r.intent==="unknown"||r.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"classic",change:e,phase:a.phase};let o=!1;for(let s of r.targets){let c=await rN(t,s,e,n.scopeTargets);if(c.exitCode!==0)return{allowed:!1,reason:c.stderr?.trim()||"Classic phase guard blocked the write",workflow:"classic",change:e,phase:a.phase};c.stderr?.includes("configured Hook allow path")&&(o=!0)}return{allowed:!0,reason:o?"Classic write allowed by configured Hook allow path":`Classic write allowed in ${a.phase}`,workflow:"classic",change:e,phase:a.phase}}De();import{promises as pE}from"fs";import be from"path";var oc=Ve($e(),1);import{promises as IS}from"fs";import Rt from"path";import{createHash as oN}from"node:crypto";import{promises as me}from"node:fs";import ae from"node:path";import{TextDecoder as sN}from"node:util";var nN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),iN=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function aN(t){return t.toLowerCase().startsWith(".env")}function Ds(t){let r=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return r.some(n=>aN(n))?"environment-file":r.some(n=>iN.has(n))?"credential-config":r.includes(".git")?"git-metadata":r.some(n=>nN.has(n))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}Gr();var cN=1024*1024;function Bs(t,e){let r=ae.relative(t,e);return r===""||!ae.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ae.sep}`)}function lN(t){let e=ae.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(i=>{let a=i.codePointAt(0)??0;return a<=31||a===127})||ae.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let r=t.toLowerCase(),n=Ds(t);if(n||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${t}`);return t}function uN(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function fN(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Ki(t,e){let r={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return nt(r,n)?A(r,n):A(r,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Sd(t){let e=await me.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await me.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function dN(t,e){let r=ae.resolve(t),n=ae.resolve(e);if(!Bs(r,n))throw new Error("Native artifact path is outside its root");let i=[await Sd(r)],a=r;for(let o of ae.relative(r,n).split(ae.sep).filter(Boolean)){a=ae.join(a,o);let s=await Sd(a);if(!Bs(i[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);i.push(s)}return i}async function Ed(t){for(let e of t){let r=await me.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!fN(e,r)||await me.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function lt(t){let e=lN(t.ref),r=t.maxBytes===null?null:uN(t.maxBytes??cN),n=ae.resolve(t.root,...e.split("/")),i=await dN(t.root,ae.dirname(n));await t.hooks?.afterParentChainCaptured?.();let a=await me.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);let o=await me.realpath(n);if(!Bs(i[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await me.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),me.lstat(n),me.realpath(n)]);if(await Ed(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Ki(a,c)||!Ki(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let f=[],d=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?h.length:r+1-d,S=await s.read(h,0,Math.min(h.length,k),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);f.push(Buffer.from(h.subarray(0,S.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([s.stat(),me.lstat(n),me.realpath(n)]);if(await Ed(i),!p.isFile()||p.isSymbolicLink()||m!==o||!Ki(c,v)||!Ki(c,p))throw new Error(`Native artifact changed while reading: ${e}`);let y=Buffer.concat(f,d),b;try{b=new sN("utf-8",{fatal:!0}).decode(y)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:d,hash:t.includeHash===!1?null:oN("sha256").update(y).digest("hex"),text:b}}finally{await s.close()}}import{randomUUID as pN}from"crypto";import{promises as V}from"fs";import ge from"path";function Ms(t,e){let r=ge.relative(t,e);return r===""||!ge.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ge.sep}`)}function hN(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function qs(t,e){return A({dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs},{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs})}function mN(t,e){return qs(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Pd(t){let e=await V.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await V.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function fn(t){for(let e of t){let r=await V.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!hN(e,r)||await V.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function gN(t,e){let r=ge.resolve(t),n=ge.resolve(e);if(!Ms(r,n))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let i=[await Pd(r)],a=ge.relative(r,n).split(ge.sep).filter(Boolean),o=r;for(let s of a){await fn(i),o=ge.join(o,s);try{await V.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Pd(o);if(!Ms(i[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);i.push(c)}return await fn(i),i}async function vN(t){let e;try{e=await V.open(t,"r"),await e.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await e?.close()}}async function wN(t,e,r={}){let n=ge.dirname(t),i=r.containedRoot?await gN(r.containedRoot,n):null;i||await V.mkdir(n,{recursive:!0});let a=ge.join(n,`.${ge.basename(t)}.${pN()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await V.open(a,"wx"),s=await o.stat(),i){let[l,u]=await Promise.all([V.lstat(a),V.realpath(a)]);if(await fn(i),!l.isFile()||l.isSymbolicLink()||!qs(s,l)||!Ms(i[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),c=await o.stat(),!qs(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.beforeCommit?.(),i){await fn(i);let l=await V.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!mN(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await V.link(a,t),await V.unlink(a)):await V.rename(a,t),await vN(n)}catch(l){if(await o?.close(),!i)await V.rm(a,{force:!0});else try{await fn(i),await V.rm(a,{force:!0})}catch{}throw l}}async function Be(t,e,r={}){await wN(t,e,r)}async function dn(t,e,r={}){await Be(t,JSON.stringify(e,null,2)+`
|
|
156
|
+
`,r)}Ee();at();Ti();var Ji=ki;async function Et(t){let e=(await bt(t))?.config??null;return e?.native?e:null}async function Yi(t){let e=await Et(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}import{promises as qk}from"fs";import Wk from"path";Ci();import{AsyncLocalStorage as yN}from"async_hooks";import{randomUUID as _d}from"crypto";import{promises as oe}from"fs";import Rd from"os";import U from"path";var Cd=16*1024,Ad=".coordinator",bN=5e3,xd=new yN,Xi=new Map;function NN(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function kN(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let r=t;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${e}`);return r}function Td(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function Ws(t,e){let r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},n={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return nt(r,n)?A(r,n):A(r,n)&&t.size===e.size}function Fs(t,e){return Ws(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function Me(t){let e,r;try{let n=await Xt(t,Cd,{bigint:!0,label:"Native lock"});e=n.bytes,r=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Pe?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Cd} bytes: ${t}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:n}):new Error(`Native lock changed while reading: ${t}`,{cause:n}):n}return{file:t,owner:kN(JSON.parse(e.toString("utf8")),t),identity:Td(r)}}async function SN(t){return(await Me(t))?.owner??null}function Id(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==Rd.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=RN(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function EN(t,e){try{await oe.lstat(e);return}catch(r){if(r.code!=="ENOENT")throw r}try{await oe.rename(t,e)}catch(r){if(r.code!=="ENOENT")throw r}}async function Hs(t,e){let r=await Me(t.file);if(!r)return"missing";if(r.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Fs(r.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await oe.mkdir(e,{recursive:!0});let n=U.join(e,`${U.basename(t.file)}.${t.owner.id}.${_d()}.removed`);try{await oe.rename(t.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let i=await Me(n);if(!i||i.owner.id!==t.owner.id||!Ws(i.identity,t.identity))throw await EN(n,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await oe.rm(n,{force:!0}),"removed"}function jd(t){return{id:_d(),pid:process.pid,hostname:Rd.hostname(),createdAt:new Date().toISOString(),operation:t}}async function Od(t,e){let r;try{r=await oe.open(t,"wx")}catch(n){if(n.code==="EEXIST"){let i=await SN(t);throw new Error(`Native lock is already held: ${t}${i?` by pid ${i.pid} for ${i.operation}`:""}`,{cause:n})}throw n}try{return await r.writeFile(JSON.stringify(e,null,2)+`
|
|
157
|
+
`,"utf8"),await r.sync(),Td(await r.stat({bigint:!0}))}finally{await r.close()}}async function PN(t,e){let r=await F(t.runtimeDir,t.locksDir);await oe.mkdir(r,{recursive:!0});let n=await F(t.runtimeDir,U.join(r,Ad));await oe.mkdir(n,{recursive:!0});let i=jd(e),a=U.join(n,`.${i.id}.tmp`),o=U.join(n,`${i.id}.claim`);try{let s=await Od(a,i);await oe.rename(a,o);let c=await Me(o);if(!c||!Ws(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.runtimeDir,locksDir:r,owner:i,identity:c.identity}}finally{await oe.rm(a,{force:!0})}}async function CN(t){let e=U.dirname(t.file),r=!1,n=U.basename(t.file);for(let i of await oe.readdir(e,{withFileTypes:!0})){if(!i.isFile()||i.isSymbolicLink()||!i.name.endsWith(".claim"))continue;let a=U.join(e,i.name);if(U.resolve(a)!==U.resolve(t.file))try{let o=await Me(a),s=Id(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Hs(o,e);continue}i.name<n&&(r=!0)}catch{i.name<n&&(r=!0)}}return r}async function $d(t){let e=await Me(t.file);if(e){if(e.owner.id!==t.owner.id||!Fs(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await Hs(e,U.dirname(t.file))}}async function xN(t,e){let r=Date.now()+bN;for(;;){let n=await PN(t,e);if(!await CN(n))return n;if(await $d(n),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(i=>setTimeout(i,2+Math.floor(Math.random()*7)))}}async function _N(t){let e=Xi.get(t)??Promise.resolve(),r,n=new Promise(a=>{r=a}),i=e.then(()=>n);return Xi.set(t,i),await e,()=>{r(),Xi.get(t)===i&&Xi.delete(t)}}async function Ld(t,e,r){let n=U.resolve(t.locksDir),i=xd.getStore();if(i?.has(n))return r();let a=await _N(n);try{let o=await xN(t,e),s=new Map(i??[]);return s.set(n,o),await xd.run(s,async()=>{try{return await r()}finally{await $d(o)}})}finally{a()}}async function Dd(t,e,r){return Ld(t,`acquire ${e}`,async()=>{let n=await F(t.runtimeDir,t.locksDir);await oe.mkdir(n,{recursive:!0});let i=await F(t.runtimeDir,U.join(n,NN(e))),a=jd(r),o=await Od(i,a);return{file:i,nativeRoot:t.runtimeDir,locksDir:n,owner:a,identity:o}})}async function Bd(t){await Me(t.file)&&await Ld({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${U.basename(t.file)}`,async()=>{let e=await Me(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Fs(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let r=U.join(t.locksDir,Ad);await Hs(e,r)})}function RN(t){try{return process.kill(t,0),!0}catch(e){let r=e.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function Md(t){return Id(await Me(t))}import lk from"node:path";var tA=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),rA=Object.freeze({maxCriteria:1024});var ea=Ve($e(),1);import{promises as IN}from"node:fs";var pn="comet.native.v4",hn="comet.native.local-execution.v4";var jN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ON=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$N=/^A[1-9][0-9]*$/u,LN=/^[a-f0-9]{64}$/u,DN=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Zi=class extends Error{constructor(r,n){super(`Native state version conflict: expected ${r}, got ${n}`);this.expectedStateVersion=r;this.actualStateVersion=n;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Q(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Z(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function W(t,e,r){if(typeof t!="string"||!r?.empty&&t.length===0)throw new Error(`${e} must be ${r?.empty?"a string":"a non-empty string"}`);return t}function zs(t,e){return t===null?null:W(t,e)}function BN(t,e){let r=W(t,e);if(!LN.test(r))throw new Error(`${e} must be a SHA-256 hash`);return r}function or(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function T(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function MN(t,e){return t===null?null:T(t,e,Number.MIN_SAFE_INTEGER)}function q(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function Re(t,e,r){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((n,i)=>r(n,i))}function ta(t,e){return Re(t,e,(r,n)=>W(r,`${e}[${n}]`))}function Pt(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function sr(t,e){let r=W(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO date or timestamp`);return r}function Gs(t,e,r=!1){let n=W(t,e);if(n.includes("\\")||n.startsWith("/")||/^[A-Za-z]:/u.test(n)||n.split("/").includes("..")||!r&&(n==="."||n.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return n}function ve(t,e){let r=Q(t,e);return Z(r,new Set(["text","truncated"]),e),{text:W(r.text,`${e}.text`,{empty:!0}),truncated:or(r.truncated,`${e}.truncated`)}}function qN(t,e){let r=`Native spec_changes[${e}]`,n=Q(t,r);Z(n,new Set(["capability","operation","source"]),r);let i=W(n.capability,`${r}.capability`);if(!ON.test(i))throw new Error(`${r}.capability is invalid`);let a=q(n.operation,["create","modify","remove"],`${r}.operation`),o=n.source===null?null:Gs(n.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:i,operation:a,source:o}}function WN(t){let e="Native workspace",r=Q(t,e);Z(r,new Set(["isolation","change_branch","target_branch","finish"]),e);let n=q(r.isolation,["current","branch","worktree"],`${e}.isolation`),i=zs(r.change_branch,`${e}.change_branch`),a=zs(r.target_branch,`${e}.target_branch`),o=r.finish===null?null:q(r.finish,["merge","push","pull-request","keep"],`${e}.finish`);if(n==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(n==="current"&&i===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(n!=="current"&&(i===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:n,change_branch:i,target_branch:a,finish:o}}function FN(t){let e="Native loop",r=Q(t,e);Z(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),e);let n=ta(r.previous_unresolved_ids,`${e}.previous_unresolved_ids`);return Pt(n,`${e}.previous_unresolved_ids`),{stage:q(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:T(r.goal_cycle,`${e}.goal_cycle`,1),iteration:T(r.iteration,`${e}.iteration`),attempt:T(r.attempt,`${e}.attempt`),retry_epoch:T(r.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:T(r.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:T(r.no_progress_count,`${e}.no_progress_count`),execution_failure_count:T(r.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:n,next_action:zs(r.next_action,`${e}.next_action`)}}function HN(t,e){let r=`Native acceptance[${e}]`,n=Q(t,r);Z(n,new Set(["id","source","text","result","reason"]),r);let i=W(n.id,`${r}.id`);if(!$N.test(i))throw new Error(`${r}.id must use A1, A2, ...`);return{id:i,source:Gs(n.source,`${r}.source`),text:W(n.text,`${r}.text`),result:q(n.result,["pending","passed","failed","blocked"],`${r}.result`),reason:n.reason===null?null:ve(n.reason,`${r}.reason`)}}function VN(t,e){let r=`Native builder_handoff.checks[${e}]`,n=Q(t,r);return Z(n,new Set(["name","result","note"]),r),{name:ve(n.name,`${r}.name`),result:q(n.result,["passed","failed","not-run"],`${r}.result`),note:n.note===null?null:ve(n.note,`${r}.note`)}}function zN(t){let e="Native builder_handoff",r=Q(t,e);Z(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),e);let n=ta(r.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);return Pt(n,`${e}.addressed_acceptance_ids`),{candidate_id:W(r.candidate_id,`${e}.candidate_id`),identity_provider:W(r.identity_provider,`${e}.identity_provider`),builder_execution_ref:W(r.builder_execution_ref,`${e}.builder_execution_ref`),iteration:T(r.iteration,`${e}.iteration`,1),summary:ve(r.summary,`${e}.summary`),addressed_acceptance_ids:n,checks:Re(r.checks,`${e}.checks`,VN),checks_truncated:or(r.checks_truncated,`${e}.checks_truncated`),known_limits:Re(r.known_limits,`${e}.known_limits`,(i,a)=>ve(i,`${e}.known_limits[${a}]`)),known_limits_truncated:or(r.known_limits_truncated,`${e}.known_limits_truncated`),submitted_at:sr(r.submitted_at,`${e}.submitted_at`)}}function GN(t,e){let r=`Native blockers[${e}]`,n=Q(t,r);Z(n,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let i=ta(n.acceptance_ids,`${r}.acceptance_ids`);return Pt(i,`${r}.acceptance_ids`),{owner:q(n.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ve(n.reason,`${r}.reason`),acceptance_ids:i,resolution_action:q(n.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function UN(t,e){let r=`Native verification.checks[${e}]`,n=Q(t,r);return Z(n,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:W(n.id,`${r}.id`),name:ve(n.name,`${r}.name`),argv_display:Re(n.argv_display,`${r}.argv_display`,(i,a)=>ve(i,`${r}.argv_display[${a}]`)),argv_truncated:or(n.argv_truncated,`${r}.argv_truncated`),cwd_ref:Gs(n.cwd_ref,`${r}.cwd_ref`,!0),status:q(n.status,["passed","failed","interrupted"],`${r}.status`),exit_code:MN(n.exit_code,`${r}.exit_code`),duration_ms:T(n.duration_ms,`${r}.duration_ms`)}}function KN(t){let e="Native verification",r=Q(t,e);Z(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let n=Re(r.checks,`${e}.checks`,UN);Pt(n.map(a=>a.id),`${e}.checks IDs`);let i=W(r.identity_provider,`${e}.identity_provider`);return{candidate_id:W(r.candidate_id,`${e}.candidate_id`),identity_provider:i,verifier_execution_ref:W(r.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:T(r.iteration,`${e}.iteration`,1),attempt:T(r.attempt,`${e}.attempt`,1),assurance:r.assurance===void 0?i==="skill-coordinated"?"skill-coordinated":"host-attested":q(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:q(r.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:n,summary:ve(r.summary,`${e}.summary`),risks:Re(r.risks,`${e}.risks`,(a,o)=>ve(a,`${e}.risks[${o}]`)),risks_truncated:or(r.risks_truncated,`${e}.risks_truncated`),completed_at:sr(r.completed_at,`${e}.completed_at`)}}function qd(t,e){let r=`Native history[${e}]`,n=Q(t,r);Z(n,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let i=ta(n.unresolved_ids,`${r}.unresolved_ids`);return Pt(i,`${r}.unresolved_ids`),{goal_cycle:T(n.goal_cycle,`${r}.goal_cycle`,1),iteration:T(n.iteration,`${r}.iteration`),attempt:T(n.attempt,`${r}.attempt`),outcome:q(n.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:i,summary:ve(n.summary,`${r}.summary`),completed_at:sr(n.completed_at,`${r}.completed_at`)}}function JN(t){let e="Native history_overflow.outcome_counts",r=Q(t,e),n=["pass","fail","blocked","execution-error","recovery"];return Z(r,new Set(n),e),{pass:T(r.pass,`${e}.pass`),fail:T(r.fail,`${e}.fail`),blocked:T(r.blocked,`${e}.blocked`),"execution-error":T(r["execution-error"],`${e}.execution-error`),recovery:T(r.recovery,`${e}.recovery`)}}function YN(t){let e="Native history_overflow",r=Q(t,e);Z(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let n=T(r.dropped_entries,`${e}.dropped_entries`),i=r.first_dropped_at===null?null:sr(r.first_dropped_at,`${e}.first_dropped_at`),a=r.last_dropped_at===null?null:sr(r.last_dropped_at,`${e}.last_dropped_at`);if(n===0&&(i!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(n>0&&(i===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=JN(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==n)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:n,first_dropped_at:i,last_dropped_at:a,outcome_counts:o}}function XN(t){let e=new Set(t.acceptance.map(r=>r.id));for(let r of t.loop.previous_unresolved_ids)if(!e.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of t.blockers)for(let n of r.acceptance_ids)if(!e.has(n))throw new Error(`Native blocker references unknown ID ${n}`);if(t.builder_handoff&&!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let n=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,i=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!n&&!i)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function QN(t){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let r=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(r!==null&&t.loop.stage!==r)throw new Error(`Native status ${t.status} requires loop stage ${r}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(n=>n.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(n=>n.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function Ae(t){let e=Q(t,"Native portable state");if(Z(e,DN,"Native portable state"),e.schema!==pn)throw new Error(`Native portable state schema must be ${pn}`);let r=W(e.name,"Native state name");if(!jN.test(r))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let n=Re(e.spec_changes,"Native spec_changes",qN);Pt(n.map(s=>s.capability),"Native spec change capabilities");let i=Re(e.acceptance,"Native acceptance",HN);Pt(i.map(s=>s.id),"Native acceptance IDs");let a=Re(e.history,"Native history",qd);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:pn,name:r,language:q(e.language,["en","zh-CN"],"Native state language"),phase:q(e.phase,["shape","build","verify","archive"],"Native state phase"),status:q(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:T(e.state_version,"Native state_version",1),brief:"brief.md",...e.children_contract_hash===void 0?{}:{children_contract_hash:BN(e.children_contract_hash,"Native children contract hash")},spec_changes:n,workspace:WN(e.workspace),loop:FN(e.loop),acceptance:i,builder_handoff:e.builder_handoff===null?null:zN(e.builder_handoff),blockers:Re(e.blockers,"Native blockers",GN),verification:e.verification===null?null:KN(e.verification),history:a,history_overflow:YN(e.history_overflow),verification_result:q(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:q(e.verification_report,["verification.md"],"Native verification_report"),archived:or(e.archived,"Native archived"),created_at:sr(e.created_at,"Native created_at")};return XN(o),QN(o),o}function ra(t,e){let r=Ae(t),n=qd(e,r.history.length),i=[...r.history,n],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;i.length>50;){let o=i.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return Ae({...r,history:i,history_overflow:a})}function ZN(t,e){let r=(0,ea.parseDocument)(t,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${e} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function mn(t){let e=await IN.readFile(t,"utf8");return Ae(ZN(e,"Native portable state"))}async function Wd(t,e,r={}){let n=Ae(e);await Be(t,(0,ea.stringify)(n),r)}var Qi=new Map;async function ek(t,e){let r=Qi.get(t)??Promise.resolve(),n,i=new Promise(o=>{n=o}),a=r.then(()=>i);Qi.set(t,a),await r;try{return await e()}finally{n(),Qi.get(t)===a&&Qi.delete(t)}}async function Fd(t){return ek(t.file,async()=>{let e=T(t.expectedStateVersion,"Native expected state version",1),r=Ae(t.next);if(r.state_version!==e+1)throw new Error("Native CAS next state_version must increment exactly once");let n=await mn(t.file);if(n.state_version===r.state_version&&JSON.stringify(n)===JSON.stringify(r))return n;if(n.state_version!==e)throw new Zi(e,n.state_version);return await Wd(t.file,r,{...t.containedRoot?{containedRoot:t.containedRoot}:{},beforeCommit:async()=>{let i=await mn(t.file);if(i.state_version!==e)throw new Zi(e,i.state_version)}}),r})}function tk(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function gn(t,e=16384){if(typeof t!="string")throw new Error("Native portable text must be a string");if(tk(e),Buffer.byteLength(t,"utf8")<=e)return{text:t,truncated:!1};let r="",n=0;for(let i of t){let a=Buffer.byteLength(i,"utf8");if(n+a>e)break;r+=i,n+=a}return{text:r,truncated:!0}}var qe="comet.native.v3",We="comet.native.v2",Fe="comet.native.v1";var Hd="comet.native.portable-migration.v1",rk=new Set(["schema","id","change","fromSchema","status","createdAt"]),nk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ik=/^[a-z0-9][a-z0-9-]{7,127}$/u,ak=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),ok=new Set([Fe,We,qe]);function sk(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ck(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let r=new Date(t);if(Number.isNaN(r.valueOf())||r.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function Vd(t){let e=sk(t,"Native portable migration transaction"),r=Object.keys(e).filter(n=>!rk.has(n));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(e.schema!==Hd)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!ik.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!nk.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!ok.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!ak.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Hd,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:ck(e.createdAt,"Native portable migration transaction createdAt")}}var Gd="comet.native.archive-transaction.v4",Ud="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",uk=new RegExp(`^portable-archive-(${Ud})\\.json$`,"u"),fk=new RegExp(`^portable-migration-(${Ud})\\.json$`,"u"),dk=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,pk=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hk=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),mk=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),gk=new Set(["capability","operation","source","content"]),Kd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Jd(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Yd(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(Object.keys(t).length!==e.size)throw new Error(`${r} fields are invalid`)}function vk(t,e){let r=`Native portable Archive spec_changes[${e}]`,n=Jd(t,r);if(Yd(n,gk,r),typeof n.capability!="string"||!Kd.test(n.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(n.operation)))throw new Error(`${r}.operation is invalid`);let i=n.operation;if(i==="remove"){if(n.source!==null||n.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:n.capability,operation:i,source:null,content:null}}if(typeof n.source!="string"||n.source.length===0||n.source.includes("\\")||n.source.startsWith("/")||/^[A-Za-z]:/u.test(n.source)||n.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${i} source is invalid`);if(typeof n.content!="string")throw new Error(`${r}.${i} content is invalid`);return{capability:n.capability,operation:i,source:n.source,content:n.content}}function wk(t){let e=Jd(t,"Native portable Archive transaction");if(Yd(e,mk,"Native portable Archive transaction"),e.schema!==Gd)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!dk.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!Kd.test(e.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(e.start_state_version)||Number(e.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof e.archive_ref!="string"||!pk.test(e.archive_ref)||!e.archive_ref.endsWith(`-${e.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof e.status!="string"||!hk.has(e.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=e.spec_changes.map(vk);if(new Set(r.map(({capability:i})=>i)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(e.next_spec_index)||Number(e.next_spec_index)<0||Number(e.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof e.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let n=new Date(e.created_at);if(Number.isNaN(n.valueOf())||n.toISOString()!==e.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Gd,id:e.id,change:e.change,start_state_version:Number(e.start_state_version),archive_ref:e.archive_ref,status:e.status,next_spec_index:Number(e.next_spec_index),spec_changes:r,created_at:e.created_at}}function Js(t){let e=uk.exec(t);if(e)return{kind:"archive",change:e[1]};let r=fk.exec(t);return r?{kind:"migration",change:r[1]}:null}async function Xd(t,e){let r=Js(e);if(!r)return null;let n=await lt({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),i=JSON.parse(n.text),a=lk.join(t.transactionsDir,e);if(r.kind==="archive"){let s=wk(i);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Vd(i);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function Qd(t){return t.kind==="archive"||t.journal.status!=="committed"}import He from"path";import{TextDecoder as xk}from"util";import{createHash as yk}from"node:crypto";import{constants as na,promises as we}from"node:fs";import ye from"node:path";import{TextDecoder as bk}from"node:util";function aa(t,e){let r=ye.relative(t,e);return r===""||!ye.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ye.sep}`)}function Nk(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function kk(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Sk(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function ia(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Ys(t,e){let r=await we.lstat(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await we.realpath(t),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Ek(t,e,r){let n=ye.resolve(t),i=ye.resolve(e);if(!aa(n,i))throw new Error(`${r} is outside its managed root`);let a=[await Ys(n,r)],o=n;for(let s of ye.relative(n,i).split(ye.sep).filter(Boolean)){await Ct(a,r),o=ye.join(o,s);let c=await Ys(o,r);if(!aa(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ct(a,r),a}async function Ct(t,e){for(let r of t){let n=await we.lstat(r.path);if(!n.isDirectory()||n.isSymbolicLink()||!kk(r,n)||await we.realpath(r.path)!==r.realPath)throw new Error(`${e} parent changed during I/O: ${r.path}`)}}async function Pk(t,e,r){let n=[],i=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-i,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(i+=s,i>e)throw new Error(`${r} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,i)}async function Xs(t){let e=Nk(t.maxBytes),r=ye.resolve(t.file),n=await Ek(t.root,ye.dirname(r),t.label),i=await Promise.all((t.forbiddenRoots??[]).map(u=>Ys(ye.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Ct(n,t.label);let a=await we.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=Sk(a),s=await we.realpath(r);if(!aa(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(i.some(u=>aa(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?na.O_RDONLY:na.O_RDONLY|na.O_NOFOLLOW|na.O_NONBLOCK,l=await we.open(r,c);try{let u=await l.stat();await t.hooks?.afterOpen?.();let[f,d]=await Promise.all([we.lstat(r),we.realpath(r)]);if(await Ct(n,t.label),await Ct(i,t.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!ia(o,u)||!ia(o,f))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let h=await Pk(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([l.stat(),we.lstat(r),we.realpath(r)]);if(await Ct(n,t.label),await Ct(i,t.label),!p.isFile()||p.isSymbolicLink()||m!==s||!ia(o,v)||!ia(o,p))throw new Error(`${t.label} changed while reading`);return{bytes:h,hash:yk("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Zd(t){let e=await Xs(t),r;try{r=new bk("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t.label} is not valid UTF-8`,{cause:n})}return{...e,text:r}}var _k=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Rk=new Set(["id","type","source","target","staged","backup"]),Ak=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Tk=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var tp=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Ik=256*1024,GA=1024*1024,UA=16*1024;var KA=64*1024*1024;var jk=new xk("utf-8",{fatal:!0});function sa(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ca(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function rp(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function Qs(t,e){if(typeof t!="string"||t.length===0||He.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function oa(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function ep(t,e){if(Qs(t,e),t.includes("\\")||t!==He.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function Ok(t,e){let r=sa(t,`transaction operations[${e}]`);if(ca(r,Rk,`transaction operations[${e}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${e}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);Qs(r.target,`transaction operation ${r.id} target`);for(let n of["source","staged","backup"])r[n]!==void 0&&Qs(r[n],`transaction operation ${r.id} ${n}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function $k(t){let e=sa(t,"Native Archive transaction journal");if(ca(e,Ak,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!tp.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!rp(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(oa(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=e.operations.map((s,c)=>{let l=sa(s,`Archive transaction operations[${c}]`);if(ca(l,Tk,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);ep(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&ep(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&oa(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(oa(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);oa(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=r.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let i=`runtime/transactions/${e.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${i}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${i}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:r}}function Lk(t){let e=sa(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return $k(e);if(ca(e,_k,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!tp.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!He.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!He.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!rp(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let r=e.operations.map(Ok),n=r.map(i=>i.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:r}}function Dk(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return He.join(t.transactionsDir,e)}function Bk(t,e){let r=Dk(t,e);return{directory:r,journal:He.join(r,"transaction.json"),events:He.join(r,"events.jsonl"),staged:He.join(r,"staged"),backups:He.join(r,"backups")}}async function Mk(t,e){let r=Bk(t,e);return await Promise.all(Object.values(r).map(n=>F(t.runtimeDir,n))),r}async function np(t,e,r={}){let n=await Mk(t,e),i=await Xs({root:t.runtimeDir,file:n.journal,maxBytes:Ik,label:`Native transaction journal ${e}`,hooks:r.hooks}),a=JSON.parse(jk.decode(i.bytes)),o=Lk(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function Fk(t,e,r){let n;try{n=await qk.readdir(t.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return!1;throw i}for(let i of n)if(!(!i.isDirectory()||i.isSymbolicLink()))try{let a=await np(t,i.name);if(a.id!==e&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let i of n)if(Js(i.name))try{let a=await Xd(t,i.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Qd(a))return!0}catch{return!0}return!1}async function Hk(t,e){let r=Date.now()+5e3,n=Wk.join(t.locksDir,"root-move.lock");for(;;)try{return await Dd(t,"root-move",e)}catch(i){if(i.cause?.code!=="EEXIST")throw i;let o=await Md(n);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw i;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function xt(t,e,r,n){let i=await Hk(t,e);try{if(await Yi(t.projectRoot),await Fk(t,n?.allowedTransactionId,n?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Bd(i)}}import ec from"path";import{createHash as Vk}from"crypto";function ip(t){return Vk("sha256").update(t).digest("hex")}var hT={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Gk=1e3,Uk=8*1024*1024,Kk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Jk=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),Yk=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),Xk=new Set(["schema","include","exclude","hash"]),Qk=new Set(["provider","gitSelection","physicalSelection","projection"]),Zk=new Set(["provider","selection"]),eS=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),tS=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),rS=new Set(["schema","status","before","after"]),nS=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),iS=new Set(["path","hash","size","type","gitObjectId"]),aS=new Set(["path","size","type","reason"]),oS=new Set(["ref","hash","count"]),sS=new Set(["change-created","legacy-migration","explicit"]),cS=new Set(["file","directory","other"]),lS=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"]),ua=/^[a-f0-9]{64}$/u,uS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var mT=64*1024,gT=64*1024;var vT={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},wT={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function la(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}var yT=(1n<<256n)-1n;function fS(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function dS(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
158
|
+
`)}function pS(t,e){return ip(`comet.native.snapshot-policy.v1
|
|
159
|
+
${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function Zs(t,e,r){let n=new Set(e),i=[...e];for(;i.length>0;){if(r&&!r())return null;let a=i.pop(),o=t[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),i.push(a+1))}return n}function hS(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function ap(t){let e=Ji(t,"Native snapshot pattern"),r=[];for(let n=0;n<e.length;n+=1){let i=e[n];i==="*"&&e[n+1]==="*"?(n+=1,e[n+1]==="/"?(n+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):i==="*"?r.push({kind:"star"}):i==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:i})}return(n,i)=>{let a=i?hS(i):void 0;if(a&&!a())return!1;let o=Zs(r,new Set([0]),a);if(o===null)return!1;for(let s of n){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Zs(r,c,a),o===null||o.size===0)return!1}return Zs(r,o,a)?.has(r.length)??!1}}function mS(t){if(t===void 0)return;let e=[...new Set(t.include.map(i=>Ji(i,"include")))].sort((i,a)=>i.localeCompare(a,"en")),r=[...new Set(t.exclude.map(i=>Ji(i,"exclude")))].sort((i,a)=>i.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let n=pS(e,r);if("hash"in t&&t.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:r,hash:n},includeMatchers:e.map(ap),excludeMatchers:r.map(ap),excludedDirectoryPrefixes:r.flatMap(i=>{if(!i.endsWith("/**"))return[];let a=i.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((i,a)=>i.localeCompare(a,"en"))}}function se(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ce(t,e,r){let n=Object.keys(t).find(i=>!e.has(i));if(n)throw new Error(`${r} contains unknown field: ${n}`)}function lr(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Te(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function cp(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let r=ec.posix.normalize(t);if(r!==t||ec.posix.isAbsolute(t)||r===".."||r.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function gS(t,e){let r=se(t,`Native snapshot entry ${e}`);ce(r,iS,`Native snapshot entry ${e}`);let n=cp(r.path,`Native snapshot entry ${e} path`);if(typeof r.hash!="string"||!ua.test(r.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let i={path:n,hash:r.hash,size:Te(r.size,`Native snapshot entry ${e} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!uS.test(r.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);i.gitObjectId=r.gitObjectId}return i}function vS(t,e){let r=se(t,`Native snapshot omission ${e}`);if(ce(r,aS,`Native snapshot omission ${e}`),!cS.has(r.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!lS.has(r.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:cp(r.path,`Native snapshot omission ${e} path`),size:r.size===null?null:Te(r.size,`Native snapshot omission ${e} size`),type:r.type,reason:r.reason}}function wS(t){let e=se(t,"Native snapshot omission overflow");if(ce(e,oS,"Native snapshot omission overflow"),typeof e.hash!="string"||!ua.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:e.hash,count:lr(e.count,"Native snapshot omission overflow count")}}function cr(t,e){let r=se(t,e);if(ce(r,tS,e),typeof r.hash!="string"||!ua.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let n=Te(r.recordCount,`${e} recordCount`),i=Te(r.storedRecordCount,`${e} storedRecordCount`),a=Te(r.stdoutBytes,`${e} stdoutBytes`);if(i>n||!r.overflow&&i!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,recordCount:n,storedRecordCount:i,stdoutBytes:a,overflow:r.overflow}}function op(t){let e=se(t,"Native Git selection evidence");if(ce(e,eS,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=cr(e.stageBefore,"Native Git selection stageBefore"),n=cr(e.combined,"Native Git selection combined"),i=cr(e.stageAfter,"Native Git selection stageAfter"),a=cr(e.finalStageBefore,"Native Git selection finalStageBefore"),o=cr(e.finalCombined,"Native Git selection finalCombined"),s=cr(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,n,i,a,o,s].some(f=>f.overflow),l=!la(r,i)||!la(i,a)||!la(n,o)||!la(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:n,stageAfter:i,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function sp(t,e){let r=se(t,e);if(ce(r,nS,e),typeof r.hash!="string"||!ua.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${e} flags are invalid`);let n=Te(r.visitedNodeCount,`${e} visitedNodeCount`),i=Te(r.recordCount,`${e} recordCount`),a=Te(r.storedRecordCount,`${e} storedRecordCount`),o=Te(r.encodedBytes,`${e} encodedBytes`);if(a>i||!r.overflow&&a!==i)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:n,recordCount:i,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function yS(t){let e=se(t,"Native physical selection evidence");if(ce(e,rS,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=sp(e.before,"Native physical selection before"),n=sp(e.after,"Native physical selection after"),i=r.overflow||n.overflow,a=r.unstable||n.unstable||!fS(r,n);if(!i&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=i&&a?"overflow-and-changed":i?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:n}}function bS(t){let e=se(t,"Native content snapshot manifest");if(ce(e,Jk,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!sS.has(e.origin))throw new Error("Native content snapshot origin is invalid");let r;if(e.capture!==void 0){let g=se(e.capture,"Native content snapshot capture");if(ce(g,Qk,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let C=g.gitSelection===void 0?void 0:op(g.gitSelection),N=g.physicalSelection===void 0?void 0:yS(g.physicalSelection),R=null;if(g.projection!==void 0){let ee=se(g.projection,"Native content snapshot projection");if(ce(ee,Zk,"Native content snapshot projection"),ee.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");R={provider:"git",...ee.selection===void 0?{}:{selection:op(ee.selection)}}}if(g.provider==="git"){if(N||R)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...C?{gitSelection:C}:{}}}else{if(C)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&R)throw new Error("Native physical-tree capture cannot combine selection and projection");r=R?{provider:"physical-tree",projection:R}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=se(e.limits,"Native content snapshot limits");ce(n,Yk,"Native content snapshot limits");let i={maxFiles:lr(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:lr(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:lr(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:lr(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:lr(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let g=se(e.policy,"Native snapshot policy");if(ce(g,Xk,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=mS({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(gS),s=e.omitted.map(vS),c=Te(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:wS(e.omissionOverflow);if(o.length>i.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>i.maxFileBytes)||o.reduce((g,C)=>g+C.size,0)>i.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Gk||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let f=s.filter(g=>g.reason==="git-enumeration-limit"),d=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...f,...d])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(f.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(f.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(g=>g.reason==="physical-enumeration-limit"),y=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...m,...y])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,k=b?.status==="overflow"||b?.status==="overflow-and-changed",S=b?.status==="changed"||b?.status==="overflow-and-changed";if(k!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:e.origin,...r?{capture:r}:{},createdAt:e.createdAt,complete:e.complete,limits:i,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(dS(E)>i.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function NS(t,e){if(!Kk.test(e))throw new Error(`Invalid Native change name: ${e}`);return ec.join(wt(t,e),"baseline-manifest.json")}async function lp(t,e){let r=NS(t,e),n=Yt(t,r);await F(n,r);try{let i=await Zd({root:n,file:r,maxBytes:Uk,label:"Native baseline snapshot manifest"});return bS(JSON.parse(i.text))}catch(i){if(i.code==="ENOENT")return null;throw i}}an();var IT={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import{createHash as SS}from"node:crypto";import{promises as fa}from"node:fs";import ut from"node:path";var vn=/^[a-f0-9]{64}$/u,up=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,ES=16*1024,rc=process.platform;function pp(t,e){let r=ut.relative(t,e);return ut.isAbsolute(r)||r===".."||r.startsWith(`..${ut.sep}`)?null:r.replaceAll("\\","/")||"."}function hp(t){return Array.from(t).some(e=>{let r=e.codePointAt(0)??0;return r<=31||r===127})}function mp(t,e){if(t.length===0||hp(t)||t.includes("\\")||ut.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let r=ut.posix.normalize(t);if(r!==t||r===".."||r.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return r}function nc(t,e){return SS("sha256").update(`${t}
|
|
160
|
+
${e}`).digest("hex")}async function fp(t,e){let r=await fa.realpath(e),n=await fa.lstat(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let i=rc==="win32"?ut.normalize(r).toLowerCase():r;return nc(t,`${i}
|
|
161
161
|
${n.dev}
|
|
162
162
|
${n.ino}
|
|
163
|
-
${n.birthtimeMs}`)}async function
|
|
163
|
+
${n.birthtimeMs}`)}async function dp(t,e){let r=await fa.realpath(e),n=await fa.lstat(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let i=rc==="win32"?ut.normalize(r).toLowerCase():r;return nc(t,i)}function PS(t){if(typeof t!="string")throw new Error("Native workspace capturedAt is invalid");let e=new Date(t);if(!Number.isFinite(e.getTime())||e.toISOString()!==t)throw new Error("Native workspace capturedAt is invalid");return t}function tc(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||hp(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function gp(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(tc(t.changeBranch,"Native workspace change branch"),tc(t.targetBranch,"Native workspace target branch"),(t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function CS(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace Git provenance must be an object");let e=t,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),n=Object.keys(e).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${n.join(", ")}`);if(e.provider!=="git"||typeof e.baseCommit!="string"||!up.test(e.baseCommit)||typeof e.targetCommit!="string"||!up.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");tc(e.targetBranch,"Native workspace Git target branch")}function da(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace identity must be an object");let e=t,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),n=Object.keys(e).filter(o=>!r.has(o));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(e.schema!=="comet.native.workspace.v2"&&e.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(e.capturedRevision)||e.capturedRevision<1||typeof e.nativeRootRef!="string"||!vn.test(String(e.projectRootId))||!vn.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");PS(e.capturedAt),mp(e.nativeRootRef,"Native workspace root ref");let i=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(i!==a)throw new Error("Native workspace path identities must be provided together");if(i&&!vn.test(String(e.projectRootPathId))||a&&!vn.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!vn.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&CS(e.git),e.schema==="comet.native.workspace.v2"){if(e.isolation!==void 0||e.changeBranch!==void 0||e.targetBranch!==void 0||e.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof e.isolation!="string"||e.changeBranch===void 0||e.targetBranch===void 0||e.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(gp(e),e.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(e.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function xS(t,e){return ut.join(wt(t,e),"workspace.json")}function _S(t,e){let r=xS(t,e),n=Yt(t,r),i=pp(n,r);if(!i||i===".")throw new Error("Native workspace file escaped its root");return{root:n,ref:mp(i,"Native workspace file ref")}}async function RS(t,e){try{let r=_S(t,e),n=await lt({root:r.root,ref:r.ref,maxBytes:ES});return JSON.parse(n.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function AS(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=pp(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let r=ar(t.paths.projectRoot),n=r.isGitWorktree?Ls(t.paths.projectRoot,"HEAD"):null,i=t.binding?.targetBranch??r.currentBranch,a=i==null?null:Ls(t.paths.projectRoot,i),o=n!==null&&i!==null&&i!==void 0&&a!==null?{provider:"git",baseCommit:n,targetBranch:i,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([fp("comet.native.workspace-project-root.v2",t.paths.projectRoot),fp("comet.native.workspace-native-root.v2",t.paths.nativeRoot),dp("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),dp("comet.native.workspace-native-root-path.v2",t.paths.nativeRoot)]),f=(t.now??new Date).toISOString();if(t.finish&&!t.binding)throw new Error("Native workspace finish requires a workspace binding");t.binding&&gp(t.binding);let d={capturedAt:f,capturedRevision:t.revision,nativeRootRef:e,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...t.sessionId?{sessionHash:nc("comet.native.workspace-session.v2",`${s}
|
|
164
164
|
${c}
|
|
165
|
-
${t.sessionId}`)}:{}},h=t.binding?{schema:"comet.native.workspace.v3",...d,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...d};return
|
|
166
|
-
`);function wn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Np(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function ma(t){if(!bp.test(t))throw new Error(`Invalid Native change name: ${t}`)}function IS(t){if(!bp.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function kp(t,e){if(t.length===0||_t.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function jS(t,e){let r=wn(t,`spec_changes[${e}]`);if(Np(r,xS,`spec_changes[${e}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(IS(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let n=r.source,i=r.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof n=="string"&&kp(n,`Spec source for ${r.capability}`),r.operation==="create"){if(!n)throw new Error(`Create spec ${r.capability} requires source`);if(i!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!n)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof i!="string"||!ic.test(i))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof i!="string"||!ic.test(i))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof n=="string"?{source:n}:{},base_hash:i}}function OS(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function oc(t,e){if(Np(t,e,lr),typeof t.name!="string")throw new Error("Native change name is required");if(ma(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!_S.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!RS.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let r=t.spec_changes.map(jS),n=r.map(i=>i.capability).filter((i,a,o)=>o.indexOf(i)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof t.verification_result!="string"||!AS.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&kp(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!OS(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:r,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Gs(t){let e=wn(t,lr);if(e.schema!==He)throw new Error(`Expected ${He}`);return{schema:He,...oc(e,PS)}}function vn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function nc(t,e,r){if(t===null)return null;let n=typeof t=="string"?TS.exec(t):null;if(!n||n[1]!==r)throw new Error(`${e} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return t}function $S(t){if(t==null)return null;if(typeof t!="string"||!ic.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function LS(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Ks(t){let e=wn(t,lr);if(e.schema!==Fe)throw new Error(`Expected ${Fe}`);if(vn(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Fe} minimum_runtime_version must be 2`);return{schema:Fe,minimum_runtime_version:2,revision:vn(e.revision,"Native v2 revision"),...oc(e,yp)}}function Fd(t){let e=wn(t,lr);if(e.schema!==qe){if(e.schema===He||e.schema===Fe){let o=e.schema===He?Gs(e):Ks(e);throw new ha(o.name,o.schema)}throw new Rt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let r=vn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Rt(e.schema,r);if(r!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=vn(e.revision,"Native revision"),i=oc(e,CS),a=$S(e.approved_contract_hash);if(i.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:qe,minimum_runtime_version:3,revision:n,verification_protocol:LS(e.verification_protocol),...i,approved_contract_hash:a,implementation_scope:nc(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:nc(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:nc(e.partial_allowance,"Native partial_allowance","allowances")}}function DS(t){let e=wn(t,lr);if(e.schema===He){let i=Gs(e);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:1,state:i,message:`Native change ${i.name} requires migration to ${qe}`}}if(e.schema===Fe){let i=Ks(e);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i,message:`Native change ${i.name} requires migration to ${qe}`}}if(e.schema!==qe){let i=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:i,state:null,message:new Rt(typeof e.schema=="string"?e.schema:"(missing)",i).message}}let r=vn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:r,state:null,message:new Rt(e.schema,r).message};let n=Fd(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function BS(t,e){ma(e);let r=_t.join(t.changesDir,e);if(!pe(t.changesDir,r))throw new Error("Native change path escaped");return r}async function MS(t,e){let r=vt(t,e),n=_t.join(r,"schema-migration.json");await F(pe(t.runtimeDir,n)?t.runtimeDir:t.nativeRoot,n);try{return await ES.lstat(n),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}}var WS=256*1024;async function qS(t,e=_t.dirname(t)){let r=_t.relative(e,t).split(_t.sep).join("/"),n=await ct({root:e,ref:r,maxBytes:WS}),i=(0,ac.parseDocument)(n.text,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${i.errors[0].message}`);return i.toJS()}async function FS(t,e){let r=_t.join(BS(t,e),lr);await F(t.nativeRoot,r);let n=DS(await qS(r,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await MS(t,e)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(n.status==="current"&&n.state&&await HS(t,n.state),n)}async function HS(t,e){if(await op(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function ga(t,e){let r=await FS(t,e);if(r.status==="migration-required")throw new ha(e,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Rt(r.schema,r.minimumRuntimeVersion);return await vp(t,e),r.state}Li();import{promises as Cp}from"node:fs";import Na from"node:path";var VS=ze(Le(),1);var gI=["$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("; ");function KS(t){return t.state_version+1}function JS(t){return t.map(e=>({...e,result:"pending",reason:null}))}function US(t){return{goal_cycle:t.state.loop.goal_cycle,iteration:t.state.loop.iteration,attempt:t.state.loop.attempt,outcome:t.outcome,unresolved_ids:t.unresolvedIds??[],summary:mn(t.summary),completed_at:t.completedAt}}function Sp(t){let e=Te(t.state);if(e.phase!=="verify"&&e.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(t.now??new Date).toISOString(),n=na(e,US({state:e,outcome:"recovery",summary:t.reason,completedAt:r}));return Te({...n,phase:"build",status:"active",state_version:KS(e),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:JS(e.acceptance),loop:{...e.loop,stage:"repairing",iteration:e.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as YS}from"node:fs";import yn from"node:path";function va(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function wa(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function je(t,e,r=!1){if(typeof t!="string"||!r&&t.length===0)throw new Error(`${e} must be ${r?"a string":"a non-empty string"}`);return t}function Ep(t,e){return t===null?null:je(t,e)}function ba(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function XS(t,e){if(t===null)return null;if(!Number.isSafeInteger(t))throw new Error(`${e} must be null or a safe integer`);return t}function QS(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function ya(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function sc(t,e){if(t===null)return null;let r=je(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO timestamp`);return r}function cc(t,e){let r=je(t,e);if(!yn.isAbsolute(r))throw new Error(`${e} must be absolute`);return yn.resolve(r)}function ZS(t,e){let r=`Native local checks[${e}]`,n=va(t,r);if(wa(n,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(n.argv)||n.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let i=n.argv.map((l,u)=>je(l,`${r}.argv[${u}]`,!0)),a=ya(n.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=sc(n.startedAt,`${r}.startedAt`),s=sc(n.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=ba(n.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:je(n.id,`${r}.id`),name:je(n.name,`${r}.name`),operationId:je(n.operationId,`${r}.operationId`),status:a,repeatable:QS(n.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:ba(n.executionCount,`${r}.executionCount`),argv:i,cwd:cc(n.cwd,`${r}.cwd`),exitCode:XS(n.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:je(n.log,`${r}.log`)}}function Pp(t){let e="Native local execution state",r=va(t,e);if(wa(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),e),r.schema!==pn)throw new Error(`Native local execution schema must be ${pn}`);let n=va(r.workspace,"Native local workspace");wa(n,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let i=null;if(r.execution!==null){let o=va(r.execution,"Native local execution");wa(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=sc(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");i={operationId:je(o.operationId,"Native local execution.operationId"),stage:ya(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:ya(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Ep(o.executionId,"Native local execution.executionId"),status:ya(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ba(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(ZS);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(i&&a.some(o=>o.operationId!==i.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:pn,change:je(r.change,"Native local change"),basedOnStateVersion:ba(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:cc(n.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:cc(n.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Ep(n.branch,"Native local workspace.branch")},execution:i,checks:a}}function lc(t){return Pp({schema:pn,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,workspace:{projectRoot:yn.resolve(t.projectRoot),worktreeRoot:yn.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null},execution:null,checks:[]})}async function uc(t,e,r={}){let n=Pp(e);await YS.mkdir(yn.dirname(t),{recursive:!0}),await fn(t,n,r)}var eE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tE="comet-state.yaml",rE="state.json";function ka(t,e){if(!eE.test(e))throw new Error(`Invalid Native change name: ${e}`);let r=Na.join(t.changesDir,e);if(!pe(t.changesDir,r))throw new Error("Native change path escaped");return r}function fc(t,e){return Na.join(ka(t,e),tE)}function xp(t,e){return Na.join(Si(t,e),rE)}async function Sa(t,e){try{let r=await Cp.readFile(fc(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function _p(t){return ir(t).currentBranch}async function ur(t,e){return hn(fc(t,e))}async function Rp(t){let e=await Md({file:fc(t.paths,t.previous.name),expectedStateVersion:t.previous.state_version,next:t.next,containedRoot:t.paths.nativeRoot});if(e.verification===null&&e.verification_report===null){let r=Na.join(ka(t.paths,e.name),"verification.md");await F(t.paths.nativeRoot,r),await Cp.rm(r,{force:!0})}return e}async function Ap(t){return Ct(t.paths,`return portable change ${t.name} to Build`,async()=>{let e=await ur(t.paths,t.name);if(e.phase==="build")return e;let r=Sp({state:e,reason:t.reason}),n=await Rp({paths:t.paths,previous:e,next:r});return await uc(xp(t.paths,e.name),lc({portableState:n,projectRoot:t.paths.projectRoot,branch:_p(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),n})}async function Tp(t){return Ct(t.paths,`return portable change ${t.name} to Shape`,async()=>{let e=await ur(t.paths,t.name);return e.phase==="shape"?e:nE({paths:t.paths,state:e,reason:t.reason})})}async function nE(t){let{state:e}=t;if(e.archived)throw new Error(`Native change ${e.name} is already archived`);let n={...na(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:mn(t.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:e.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete n.children_contract_hash;let i=await Rp({paths:t.paths,previous:e,next:n});return await uc(xp(t.paths,e.name),lc({portableState:i,projectRoot:t.paths.projectRoot,branch:_p(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),i}var Kj=16*1024;async function iE(t){let e=await tr(t.projectRoot);return e.status==="missing"||e.selection.workflow!=="native"?null:(ma(e.selection.change),e.selection)}async function Ip(t){let e=await iE(t);return e?(await Sa(t,e.change)?await ur(t,e.change):await ga(t,e.change),e.change):null}async function oE(t){let{projectRoot:e,paths:r,state:n,request:i}=t,a=ka(r,n.name),o=[],s=[],c=!1,l=!1,u=!1;for(let f of i.targets){let d=Ne.resolve(e,f);if(!At(e,d)){u=!0;continue}let h=Ne.relative(e,d).replaceAll("\\","/");if(h===".comet/config.yaml"){l=!0;continue}if(!At(r.nativeRoot,d)){if(await er(e,d,[Ne.join(e,".comet"),r.nativeRoot])){c=!0;continue}s.push(h);continue}if(!At(a,d))return{allowed:!1,reason:"Portable Native control state is Runtime-owned",workflow:"native",phase:n.phase,change:n.name};let v=Ne.relative(a,d).replaceAll("\\","/");if(v==="brief.md"||v==="children.yaml"||v.startsWith("specs/")){o.push(v);continue}return{allowed:!1,reason:`${v||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:n.phase,change:n.name}}return o.length>0&&s.length>0?{allowed:!1,reason:"Formal Native requirements and implementation files must be edited in separate actions",workflow:"native",phase:n.phase,change:n.name}:o.length>0?n.phase!=="shape"?{allowed:!0,reason:`Native requirements changed; returned to Shape goal cycle ${(await Tp({paths:r,name:n.name,reason:`Formal requirement write requested for ${o.join(", ")}`})).loop.goal_cycle}`,workflow:"native",phase:"shape",change:n.name}:{allowed:!0,reason:"Native control artifact write",workflow:"native",phase:n.phase,change:n.name}:s.length>0?n.children_contract_hash?{allowed:!1,reason:"Native parent Build advances child changes instead of editing implementation",workflow:"native",phase:n.phase,change:n.name}:n.phase==="build"?{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:n.phase,change:n.name}:n.phase==="verify"||n.phase==="archive"?{allowed:!0,reason:`Native candidate was invalidated and returned to Build iteration ${(await Ap({paths:r,name:n.name,reason:`Observed implementation write before ${s.join(", ")}`})).loop.iteration}`,workflow:"native",phase:"build",change:n.name}:{allowed:!1,reason:`Native change ${n.name} is in ${n.phase}; implementation writes are only allowed in Build`,workflow:"native",phase:n.phase,change:n.name}:c?{allowed:!0,reason:"Native configured Hook allow path",workflow:"native",phase:n.phase,change:n.name}:{allowed:!0,reason:l?"Native control artifact write":u?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:n.phase,change:n.name}}function At(t,e){let r=Ne.relative(t,e);return r===""||!r.startsWith("..")&&!Ne.isAbsolute(r)}function sE(t,e,r){return r.targets.length>0&&r.targets.every(n=>{let i=Ne.resolve(t,n);return At(t,i)?Ne.relative(t,i).replaceAll("\\","/")===".comet/config.yaml"||At(e,i):!0})}async function cE(t){let e=await St(t);if(!e||!(e.workflows??[e.default_workflow]).includes("native"))return null;let r=await Hr(t,e.native.artifact_root),n;try{n=await aE.readdir(r.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:r,changes:[]};throw a}let i=[];for(let a of n.sort((o,s)=>o.name.localeCompare(s.name)))if(!(!a.isDirectory()||a.isSymbolicLink()))if(await Sa(r,a.name)){let o=await ur(r,a.name);o.archived||i.push({kind:"portable",state:o})}else{let o=await ga(r,a.name);o.archived||i.push({kind:"legacy",state:o})}return{paths:r,changes:i}}var jp=X("nativeActiveContext",t=>cE(t));async function Op(t){return((await jp(t))?.changes??[]).map(r=>({workflow:"native",name:r.state.name,phase:r.state.phase}))}async function $p(t,e,r){let n=await jp(t);if(!n)return{allowed:!0,reason:"Native workflow is not enabled"};if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(n.changes.length===0)return{allowed:!0,reason:sE(t,n.paths.nativeRoot,e)?"Native control artifact write":"No Native changes exist"};let i;if(r){if(i=n.changes.find(l=>l.state.name===r),!i)return{allowed:!1,reason:`Selected Native change ${r} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:r}}else if(n.changes.length===1)i=n.changes[0];else{let l=await Ip(n.paths);if(i=n.changes.find(u=>u.state.name===l),!i)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let a=i.state;if(i.kind==="legacy"&&a.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:a.phase,change:a.name};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:a.phase,change:a.name};if(i.kind==="portable")return oE({projectRoot:t,paths:n.paths,state:i.state,request:e});let o=!1,s=!1,c=!1;for(let l of e.targets){let u=Ne.resolve(t,l);if(!At(t,u)){s=!0;continue}if(Ne.relative(t,u).replaceAll("\\","/")===".comet/config.yaml"){o=!0;continue}if(At(n.paths.nativeRoot,u)){o=!0;continue}if(await er(t,u,[Ne.join(t,".comet"),n.paths.nativeRoot])){c=!0;continue}return{allowed:!1,reason:`Native change ${a.name} is in ${a.phase}; implementation writes are only allowed in build. If this belongs to the current change, confirm the scope and run comet native next ${a.name} --summary "<reason>" --return-to-build; otherwise create or select a separate Native change`,workflow:"native",phase:a.phase,change:a.name}}return{allowed:!0,reason:o?"Native control artifact write":s?"Write target is outside the guarded project":c?"Native configured Hook allow path":"No guarded write target was provided",workflow:"native",phase:a.phase,change:a.name}}Be();Be();it();var Lp=X("readWorkflowProjectConfig",t=>Ur(t)),lO=X("discoverNativeProject",t=>Fr(t));var lE=X("readCometCurrentSelection",t=>tr(t)),Mp={listNative:Op,listClassic:hd,inspectNative:$p,inspectClassic:yd};function uE(t){return t?t.workflows??[t.default_workflow]:["classic"]}async function Dp(t,e,r,n,i={}){let a=async()=>{if(!e.includes("classic"))return[];if(n?.workflow==="classic")return n.candidates;try{return await r.listClassic(t)}catch(c){if(i.tolerateUnavailableClassic&&c instanceof st)return[];throw c}},[o,s]=await Promise.all([e.includes("native")?n?.workflow==="native"?n.candidates:r.listNative(t):[],a()]);return[...o,...s]}function Bp(t,e){return t.length===0?{status:"none",staleSelection:e}:t.length===1?{status:"inferred",owner:t[0],staleSelection:e}:{status:"ambiguous",candidates:t,staleSelection:e}}async function fE(t,e=Mp){let r=await Lp(t),n=uE(r),i;try{i=await lE(t)}catch(a){return{status:"stale",code:"selection-unreadable",reason:a instanceof Error?a.message:String(a)}}if(i.status==="selected"){let a=i.selection;if(!n.includes(a.workflow))return{status:"stale",code:"workflow-disabled",reason:`selected workflow '${a.workflow}' is not enabled for this project`};let o;try{o=a.workflow==="native"?await e.listNative(t):await e.listClassic(t)}catch(c){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${c instanceof Error?c.message:String(c)}`}}let s=o.find(c=>c.name===a.change);if(!s){let c={code:"target-missing",reason:`selected ${a.workflow} change '${a.change}' is missing or archived`};try{let l=await Dp(t,n,e,{workflow:a.workflow,candidates:o});return Bp(l,c)}catch(l){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${l instanceof Error?l.message:String(l)}`}}}if(a.workflow==="classic"){let c=await Ki(t);if(c.status!=="selected")return{status:"stale",code:"classic-selection-invalid",reason:c.status==="stale"?c.reason:`selected Classic change '${a.change}' is no longer active`}}return{status:"owned",owner:s}}try{let a=await Dp(t,n,e,void 0,{tolerateUnavailableClassic:!0});return Bp(a)}catch(a){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${a instanceof Error?a.message:String(a)}`}}}async function Wp(t,e,r=Mp){if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target is outside Comet attribution"};let n;try{let i=await(r.scopeTargets??$i)(t,e.targets);if(i.projectTargets.length===0)return{allowed:!0,reason:"Write targets are outside the guarded project"};n={...e,targets:i.projectTargets}}catch(i){return{allowed:!1,reason:["Comet Hook Router scope could not be determined safely.",`Reason: ${i instanceof Error?i.message:String(i)}`,"Next: verify that the project root is accessible, then retry the write."].join(" ")}}try{let i=await fE(t,r);if(i.status==="none")return{allowed:!0,reason:"No active Comet change"};if(i.status==="stale")return{allowed:!1,reason:`${i.reason}. Resume /comet-native or /comet-classic and select the current change before retrying`};if(i.status==="ambiguous")return{allowed:!1,reason:`Multiple active Comet changes require one current selection: ${i.candidates.map(o=>`${o.workflow}:${o.name}`).join(", ")}`};let a=i.owner;return a.workflow==="native"?r.inspectNative(t,n,a.name):r.inspectClassic(t,a.name,n)}catch(i){return{allowed:!1,reason:`Comet Hook Router failed closed: ${i instanceof Error?i.message:String(i)}`}}}import{promises as dE}from"fs";import ue from"path";function pE(t,e){let r=ue.resolve(t),n=ue.resolve(e);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function hE(t,e){let r=ue.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${ue.sep}`)&&!ue.isAbsolute(r)}function qp(t,e){return[...e].sort((r,n)=>n.length-r.length).find(r=>hE(r,t))??null}async function mE(t){for(let e of[".git",ue.join(".comet","config.yaml")])try{await dE.lstat(ue.join(t,e))}catch(r){throw r.code!=="ENOENT"?r:new Error(`linked worktree ${t} is not initialized for Comet: missing ${e.replaceAll("\\","/")}`,{cause:r})}}async function Fp(t,e){let r=ue.resolve(t),n=Gi(r);if(n.length<2||e.targets.length===0)return r;let a=(e.cwd?qp(ue.resolve(e.cwd),n):null)??r,o=new Map;for(let c of e.targets){let l=ue.isAbsolute(c)?ue.resolve(c):ue.resolve(a,c),u=qp(l,n);if(!u)continue;let f=process.platform==="win32"?u.toLowerCase():u;o.set(f,u)}if(o.size===0)return r;if(o.size>1)throw new Error("one Hook request cannot write across multiple Git worktrees");let[s]=o.values();return pE(s,r)||await mE(s),s}var wE="Usage: comet-hook-router --platform <platform-id> [--project-root <project-root>]";function yE(t){let e,r;for(let n=0;n<t.length;n++){let i=t[n];if(i==="--platform"){e=t[++n];continue}if(i==="--project-root"){r=t[++n];continue}throw new Error(`Unknown argument: ${i}`)}if(!e||e.startsWith("--"))throw new Error("--platform is required");if(!ys.has(e))throw new Error(`unsupported Hook platform: ${e}`);if(r?.startsWith("--"))throw new Error("--project-root requires a value");return{platformId:e,...r?{projectRoot:zp.resolve(r)}:{}}}async function bE(t,e){if(t.projectRoot)return e?Fp(t.projectRoot,e):t.projectRoot;if(!e?.cwd)return null;let r=e.cwd,n=await Fr(r);for(let o of[[".comet","config.yaml"],[".git"]])try{return await Vp.lstat(zp.join(n,...o)),n}catch(s){if(s.code!=="ENOENT")throw s}let i=await wf(r),a=await De(i);try{return await Vp.lstat(a.changesDir),i}catch(o){if(o.code!=="ENOENT")throw o}return null}async function NE(t){let e;try{e=yE(t)}catch(i){return process.stderr.write(`${i instanceof Error?i.message:String(i)}
|
|
167
|
-
${
|
|
168
|
-
`),64}let r;try{let i=
|
|
165
|
+
${t.sessionId}`)}:{}},h=t.binding?{schema:"comet.native.workspace.v3",...d,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...d};return da(h),h}async function vp(t,e){let r=await RS(t,e);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(da(r),r)}async function wp(t){da(t.identity);let e=await AS({paths:t.paths,name:"workspace-advisory",revision:t.identity.capturedRevision}),r=[],n=[];return e.nativeRootRef!==t.identity.nativeRootRef&&r.push("native-root-ref"),t.identity.projectRootPathId&&t.identity.nativeRootPathId?(e.projectRootPathId!==t.identity.projectRootPathId&&r.push("project-root-path"),e.nativeRootPathId!==t.identity.nativeRootPathId&&r.push("native-root-path")):(e.projectRootId!==t.identity.projectRootId&&r.push("project-root-legacy-identity"),e.nativeRootId!==t.identity.nativeRootId&&r.push("native-root-legacy-identity")),rc==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):r.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:r}}async function yp(t){if(da(t.identity),t.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await wp(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ar(t.paths.projectRoot);return t.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==t.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${t.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:t.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function bp(t,e){let r=await vp(t,e);if(r===null)return null;let n=await yp({paths:t,identity:r});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return r}var Np=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],jS=new Set(Np),kp=new Set([...Np,"minimum_runtime_version","revision"]),OS=new Set([...kp,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),$S=new Set(["capability","operation","source","base_hash"]),LS=new Set(["shape","build","verify","archive"]),DS=new Set(["implicit","confirmed"]),BS=new Set(["pending","pass","fail"]),ur="comet-state.yaml",ac=/^[a-f0-9]{64}$/u,Sp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,MS=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,pa=class extends Error{constructor(r,n){super(`Native change ${r} uses ${n}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},At=class extends Error{constructor(r,n){super(r!==qe||n===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"};var vI=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
166
|
+
`);function yn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Ep(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function ha(t){if(!Sp.test(t))throw new Error(`Invalid Native change name: ${t}`)}function qS(t){if(!Sp.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function Pp(t,e){if(t.length===0||Rt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function WS(t,e){let r=yn(t,`spec_changes[${e}]`);if(Ep(r,$S,`spec_changes[${e}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(qS(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let n=r.source,i=r.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof n=="string"&&Pp(n,`Spec source for ${r.capability}`),r.operation==="create"){if(!n)throw new Error(`Create spec ${r.capability} requires source`);if(i!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!n)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof i!="string"||!ac.test(i))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof i!="string"||!ac.test(i))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof n=="string"?{source:n}:{},base_hash:i}}function FS(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function sc(t,e){if(Ep(t,e,ur),typeof t.name!="string")throw new Error("Native change name is required");if(ha(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!LS.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!DS.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let r=t.spec_changes.map(WS),n=r.map(i=>i.capability).filter((i,a,o)=>o.indexOf(i)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof t.verification_result!="string"||!BS.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&Pp(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!FS(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:r,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Us(t){let e=yn(t,ur);if(e.schema!==Fe)throw new Error(`Expected ${Fe}`);return{schema:Fe,...sc(e,jS)}}function wn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function ic(t,e,r){if(t===null)return null;let n=typeof t=="string"?MS.exec(t):null;if(!n||n[1]!==r)throw new Error(`${e} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return t}function HS(t){if(t==null)return null;if(typeof t!="string"||!ac.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function VS(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Ks(t){let e=yn(t,ur);if(e.schema!==We)throw new Error(`Expected ${We}`);if(wn(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${We} minimum_runtime_version must be 2`);return{schema:We,minimum_runtime_version:2,revision:wn(e.revision,"Native v2 revision"),...sc(e,kp)}}function zd(t){let e=yn(t,ur);if(e.schema!==qe){if(e.schema===Fe||e.schema===We){let o=e.schema===Fe?Us(e):Ks(e);throw new pa(o.name,o.schema)}throw new At(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let r=wn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new At(e.schema,r);if(r!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=wn(e.revision,"Native revision"),i=sc(e,OS),a=HS(e.approved_contract_hash);if(i.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:qe,minimum_runtime_version:3,revision:n,verification_protocol:VS(e.verification_protocol),...i,approved_contract_hash:a,implementation_scope:ic(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:ic(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:ic(e.partial_allowance,"Native partial_allowance","allowances")}}function zS(t){let e=yn(t,ur);if(e.schema===Fe){let i=Us(e);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:1,state:i,message:`Native change ${i.name} requires migration to ${qe}`}}if(e.schema===We){let i=Ks(e);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i,message:`Native change ${i.name} requires migration to ${qe}`}}if(e.schema!==qe){let i=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:i,state:null,message:new At(typeof e.schema=="string"?e.schema:"(missing)",i).message}}let r=wn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:r,state:null,message:new At(e.schema,r).message};let n=zd(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function GS(t,e){ha(e);let r=Rt.join(t.changesDir,e);if(!de(t.changesDir,r))throw new Error("Native change path escaped");return r}async function US(t,e){let r=wt(t,e),n=Rt.join(r,"schema-migration.json");await F(de(t.runtimeDir,n)?t.runtimeDir:t.nativeRoot,n);try{return await IS.lstat(n),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}}var KS=256*1024;async function JS(t,e=Rt.dirname(t)){let r=Rt.relative(e,t).split(Rt.sep).join("/"),n=await lt({root:e,ref:r,maxBytes:KS}),i=(0,oc.parseDocument)(n.text,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${i.errors[0].message}`);return i.toJS()}async function YS(t,e){let r=Rt.join(GS(t,e),ur);await F(t.nativeRoot,r);let n=zS(await JS(r,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await US(t,e)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(n.status==="current"&&n.state&&await XS(t,n.state),n)}async function XS(t,e){if(await lp(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function ma(t,e){let r=await YS(t,e);if(r.status==="migration-required")throw new pa(e,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new At(r.schema,r.minimumRuntimeVersion);return await bp(t,e),r.state}$i();import{promises as Rp}from"node:fs";import ba from"node:path";var QS=Ve($e(),1);var xI=["$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("; ");function tE(t){return t.state_version+1}function rE(t){return t.map(e=>({...e,result:"pending",reason:null}))}function nE(t){return{goal_cycle:t.state.loop.goal_cycle,iteration:t.state.loop.iteration,attempt:t.state.loop.attempt,outcome:t.outcome,unresolved_ids:t.unresolvedIds??[],summary:gn(t.summary),completed_at:t.completedAt}}function Cp(t){let e=Ae(t.state);if(e.phase!=="verify"&&e.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(t.now??new Date).toISOString(),n=ra(e,nE({state:e,outcome:"recovery",summary:t.reason,completedAt:r}));return Ae({...n,phase:"build",status:"active",state_version:tE(e),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:rE(e.acceptance),loop:{...e.loop,stage:"repairing",iteration:e.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as iE}from"node:fs";import bn from"node:path";function ga(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function va(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function Ie(t,e,r=!1){if(typeof t!="string"||!r&&t.length===0)throw new Error(`${e} must be ${r?"a string":"a non-empty string"}`);return t}function xp(t,e){return t===null?null:Ie(t,e)}function ya(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function aE(t,e){if(t===null)return null;if(!Number.isSafeInteger(t))throw new Error(`${e} must be null or a safe integer`);return t}function oE(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function wa(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function cc(t,e){if(t===null)return null;let r=Ie(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO timestamp`);return r}function lc(t,e){let r=Ie(t,e);if(!bn.isAbsolute(r))throw new Error(`${e} must be absolute`);return bn.resolve(r)}function sE(t,e){let r=`Native local checks[${e}]`,n=ga(t,r);if(va(n,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(n.argv)||n.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let i=n.argv.map((l,u)=>Ie(l,`${r}.argv[${u}]`,!0)),a=wa(n.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=cc(n.startedAt,`${r}.startedAt`),s=cc(n.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=ya(n.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Ie(n.id,`${r}.id`),name:Ie(n.name,`${r}.name`),operationId:Ie(n.operationId,`${r}.operationId`),status:a,repeatable:oE(n.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:ya(n.executionCount,`${r}.executionCount`),argv:i,cwd:lc(n.cwd,`${r}.cwd`),exitCode:aE(n.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Ie(n.log,`${r}.log`)}}function _p(t){let e="Native local execution state",r=ga(t,e);if(va(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),e),r.schema!==hn)throw new Error(`Native local execution schema must be ${hn}`);let n=ga(r.workspace,"Native local workspace");va(n,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let i=null;if(r.execution!==null){let o=ga(r.execution,"Native local execution");va(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=cc(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");i={operationId:Ie(o.operationId,"Native local execution.operationId"),stage:wa(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:wa(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:xp(o.executionId,"Native local execution.executionId"),status:wa(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ya(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(sE);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(i&&a.some(o=>o.operationId!==i.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:hn,change:Ie(r.change,"Native local change"),basedOnStateVersion:ya(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:lc(n.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:lc(n.worktreeRoot,"Native local workspace.worktreeRoot"),branch:xp(n.branch,"Native local workspace.branch")},execution:i,checks:a}}function uc(t){return _p({schema:hn,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,workspace:{projectRoot:bn.resolve(t.projectRoot),worktreeRoot:bn.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null},execution:null,checks:[]})}async function fc(t,e,r={}){let n=_p(e);await iE.mkdir(bn.dirname(t),{recursive:!0}),await dn(t,n,r)}var cE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lE="comet-state.yaml",uE="state.json";function Ap(t){let e=t.expected;if(e){if(t.state.state_version!==e.stateVersion)throw new Error(`Native continuation is stale for state version ${e.stateVersion}; current state version is ${t.state.state_version}`);if(e.action!==t.action)throw new Error(`Native continuation expected ${e.action} cannot be used for ${t.action}`)}}function Na(t,e){if(!cE.test(e))throw new Error(`Invalid Native change name: ${e}`);let r=ba.join(t.changesDir,e);if(!de(t.changesDir,r))throw new Error("Native change path escaped");return r}function dc(t,e){return ba.join(Na(t,e),lE)}function Tp(t,e){return ba.join(Si(t,e),uE)}async function ka(t,e){try{let r=await Rp.readFile(dc(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Ip(t){return ar(t).currentBranch}async function fr(t,e){return mn(dc(t,e))}async function jp(t){let e=await Fd({file:dc(t.paths,t.previous.name),expectedStateVersion:t.previous.state_version,next:t.next,containedRoot:t.paths.nativeRoot});if(e.verification===null&&e.verification_report===null){let r=ba.join(Na(t.paths,e.name),"verification.md");await F(t.paths.nativeRoot,r),await Rp.rm(r,{force:!0})}return e}async function Op(t){return xt(t.paths,`return portable change ${t.name} to Build`,async()=>{let e=await fr(t.paths,t.name);if(Ap({state:e,expected:t.expectedContinuation,action:"revise-implementation"}),e.phase==="build")return e;let r=Cp({state:e,reason:t.reason}),n=await jp({paths:t.paths,previous:e,next:r});return await fc(Tp(t.paths,e.name),uc({portableState:n,projectRoot:t.paths.projectRoot,branch:Ip(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),n})}async function $p(t){return xt(t.paths,`return portable change ${t.name} to Shape`,async()=>{let e=await fr(t.paths,t.name);if(Ap({state:e,expected:t.expectedContinuation,action:"revise-requirements"}),t.allowedPhases&&!t.allowedPhases.includes(e.phase))throw new Error("--revise-requirements is only valid from Verify");return e.phase==="shape"?e:fE({paths:t.paths,state:e,reason:t.reason})})}async function fE(t){let{state:e}=t;if(e.archived)throw new Error(`Native change ${e.name} is already archived`);let n={...ra(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:gn(t.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:e.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete n.children_contract_hash;let i=await jp({paths:t.paths,previous:e,next:n});return await fc(Tp(t.paths,e.name),uc({portableState:i,projectRoot:t.paths.projectRoot,branch:Ip(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),i}var aO=16*1024;async function dE(t){let e=await rr(t.projectRoot);return e.status==="missing"||e.selection.workflow!=="native"?null:(ha(e.selection.change),e.selection)}async function Lp(t){let e=await dE(t);return e?(await ka(t,e.change)?await fr(t,e.change):await ma(t,e.change),e.change):null}function Dp(t){let e=`Native change ${t.name} is in ${t.phase}; implementation writes are only allowed in Build.`;return t.phase==="shape"?`${e} Reread the latest continuation, complete requirement clarification, and execute the Shape confirmation command after user confirmation.`:t.phase==="verify"?`${e} Select and execute the matching commandAlternative from the latest continuation, preserving --expected-state-version and --expected-action.`:t.phase==="archive"?`${e} Continue finalizing the accepted result; do not run Verify-only revision commands from Archive.`:`${e} Create or select a separate Native change if this write belongs to different work.`}async function hE(t){let{projectRoot:e,paths:r,state:n,request:i}=t,a=Na(r,n.name),o=[],s=[],c=!1,l=!1,u=!1;for(let f of i.targets){let d=be.resolve(e,f);if(!Tt(e,d)){u=!0;continue}let h=be.relative(e,d).replaceAll("\\","/");if(h===".comet/config.yaml"){l=!0;continue}if(!Tt(r.nativeRoot,d)){if(await tr(e,d,[be.join(e,".comet"),r.nativeRoot])){c=!0;continue}s.push(h);continue}if(!Tt(a,d))return{allowed:!1,reason:"Portable Native control state is Runtime-owned",workflow:"native",phase:n.phase,change:n.name};let v=be.relative(a,d).replaceAll("\\","/");if(v==="brief.md"||v==="children.yaml"||v.startsWith("specs/")){o.push(v);continue}return{allowed:!1,reason:`${v||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:n.phase,change:n.name}}return o.length>0&&s.length>0?{allowed:!1,reason:"Formal Native requirements and implementation files must be edited in separate actions",workflow:"native",phase:n.phase,change:n.name}:o.length>0?n.phase!=="shape"?{allowed:!0,reason:`Native requirements changed; returned to Shape goal cycle ${(await $p({paths:r,name:n.name,reason:`Formal requirement write requested for ${o.join(", ")}`})).loop.goal_cycle}`,workflow:"native",phase:"shape",change:n.name}:{allowed:!0,reason:"Native control artifact write",workflow:"native",phase:n.phase,change:n.name}:s.length>0?n.children_contract_hash?{allowed:!1,reason:"Native parent Build advances child changes instead of editing implementation",workflow:"native",phase:n.phase,change:n.name}:n.phase==="build"?{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:n.phase,change:n.name}:n.phase==="verify"||n.phase==="archive"?{allowed:!0,reason:`Native candidate was invalidated and returned to Build iteration ${(await Op({paths:r,name:n.name,reason:`Observed implementation write before ${s.join(", ")}`})).loop.iteration}`,workflow:"native",phase:"build",change:n.name}:{allowed:!1,reason:Dp(n),workflow:"native",phase:n.phase,change:n.name}:c?{allowed:!0,reason:"Native configured Hook allow path",workflow:"native",phase:n.phase,change:n.name}:{allowed:!0,reason:l?"Native control artifact write":u?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:n.phase,change:n.name}}function Tt(t,e){let r=be.relative(t,e);return r===""||!r.startsWith("..")&&!be.isAbsolute(r)}function mE(t,e,r){return r.targets.length>0&&r.targets.every(n=>{let i=be.resolve(t,n);return Tt(t,i)?be.relative(t,i).replaceAll("\\","/")===".comet/config.yaml"||Tt(e,i):!0})}async function gE(t){let e=await Et(t);if(!e||!(e.workflows??[e.default_workflow]).includes("native"))return null;let r=await Vr(t,e.native.artifact_root),n;try{n=await pE.readdir(r.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:r,changes:[]};throw a}let i=[];for(let a of n.sort((o,s)=>o.name.localeCompare(s.name)))if(!(!a.isDirectory()||a.isSymbolicLink()))if(await ka(r,a.name)){let o=await fr(r,a.name);o.archived||i.push({kind:"portable",state:o})}else{let o=await ma(r,a.name);o.archived||i.push({kind:"legacy",state:o})}return{paths:r,changes:i}}var Bp=X("nativeActiveContext",t=>gE(t));async function Mp(t){return((await Bp(t))?.changes??[]).map(r=>({workflow:"native",name:r.state.name,phase:r.state.phase}))}async function qp(t,e,r){let n=await Bp(t);if(!n)return{allowed:!0,reason:"Native workflow is not enabled"};if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(n.changes.length===0)return{allowed:!0,reason:mE(t,n.paths.nativeRoot,e)?"Native control artifact write":"No Native changes exist"};let i;if(r){if(i=n.changes.find(l=>l.state.name===r),!i)return{allowed:!1,reason:`Selected Native change ${r} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:r}}else if(n.changes.length===1)i=n.changes[0];else{let l=await Lp(n.paths);if(i=n.changes.find(u=>u.state.name===l),!i)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let a=i.state;if(i.kind==="legacy"&&a.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:a.phase,change:a.name};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:a.phase,change:a.name};if(i.kind==="portable")return hE({projectRoot:t,paths:n.paths,state:i.state,request:e});let o=!1,s=!1,c=!1;for(let l of e.targets){let u=be.resolve(t,l);if(!Tt(t,u)){s=!0;continue}if(be.relative(t,u).replaceAll("\\","/")===".comet/config.yaml"){o=!0;continue}if(Tt(n.paths.nativeRoot,u)){o=!0;continue}if(await tr(t,u,[be.join(t,".comet"),n.paths.nativeRoot])){c=!0;continue}return{allowed:!1,reason:Dp(a),workflow:"native",phase:a.phase,change:a.name}}return{allowed:!0,reason:o?"Native control artifact write":s?"Write target is outside the guarded project":c?"Native configured Hook allow path":"No guarded write target was provided",workflow:"native",phase:a.phase,change:a.name}}De();De();at();var Wp=X("readWorkflowProjectConfig",t=>Yr(t)),NO=X("discoverNativeProject",t=>Hr(t));var vE=X("readCometCurrentSelection",t=>rr(t)),Vp={listNative:Mp,listClassic:vd,inspectNative:qp,inspectClassic:kd};function wE(t){return t?t.workflows??[t.default_workflow]:["classic"]}async function Fp(t,e,r,n,i={}){let a=async()=>{if(!e.includes("classic"))return[];if(n?.workflow==="classic")return n.candidates;try{return await r.listClassic(t)}catch(c){if(i.tolerateUnavailableClassic&&c instanceof ct)return[];throw c}},[o,s]=await Promise.all([e.includes("native")?n?.workflow==="native"?n.candidates:r.listNative(t):[],a()]);return[...o,...s]}function Hp(t,e){return t.length===0?{status:"none",staleSelection:e}:t.length===1?{status:"inferred",owner:t[0],staleSelection:e}:{status:"ambiguous",candidates:t,staleSelection:e}}async function yE(t,e=Vp){let r=await Wp(t),n=wE(r),i;try{i=await vE(t)}catch(a){return{status:"stale",code:"selection-unreadable",reason:a instanceof Error?a.message:String(a)}}if(i.status==="selected"){let a=i.selection;if(!n.includes(a.workflow))return{status:"stale",code:"workflow-disabled",reason:`selected workflow '${a.workflow}' is not enabled for this project`};let o;try{o=a.workflow==="native"?await e.listNative(t):await e.listClassic(t)}catch(c){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${c instanceof Error?c.message:String(c)}`}}let s=o.find(c=>c.name===a.change);if(!s){let c={code:"target-missing",reason:`selected ${a.workflow} change '${a.change}' is missing or archived`};try{let l=await Fp(t,n,e,{workflow:a.workflow,candidates:o});return Hp(l,c)}catch(l){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${l instanceof Error?l.message:String(l)}`}}}if(a.workflow==="classic"){let c=await Gi(t);if(c.status!=="selected")return{status:"stale",code:"classic-selection-invalid",reason:c.status==="stale"?c.reason:`selected Classic change '${a.change}' is no longer active`}}return{status:"owned",owner:s}}try{let a=await Fp(t,n,e,void 0,{tolerateUnavailableClassic:!0});return Hp(a)}catch(a){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${a instanceof Error?a.message:String(a)}`}}}async function zp(t,e,r=Vp){if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target is outside Comet attribution"};let n;try{let i=await(r.scopeTargets??Oi)(t,e.targets);if(i.projectTargets.length===0)return{allowed:!0,reason:"Write targets are outside the guarded project"};n={...e,targets:i.projectTargets}}catch(i){return{allowed:!1,reason:["Comet Hook Router scope could not be determined safely.",`Reason: ${i instanceof Error?i.message:String(i)}`,"Next: verify that the project root is accessible, then retry the write."].join(" ")}}try{let i=await yE(t,r);if(i.status==="none")return{allowed:!0,reason:"No active Comet change"};if(i.status==="stale")return{allowed:!1,reason:`${i.reason}. Resume /comet-native or /comet-classic and select the current change before retrying`};if(i.status==="ambiguous")return{allowed:!1,reason:`Multiple active Comet changes require one current selection: ${i.candidates.map(o=>`${o.workflow}:${o.name}`).join(", ")}`};let a=i.owner;return a.workflow==="native"?r.inspectNative(t,n,a.name):r.inspectClassic(t,a.name,n)}catch(i){return{allowed:!1,reason:`Comet Hook Router failed closed: ${i instanceof Error?i.message:String(i)}`}}}import{promises as bE}from"fs";import le from"path";function NE(t,e){let r=le.resolve(t),n=le.resolve(e);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function kE(t,e){let r=le.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${le.sep}`)&&!le.isAbsolute(r)}function Gp(t,e){return[...e].sort((r,n)=>n.length-r.length).find(r=>kE(r,t))??null}async function SE(t){for(let e of[".git",le.join(".comet","config.yaml")])try{await bE.lstat(le.join(t,e))}catch(r){throw r.code!=="ENOENT"?r:new Error(`linked worktree ${t} is not initialized for Comet: missing ${e.replaceAll("\\","/")}`,{cause:r})}}async function Up(t,e){let r=le.resolve(t),n=zi(r);if(n.length<2||e.targets.length===0)return r;let a=(e.cwd?Gp(le.resolve(e.cwd),n):null)??r,o=new Map;for(let c of e.targets){let l=le.isAbsolute(c)?le.resolve(c):le.resolve(a,c),u=Gp(l,n);if(!u)continue;let f=process.platform==="win32"?u.toLowerCase():u;o.set(f,u)}if(o.size===0)return r;if(o.size>1)throw new Error("one Hook request cannot write across multiple Git worktrees");let[s]=o.values();return NE(s,r)||await SE(s),s}var CE="Usage: comet-hook-router --platform <platform-id> [--project-root <project-root>]";function xE(t){let e,r;for(let n=0;n<t.length;n++){let i=t[n];if(i==="--platform"){e=t[++n];continue}if(i==="--project-root"){r=t[++n];continue}throw new Error(`Unknown argument: ${i}`)}if(!e||e.startsWith("--"))throw new Error("--platform is required");if(!bs.has(e))throw new Error(`unsupported Hook platform: ${e}`);if(r?.startsWith("--"))throw new Error("--project-root requires a value");return{platformId:e,...r?{projectRoot:Yp.resolve(r)}:{}}}async function _E(t,e){if(t.projectRoot)return e?Up(t.projectRoot,e):t.projectRoot;if(!e?.cwd)return null;let r=e.cwd,n=await Hr(r);for(let o of[[".comet","config.yaml"],[".git"]])try{return await Jp.lstat(Yp.join(n,...o)),n}catch(s){if(s.code!=="ENOENT")throw s}let i=await Nf(r),a=await Le(i);try{return await Jp.lstat(a.changesDir),i}catch(o){if(o.code!=="ENOENT")throw o}return null}async function RE(t){let e;try{e=xE(t)}catch(i){return process.stderr.write(`${i instanceof Error?i.message:String(i)}
|
|
167
|
+
${CE}
|
|
168
|
+
`),64}let r;try{let i=ks(),a=await _E(e,i);r=a?await _f(()=>zp(a,i)):{allowed:!0,reason:"No Comet project discovered"}}catch(i){r={allowed:!1,reason:`Comet Hook Router failed closed during project discovery: ${i instanceof Error?i.message:String(i)}`}}let n=xf(e.platformId,r);return n.stdout&&process.stdout.write(n.stdout),n.stderr&&process.stderr.write(n.stderr),n.exitCode}async function AE(t=process.argv.slice(2)){return RE(t)}function TE(t,e=import.meta.url){if(!t)return!1;try{return Kp(t)===Kp(EE(e))}catch{return e===PE(t).href}}var IE=process.argv[1];TE(IE)&&AE().then(t=>{process.exitCode=t});export{TE as isDirectEntry,AE as main,_E as projectRootFrom,RE as runCometHookRouter};
|