@rpamis/comet 0.4.0-beta.17 → 0.4.0-beta.18
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 +49 -24
- package/assets/manifest.json +2 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +128 -128
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +78 -78
- package/assets/skills/comet/scripts/comet-guard.mjs +144 -144
- package/assets/skills/comet/scripts/comet-handoff.mjs +109 -109
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +130 -130
- package/assets/skills/comet/scripts/comet-hook-router.mjs +115 -115
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +85 -85
- package/assets/skills/comet/scripts/comet-runtime.mjs +188 -187
- package/assets/skills/comet/scripts/comet-state.mjs +117 -117
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +71 -71
- package/assets/skills/comet-build/SKILL.md +15 -56
- package/assets/skills/comet-classic/SKILL.md +14 -8
- package/assets/skills/comet-classic/reference/comet-yaml-fields.md +1 -1
- package/assets/skills/comet-classic/reference/scripts.md +3 -1
- package/assets/skills/comet-classic/reference/workspace.md +23 -0
- package/assets/skills/comet-native/SKILL.md +13 -10
- package/assets/skills/comet-native/reference/artifacts.md +3 -2
- package/assets/skills/comet-native/reference/commands.md +1 -1
- package/assets/skills/comet-native/reference/recovery.md +1 -1
- package/assets/skills/comet-native/reference/workspace.md +4 -4
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +97 -97
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +146 -146
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +100 -100
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +85 -85
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +115 -115
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +118 -118
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +107 -107
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +154 -154
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +133 -133
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +109 -109
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +87 -87
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +109 -109
- package/assets/skills/comet-open/SKILL.md +24 -5
- package/assets/skills-zh/comet-build/SKILL.md +15 -56
- package/assets/skills-zh/comet-classic/SKILL.md +14 -8
- package/assets/skills-zh/comet-classic/reference/comet-yaml-fields.md +1 -1
- package/assets/skills-zh/comet-classic/reference/scripts.md +3 -1
- package/assets/skills-zh/comet-classic/reference/workspace.md +23 -0
- package/assets/skills-zh/comet-native/SKILL.md +13 -10
- package/assets/skills-zh/comet-native/reference/artifacts.md +3 -2
- package/assets/skills-zh/comet-native/reference/commands.md +1 -1
- package/assets/skills-zh/comet-native/reference/recovery.md +1 -1
- package/assets/skills-zh/comet-native/reference/workspace.md +4 -4
- package/assets/skills-zh/comet-open/SKILL.md +24 -5
- package/dist/app/cli/index.js +20 -1
- package/dist/app/cli/index.js.map +1 -1
- package/dist/app/commands/classic.d.ts.map +1 -1
- package/dist/app/commands/classic.js +2 -0
- package/dist/app/commands/classic.js.map +1 -1
- package/dist/app/commands/eval.d.ts +9 -2
- package/dist/app/commands/eval.d.ts.map +1 -1
- package/dist/app/commands/eval.js +293 -48
- package/dist/app/commands/eval.js.map +1 -1
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +2 -1
- 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 +4 -1
- package/dist/app/commands/update.js.map +1 -1
- package/dist/domains/comet-classic/classic-cli.d.ts +1 -1
- package/dist/domains/comet-classic/classic-cli.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-cli.js +3 -0
- package/dist/domains/comet-classic/classic-cli.js.map +1 -1
- package/dist/domains/comet-classic/classic-current-change.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-current-change.js +29 -3
- package/dist/domains/comet-classic/classic-current-change.js.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-hook-guard.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard.js +14 -1
- package/dist/domains/comet-classic/classic-hook-guard.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 +31 -8
- package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-workspace-command.d.ts +3 -0
- package/dist/domains/comet-classic/classic-workspace-command.d.ts.map +1 -0
- package/dist/domains/comet-classic/classic-workspace-command.js +45 -0
- package/dist/domains/comet-classic/classic-workspace-command.js.map +1 -0
- package/dist/domains/comet-classic/classic-workspace.d.ts +38 -0
- package/dist/domains/comet-classic/classic-workspace.d.ts.map +1 -0
- package/dist/domains/comet-classic/classic-workspace.js +315 -0
- package/dist/domains/comet-classic/classic-workspace.js.map +1 -0
- package/dist/domains/comet-entry/hook-adapter.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-adapter.js +1 -0
- package/dist/domains/comet-entry/hook-adapter.js.map +1 -1
- package/dist/domains/comet-entry/hook-router-entry.d.ts +2 -0
- package/dist/domains/comet-entry/hook-router-entry.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-router-entry.js +21 -1
- package/dist/domains/comet-entry/hook-router-entry.js.map +1 -1
- package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
- package/dist/domains/comet-entry/init-workflow.js +13 -5
- package/dist/domains/comet-entry/init-workflow.js.map +1 -1
- package/dist/domains/comet-native/index.d.ts +1 -0
- package/dist/domains/comet-native/index.d.ts.map +1 -1
- package/dist/domains/comet-native/index.js +1 -0
- package/dist/domains/comet-native/index.js.map +1 -1
- package/dist/domains/comet-native/native-children.d.ts +49 -0
- package/dist/domains/comet-native/native-children.d.ts.map +1 -0
- package/dist/domains/comet-native/native-children.js +388 -0
- package/dist/domains/comet-native/native-children.js.map +1 -0
- package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +3 -3
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-doctor-command.js +10 -5
- package/dist/domains/comet-native/native-doctor-command.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 +41 -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 +85 -5
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts +3 -2
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +63 -1
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.d.ts +5 -0
- package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.js +110 -4
- package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-state.js +13 -0
- package/dist/domains/comet-native/native-portable-state.js.map +1 -1
- package/dist/domains/comet-native/native-portable-status.d.ts +3 -0
- package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-status.js +9 -1
- package/dist/domains/comet-native/native-portable-status.js.map +1 -1
- package/dist/domains/comet-native/native-portable-types.d.ts +1 -0
- package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-types.js.map +1 -1
- package/dist/domains/comet-native/native-show-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-show-command.js +2 -1
- package/dist/domains/comet-native/native-show-command.js.map +1 -1
- package/dist/domains/comet-native/native-workspace-preparation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-workspace-preparation.js +192 -133
- package/dist/domains/comet-native/native-workspace-preparation.js.map +1 -1
- package/dist/domains/dashboard/collector.d.ts +1 -1
- package/dist/domains/dashboard/collector.d.ts.map +1 -1
- package/dist/domains/dashboard/collector.js +102 -87
- package/dist/domains/dashboard/collector.js.map +1 -1
- package/dist/domains/dashboard/native-adapter.d.ts +20 -0
- package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
- package/dist/domains/dashboard/native-adapter.js +11 -0
- package/dist/domains/dashboard/native-adapter.js.map +1 -1
- package/dist/domains/dashboard/native-collector.d.ts +1 -0
- package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
- package/dist/domains/dashboard/native-collector.js +304 -55
- package/dist/domains/dashboard/native-collector.js.map +1 -1
- package/dist/domains/dashboard/native-legacy-adapter.d.ts +12 -5
- package/dist/domains/dashboard/native-legacy-adapter.d.ts.map +1 -1
- package/dist/domains/dashboard/native-legacy-adapter.js +12 -0
- package/dist/domains/dashboard/native-legacy-adapter.js.map +1 -1
- package/dist/domains/dashboard/server.d.ts.map +1 -1
- package/dist/domains/dashboard/server.js +5 -3
- package/dist/domains/dashboard/server.js.map +1 -1
- package/dist/domains/dashboard/types.d.ts +5 -0
- package/dist/domains/dashboard/types.d.ts.map +1 -1
- package/dist/domains/dashboard/web/assets/abnfDiagram-N423BO3Z-B5cFR6hS.js +1 -0
- package/dist/domains/dashboard/web/assets/arc-CVQDtMsu.js +1 -0
- package/dist/domains/dashboard/web/assets/architectureDiagram-T3A2C74G-C0v0kULK.js +36 -0
- package/dist/domains/dashboard/web/assets/blockDiagram-VBNYF7ZC-DpHLuxu4.js +132 -0
- package/dist/domains/dashboard/web/assets/{c4Diagram-AAUBKEIU-BL17BIb8.js → c4Diagram-5PPSVZJV-BHnFxUs1.js} +1 -1
- package/dist/domains/dashboard/web/assets/channel-eM0x3m1G.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-ND2GUHAM-XWLMOyd4.js → chunk-2GRJ4B5K-CGC9gh5n.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-QZHKN3VN-4drjXzHQ.js → chunk-2Q5K7J3B-l4puLU_O.js} +1 -1
- package/dist/domains/dashboard/web/assets/chunk-5RXB4S5H-ls9jQHZc.js +231 -0
- package/dist/domains/dashboard/web/assets/{chunk-FMBD7UC4-CQXqBSqQ.js → chunk-5VM5RSS4-BVavmTEq.js} +1 -1
- package/dist/domains/dashboard/web/assets/chunk-6Q2QTUOP-Dungt2g9.js +88 -0
- package/dist/domains/dashboard/web/assets/{chunk-727SXJPM-pMreYMW7.js → chunk-GF5L2VYU-BidXO_ZP.js} +5 -5
- package/dist/domains/dashboard/web/assets/{chunk-4BX2VUAB-vQyyh3eG.js → chunk-JWPE2WC7-57L5Up5X.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-2J33WTMH-B_DDS2IK.js → chunk-KBJHAD2P-C5u5vbwr.js} +1 -1
- package/dist/domains/dashboard/web/assets/chunk-RYQCIY6F-CvLz21I2.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-55IACEB6-Cug8J1Qa.js → chunk-XXDRQBXY-D5nJpckG.js} +1 -1
- package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-CEFhao2K.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-CEFhao2K.js +1 -0
- package/dist/domains/dashboard/web/assets/{cose-bilkent-S5V4N54A-IQKP-hgj.js → cose-bilkent-JH36ORCC-Dp0JAGyE.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-CvvRO4J2.js → cynefin-VYW2F7L2-EjC54l1g.js} +2 -2
- package/dist/domains/dashboard/web/assets/cynefinDiagram-MW4NZA55-CpYrW3w3.js +62 -0
- package/dist/domains/dashboard/web/assets/dagre-VZM6K2ZE-h5K39rCk.js +4 -0
- package/dist/domains/dashboard/web/assets/{demo-CeIDHUFJ.js → demo-BfLsKrIL.js} +26 -5
- package/dist/domains/dashboard/web/assets/diagram-7IWD3JNH-CKQj9O4H.js +30 -0
- package/dist/domains/dashboard/web/assets/{diagram-KO2AKTUF-CN_LYqvT.js → diagram-B4RE2ZJO-DXRIYcnW.js} +3 -3
- package/dist/domains/dashboard/web/assets/diagram-LBJQPF4R-wWutQYmv.js +24 -0
- package/dist/domains/dashboard/web/assets/diagram-Q27KOJAE-EgXLJQYi.js +24 -0
- package/dist/domains/dashboard/web/assets/diagram-UB23O5K3-CsQRXDQZ.js +41 -0
- package/dist/domains/dashboard/web/assets/ebnfDiagram-BXEA7PRR-gm328Eho.js +1 -0
- package/dist/domains/dashboard/web/assets/erDiagram-JOGREHBK-BbbMVUx_.js +85 -0
- package/dist/domains/dashboard/web/assets/flowDiagram-UKHOOZJN-1Y7scCns.js +156 -0
- package/dist/domains/dashboard/web/assets/ganttDiagram-PKOTCBZU-BAoBqczv.js +292 -0
- package/dist/domains/dashboard/web/assets/{gitGraphDiagram-PVQCEYII-CaWEk3PM.js → gitGraphDiagram-DS77QQ5N-CMUAyEzl.js} +3 -3
- package/dist/domains/dashboard/web/assets/{graph--OzhPTMs.js → graph-DOmOIIwC.js} +1 -1
- package/dist/domains/dashboard/web/assets/{index-BNyOfAhu.js → index-CCApJ0Yr.js} +1 -1
- package/dist/domains/dashboard/web/assets/index-DWdm_XBi.js +257 -0
- package/dist/domains/dashboard/web/assets/{index-BFwKBVTJ.css → index-DhhbseFJ.css} +1 -1
- package/dist/domains/dashboard/web/assets/{infoDiagram-5YYISTIA-BK07mNG0.js → infoDiagram-6WML65LV-BaCdtYYC.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ishikawaDiagram-YF4QCWOH-mWnmaWfZ.js → ishikawaDiagram-WSZJBQD7-DQQlNnjU.js} +4 -4
- package/dist/domains/dashboard/web/assets/{journeyDiagram-JHISSGLW-BPy-P7xx.js → journeyDiagram-NVQOT4AX-DW9wUMqn.js} +1 -1
- package/dist/domains/dashboard/web/assets/{kanban-definition-UN3LZRKU-3Jq9c_lo.js → kanban-definition-27J2QSJJ-C_ITaZ0q.js} +7 -7
- package/dist/domains/dashboard/web/assets/layout-D-LzfAck.js +1 -0
- package/dist/domains/dashboard/web/assets/{linear-kQyEW-4G.js → linear-DXOo6ZRT.js} +1 -1
- package/dist/domains/dashboard/web/assets/map-DxJ2ADlA.js +1 -0
- package/dist/domains/dashboard/web/assets/mermaid.core-ol-0NI97.js +306 -0
- package/dist/domains/dashboard/web/assets/{mindmap-definition-RKZ34NQL-CyyurUpv.js → mindmap-definition-FAOFIHXS-CHF_HOLV.js} +1 -1
- package/dist/domains/dashboard/web/assets/pegDiagram-VL7TDLO6-wQEvkNF8.js +1 -0
- package/dist/domains/dashboard/web/assets/pieDiagram-7S7Q4E2Y-C3H3kiIP.js +39 -0
- package/dist/domains/dashboard/web/assets/purify.es-Cz4mVeUR.js +3 -0
- package/dist/domains/dashboard/web/assets/{quadrantDiagram-W4KKPZXB-CpayUMjH.js → quadrantDiagram-CIZ2JOQS-S0FdVzJb.js} +4 -4
- package/dist/domains/dashboard/web/assets/railroadDiagram-AXF67PYL-DCDXDaVg.js +1 -0
- package/dist/domains/dashboard/web/assets/{requirementDiagram-4Y6WPE33-Bi8YpfnA.js → requirementDiagram-LRYGKXZP-BW8J4gO_.js} +1 -1
- package/dist/domains/dashboard/web/assets/sankeyDiagram-W5VNT64P-DQQBmLoy.js +40 -0
- package/dist/domains/dashboard/web/assets/sequenceDiagram-SI44F4Z6-2tDcli0Y.js +162 -0
- package/dist/domains/dashboard/web/assets/sizeCapture-X5ZJPWSS-4sEZLBKb.js +1 -0
- package/dist/domains/dashboard/web/assets/stateDiagram-OKZ733FA-OgPb8pyR.js +1 -0
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-CiDNPr4P.js +1 -0
- package/dist/domains/dashboard/web/assets/swimlanes-SLNWSIFB-DR7lwtxd.js +2 -0
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-DggHFP9q.js +8 -0
- package/dist/domains/dashboard/web/assets/{timeline-definition-PNZ67QCA-aHrrtV-b.js → timeline-definition-Z64GVDOM-DNIJVlQV.js} +4 -4
- package/dist/domains/dashboard/web/assets/vennDiagram-T6HMQDX7-CClhw4QZ.js +34 -0
- package/dist/domains/dashboard/web/assets/{wardleyDiagram-YWT4CUSO-RVQbcySh.js → wardleyDiagram-T6FBY63Y-DzR3aFPS.js} +3 -3
- package/dist/domains/dashboard/web/assets/xychartDiagram-ELKLHX3M-DZhq0ZRj.js +7 -0
- package/dist/domains/dashboard/web/index.html +2 -2
- package/dist/domains/dashboard/workspace.d.ts +24 -0
- package/dist/domains/dashboard/workspace.d.ts.map +1 -0
- package/dist/domains/dashboard/workspace.js +87 -0
- package/dist/domains/dashboard/workspace.js.map +1 -0
- package/dist/domains/eval/index.d.ts +3 -0
- package/dist/domains/eval/index.d.ts.map +1 -1
- package/dist/domains/eval/index.js +3 -0
- package/dist/domains/eval/index.js.map +1 -1
- package/dist/domains/eval/standalone-context.d.ts +19 -0
- package/dist/domains/eval/standalone-context.d.ts.map +1 -0
- package/dist/domains/eval/standalone-context.js +107 -0
- package/dist/domains/eval/standalone-context.js.map +1 -0
- package/dist/domains/eval/standalone-static-collect.d.ts +22 -0
- package/dist/domains/eval/standalone-static-collect.d.ts.map +1 -0
- package/dist/domains/eval/standalone-static-collect.js +779 -0
- package/dist/domains/eval/standalone-static-collect.js.map +1 -0
- package/dist/domains/eval/user-environment.d.ts +6 -0
- package/dist/domains/eval/user-environment.d.ts.map +1 -0
- package/dist/domains/eval/user-environment.js +73 -0
- package/dist/domains/eval/user-environment.js.map +1 -0
- 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 +110 -26
- package/dist/domains/integrations/openspec.js.map +1 -1
- package/dist/domains/integrations/superpowers.d.ts +5 -1
- package/dist/domains/integrations/superpowers.d.ts.map +1 -1
- package/dist/domains/integrations/superpowers.js +21 -2
- package/dist/domains/integrations/superpowers.js.map +1 -1
- package/dist/domains/skill/platform-install.d.ts +1 -1
- package/dist/domains/skill/platform-install.js +1 -1
- package/dist/domains/skill/project-instructions.d.ts.map +1 -1
- package/dist/domains/skill/project-instructions.js +5 -3
- package/dist/domains/skill/project-instructions.js.map +1 -1
- package/dist/domains/workflow-contract/hook-write-policy.d.ts +9 -0
- package/dist/domains/workflow-contract/hook-write-policy.d.ts.map +1 -0
- package/dist/domains/workflow-contract/hook-write-policy.js +52 -0
- package/dist/domains/workflow-contract/hook-write-policy.js.map +1 -0
- package/dist/domains/workflow-contract/index.d.ts +2 -0
- package/dist/domains/workflow-contract/index.d.ts.map +1 -1
- package/dist/domains/workflow-contract/index.js +1 -0
- package/dist/domains/workflow-contract/index.js.map +1 -1
- package/dist/domains/workflow-contract/project-config.d.ts +2 -2
- package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config.js +42 -2
- package/dist/domains/workflow-contract/project-config.js.map +1 -1
- package/dist/domains/workflow-contract/protected-project-path.d.ts +13 -0
- package/dist/domains/workflow-contract/protected-project-path.d.ts.map +1 -1
- package/dist/domains/workflow-contract/protected-project-path.js +83 -0
- package/dist/domains/workflow-contract/protected-project-path.js.map +1 -1
- package/dist/domains/workflow-contract/types.d.ts +4 -0
- package/dist/domains/workflow-contract/types.d.ts.map +1 -1
- package/dist/platform/install/platforms.d.ts.map +1 -1
- package/dist/platform/install/platforms.js +13 -2
- package/dist/platform/install/platforms.js.map +1 -1
- package/dist/platform/paths/git-worktree.d.ts +7 -1
- package/dist/platform/paths/git-worktree.d.ts.map +1 -1
- package/dist/platform/paths/git-worktree.js +28 -7
- package/dist/platform/paths/git-worktree.js.map +1 -1
- package/eval/.env.example +115 -0
- package/eval/README.md +237 -14
- package/eval/langfuse/.env.example +9 -0
- package/eval/langfuse/tests/conftest.py +146 -0
- package/eval/langfuse/tests/tasks/test_tasks.py +109 -0
- package/eval/langfuse/tests/test_adapter.py +272 -0
- package/eval/langsmith/.env.example +16 -0
- package/eval/langsmith/tests/conftest.py +10 -1
- package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +4 -2
- package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +2 -2
- package/eval/local/tests/conftest.py +701 -80
- package/eval/local/tests/scaffold/fixtures/custom-agent/adapter.yaml +19 -0
- package/eval/local/tests/scaffold/test_agents.py +76 -0
- package/eval/local/tests/scaffold/test_aligned_comparison.py +70 -0
- package/eval/local/tests/scaffold/test_auto_tasks.py +350 -0
- package/eval/local/tests/scaffold/test_conftest_helpers.py +267 -18
- package/eval/local/tests/scaffold/test_custom_agents.py +174 -0
- package/eval/local/tests/scaffold/test_eval_context.py +217 -0
- package/eval/local/tests/scaffold/test_execution.py +364 -0
- package/eval/local/tests/scaffold/test_inline_tasks.py +56 -0
- package/eval/local/tests/scaffold/test_langfuse_trajectory.py +263 -0
- package/eval/local/tests/scaffold/test_langsmith_conftest.py +63 -0
- package/eval/local/tests/scaffold/test_logging.py +162 -0
- package/eval/local/tests/scaffold/test_manifest_tasks.py +76 -0
- package/eval/local/tests/scaffold/test_manifests.py +396 -0
- package/eval/local/tests/scaffold/test_native_aligned_eval.py +17 -0
- package/eval/local/tests/scaffold/test_profiles.py +64 -6
- package/eval/local/tests/scaffold/test_task_resolution.py +212 -0
- package/eval/local/tests/scaffold/test_utils.py +480 -4
- package/eval/local/tests/tasks/test_tasks.py +216 -14
- package/eval/pyproject.toml +5 -0
- package/eval/scaffold/__init__.py +6 -0
- package/eval/scaffold/docker/agent-overlay.Dockerfile +41 -0
- package/eval/scaffold/python/__init__.py +128 -20
- package/eval/scaffold/python/agents.py +239 -0
- package/eval/scaffold/python/aligned_comparison.py +156 -27
- package/eval/scaffold/python/auto_tasks.py +700 -0
- package/eval/scaffold/python/custom_agents.py +172 -0
- package/eval/scaffold/python/eval_context.py +236 -0
- package/eval/scaffold/python/eval_schema.py +135 -0
- package/eval/scaffold/python/execution.py +544 -0
- package/eval/scaffold/python/generated_task_cache.py +230 -0
- package/eval/scaffold/python/generic_llm_judge.py +41 -14
- package/eval/scaffold/python/inline_tasks.py +118 -0
- package/eval/scaffold/python/judge_config.py +158 -37
- package/eval/scaffold/python/langfuse_adapter.py +1023 -0
- package/eval/scaffold/python/llm_judge.py +68 -11
- package/eval/scaffold/python/logging.py +157 -17
- package/eval/scaffold/python/manifest_tasks.py +69 -0
- package/eval/scaffold/python/manifests.py +443 -22
- package/eval/scaffold/python/paths.py +11 -1
- package/eval/scaffold/python/task_resolution.py +176 -0
- package/eval/scaffold/python/tasks.py +17 -4
- package/eval/scaffold/python/utils.py +167 -11
- package/eval/scaffold/python/validation/core.py +48 -2
- package/eval/scaffold/python/validation/generic_rubric.py +9 -0
- package/eval/scaffold/python/validation/native_workflow.py +6 -1
- package/eval/scaffold/python/validation/rubric.py +16 -1
- package/eval/scaffold/shell/agent-runtime-config.sh +88 -0
- package/eval/scaffold/shell/docker.sh +534 -33
- package/eval/scaffold/shell/run-agent-runtime.sh +49 -0
- package/eval/scaffold/shell/run-claude-loop.sh +153 -14
- package/eval/schemas/comet.eval/v1alpha1.schema.json +244 -0
- package/package.json +8 -3
- package/dist/domains/dashboard/web/assets/arc-CkuYweSh.js +0 -1
- package/dist/domains/dashboard/web/assets/architectureDiagram-3BPJPVTR--tTGrKam.js +0 -36
- package/dist/domains/dashboard/web/assets/blockDiagram-GPEHLZMM-DLKYOixs.js +0 -132
- package/dist/domains/dashboard/web/assets/channel-Cg__FSMr.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-AQP2D5EJ-BUkV_rb7.js +0 -231
- package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-CsC-pvu9.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-CsC-pvu9.js +0 -1
- package/dist/domains/dashboard/web/assets/dagre-BM42HDAG-DeOQo7bP.js +0 -4
- package/dist/domains/dashboard/web/assets/diagram-2AECGRRQ-IQd_jQwB.js +0 -43
- package/dist/domains/dashboard/web/assets/diagram-5GNKFQAL-Dllkdt0m.js +0 -10
- package/dist/domains/dashboard/web/assets/diagram-LMA3HP47-DK36WkNN.js +0 -24
- package/dist/domains/dashboard/web/assets/diagram-OG6HWLK6-iqUnMYEh.js +0 -24
- package/dist/domains/dashboard/web/assets/erDiagram-TEJ5UH35-Bc64lzy8.js +0 -85
- package/dist/domains/dashboard/web/assets/flowDiagram-I6XJVG4X-UfOqef9j.js +0 -162
- package/dist/domains/dashboard/web/assets/ganttDiagram-6RSMTGT7-D-u6Aauc.js +0 -292
- package/dist/domains/dashboard/web/assets/index-COZ_03uK.js +0 -257
- package/dist/domains/dashboard/web/assets/layout-SsrduOYp.js +0 -1
- package/dist/domains/dashboard/web/assets/mermaid.core-COBBjtVH.js +0 -301
- package/dist/domains/dashboard/web/assets/pieDiagram-4H26LBE5-CJro_XKk.js +0 -30
- package/dist/domains/dashboard/web/assets/purify.es-VaSPOPhr.js +0 -3
- package/dist/domains/dashboard/web/assets/sankeyDiagram-5OEKKPKP-Wx60WwHe.js +0 -40
- package/dist/domains/dashboard/web/assets/sequenceDiagram-3UESZ5HK-BiMsRFbc.js +0 -162
- package/dist/domains/dashboard/web/assets/stateDiagram-AJRCARHV-BrURMY0R.js +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-BpEE-yEg.js +0 -1
- package/dist/domains/dashboard/web/assets/vennDiagram-CIIHVFJN-DGB16bvR.js +0 -34
- package/dist/domains/dashboard/web/assets/xychartDiagram-2RQKCTM6-DMzzwDVX.js +0 -7
|
@@ -1,77 +1,77 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`)}};
|
|
6
|
-
`)?
|
|
4
|
+
var Qf=Object.create;var oc=Object.defineProperty;var Zf=Object.getOwnPropertyDescriptor;var eh=Object.getOwnPropertyNames;var th=Object.getPrototypeOf,ih=Object.prototype.hasOwnProperty;var fr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var y=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var rh=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of eh(t))!ih.call(e,n)&&n!==i&&oc(e,n,{get:()=>t[n],enumerable:!(r=Zf(t,n))||r.enumerable});return e};var ti=(e,t,i)=>(i=e!=null?Qf(th(e)):{},rh(t||!e||!e.__esModule?oc(i,"default",{value:e,enumerable:!0}):i,e));var P=y(M=>{"use strict";var fa=Symbol.for("yaml.alias"),dc=Symbol.for("yaml.document"),mr=Symbol.for("yaml.map"),fc=Symbol.for("yaml.pair"),ha=Symbol.for("yaml.scalar"),vr=Symbol.for("yaml.seq"),Ie=Symbol.for("yaml.node.type"),Nh=e=>!!e&&typeof e=="object"&&e[Ie]===fa,bh=e=>!!e&&typeof e=="object"&&e[Ie]===dc,kh=e=>!!e&&typeof e=="object"&&e[Ie]===mr,Sh=e=>!!e&&typeof e=="object"&&e[Ie]===fc,hc=e=>!!e&&typeof e=="object"&&e[Ie]===ha,Eh=e=>!!e&&typeof e=="object"&&e[Ie]===vr;function pc(e){if(e&&typeof e=="object")switch(e[Ie]){case mr:case vr:return!0}return!1}function Ph(e){if(e&&typeof e=="object")switch(e[Ie]){case fa:case mr:case ha:case vr:return!0}return!1}var xh=e=>(hc(e)||pc(e))&&!!e.anchor;M.ALIAS=fa;M.DOC=dc;M.MAP=mr;M.NODE_TYPE=Ie;M.PAIR=fc;M.SCALAR=ha;M.SEQ=vr;M.hasAnchor=xh;M.isAlias=Nh;M.isCollection=pc;M.isDocument=bh;M.isMap=kh;M.isNode=Ph;M.isPair=Sh;M.isScalar=hc;M.isSeq=Eh});var oi=y(pa=>{"use strict";var D=P(),X=Symbol("break visit"),mc=Symbol("skip children"),Se=Symbol("remove node");function gr(e,t){let i=vc(t);D.isDocument(e)?xt(null,e.contents,i,Object.freeze([e]))===Se&&(e.contents=null):xt(null,e,i,Object.freeze([]))}gr.BREAK=X;gr.SKIP=mc;gr.REMOVE=Se;function xt(e,t,i,r){let n=gc(e,t,i,r);if(D.isNode(n)||D.isPair(n))return wc(e,r,n),xt(e,n,i,r);if(typeof n!="symbol"){if(D.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=xt(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===X)return X;o===Se&&(t.items.splice(a,1),a-=1)}}}else if(D.isPair(t)){r=Object.freeze(r.concat(t));let a=xt("key",t.key,i,r);if(a===X)return X;a===Se&&(t.key=null);let o=xt("value",t.value,i,r);if(o===X)return X;o===Se&&(t.value=null)}}return n}async function wr(e,t){let i=vc(t);D.isDocument(e)?await Rt(null,e.contents,i,Object.freeze([e]))===Se&&(e.contents=null):await Rt(null,e,i,Object.freeze([]))}wr.BREAK=X;wr.SKIP=mc;wr.REMOVE=Se;async function Rt(e,t,i,r){let n=await gc(e,t,i,r);if(D.isNode(n)||D.isPair(n))return wc(e,r,n),Rt(e,n,i,r);if(typeof n!="symbol"){if(D.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await Rt(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===X)return X;o===Se&&(t.items.splice(a,1),a-=1)}}}else if(D.isPair(t)){r=Object.freeze(r.concat(t));let a=await Rt("key",t.key,i,r);if(a===X)return X;a===Se&&(t.key=null);let o=await Rt("value",t.value,i,r);if(o===X)return X;o===Se&&(t.value=null)}}return n}function vc(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function gc(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(D.isMap(t))return i.Map?.(e,t,r);if(D.isSeq(t))return i.Seq?.(e,t,r);if(D.isPair(t))return i.Pair?.(e,t,r);if(D.isScalar(t))return i.Scalar?.(e,t,r);if(D.isAlias(t))return i.Alias?.(e,t,r)}function wc(e,t,i){let r=t[t.length-1];if(D.isCollection(r))r.items[e]=i;else if(D.isPair(r))e==="key"?r.key=i:r.value=i;else if(D.isDocument(r))r.contents=i;else{let n=D.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}pa.visit=gr;pa.visitAsync=wr});var ma=y(Nc=>{"use strict";var yc=P(),Rh=oi(),Ch={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ah=e=>e.replace(/[!,[\]{}]/g,t=>Ch[t]),si=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+Ah(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&yc.isNode(t.contents)){let a={};Rh.visit(t.contents,(o,s)=>{yc.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
|
|
5
|
+
`)}};si.defaultYaml={explicit:!1,version:"1.2"};si.defaultTags={"!!":"tag:yaml.org,2002:"};Nc.Directives=si});var yr=y(ci=>{"use strict";var bc=P(),_h=oi();function Th(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function kc(e){let t=new Set;return _h.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Sc(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function Ih(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=kc(e));let o=Sc(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(bc.isScalar(o.node)||bc.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:r}}ci.anchorIsValid=Th;ci.anchorNames=kc;ci.createNodeAnchors=Ih;ci.findNewAnchor=Sc});var va=y(Ec=>{"use strict";function li(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=li(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=li(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=li(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=li(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}Ec.applyReviver=li});var qe=y(xc=>{"use strict";var jh=P();function Pc(e,t,i){if(Array.isArray(e))return e.map((r,n)=>Pc(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!jh.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}xc.toJS=Pc});var Nr=y(Cc=>{"use strict";var $h=va(),Rc=P(),Oh=qe(),ga=class{constructor(t){Object.defineProperty(this,Rc.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!Rc.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=Oh.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?$h.applyReviver(a,{"":s},"",s):s}};Cc.NodeBase=ga});var ui=y(Ac=>{"use strict";var Hh=yr(),Dh=oi(),Ct=P(),Bh=Nr(),Lh=qe(),wa=class extends Bh.NodeBase{constructor(t){super(Ct.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],Dh.visit(t,{Node:(a,o)=>{(Ct.isAlias(o)||Ct.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(Lh.toJS(o,null,i),s=r.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=br(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if(Hh.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function br(e,t,i){if(Ct.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Ct.isCollection(t)){let r=0;for(let n of t.items){let a=br(e,n,i);a>r&&(r=a)}return r}else if(Ct.isPair(t)){let r=br(e,t.key,i),n=br(e,t.value,i);return Math.max(r,n)}return 1}Ac.Alias=wa});var j=y(ya=>{"use strict";var Fh=P(),Mh=Nr(),Vh=qe(),qh=e=>!e||typeof e!="function"&&typeof e!="object",We=class extends Mh.NodeBase{constructor(t){super(Fh.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:Vh.toJS(this.value,t,i)}toString(){return String(this.value)}};We.BLOCK_FOLDED="BLOCK_FOLDED";We.BLOCK_LITERAL="BLOCK_LITERAL";We.PLAIN="PLAIN";We.QUOTE_DOUBLE="QUOTE_DOUBLE";We.QUOTE_SINGLE="QUOTE_SINGLE";ya.Scalar=We;ya.isScalarValue=qh});var di=y(Tc=>{"use strict";var Wh=ui(),st=P(),_c=j(),zh="tag:yaml.org,2002:";function Jh(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function Gh(e,t,i){if(st.isDocument(e)&&(e=e.contents),st.isNode(e))return e;if(st.isPair(e)){let f=i.schema[st.MAP].createNode?.(i.schema,null,i);return f.items.push(e),f}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Wh.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=zh+t.slice(2));let l=Jh(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let f=new _c.Scalar(e);return c&&(c.node=f),f}l=e instanceof Map?o[st.MAP]:Symbol.iterator in Object(e)?o[st.SEQ]:o[st.MAP]}a&&(a(l),delete i.onTagObj);let d=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new _c.Scalar(e);return t?d.tag=t:l.default||(d.tag=l.tag),c&&(c.node=d),d}Tc.createNode=Gh});var Sr=y(kr=>{"use strict";var Uh=di(),Ee=P(),Kh=Nr();function Na(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return Uh.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Ic=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ba=class extends Kh.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>Ee.isNode(r)||Ee.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Ic(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(Ee.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Na(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(Ee.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&Ee.isScalar(a)?a.value:a:Ee.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!Ee.isPair(i))return!1;let r=i.value;return r==null||t&&Ee.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return Ee.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(Ee.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Na(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};kr.Collection=ba;kr.collectionFromPath=Na;kr.isEmptyPath=Ic});var fi=y(Er=>{"use strict";var Yh=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ka(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Xh=(e,t,i)=>e.endsWith(`
|
|
6
|
+
`)?ka(i,t):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)i===
|
|
8
|
+
`+ka(i,t):(e.endsWith(" ")?"":" ")+i;Er.indentComment=ka;Er.lineComment=Xh;Er.stringifyComment=Yh});var $c=y(hi=>{"use strict";var Qh="flow",Sa="block",Pr="quoted";function Zh(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],d={},f=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):f=n-r);let u,p,v=!1,h=-1,m=-1,g=-1;i===Sa&&(h=jc(e,h,t.length),h!==-1&&(f=h+c));for(let w;w=e[h+=1];){if(i===Pr&&w==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(w===`
|
|
9
|
+
`)i===Sa&&(h=jc(e,h,t.length)),f=h+t.length+c,u=void 0;else{if(w===" "&&p&&p!==" "&&p!==`
|
|
10
10
|
`&&p!==" "){let k=e[h+1];k&&k!==" "&&k!==`
|
|
11
11
|
`&&k!==" "&&(u=h)}if(h>=f)if(u)l.push(u),f=u+c,u=void 0;else if(i===Pr){for(;p===" "||p===" ";)p=w,w=e[h+=1],v=!0;let k=h>g+1?h-2:m-1;if(d[k])return e;l.push(k),d[k]=!0,f=k+c,u=void 0}else v=!0}p=w}if(v&&s&&s(),l.length===0)return e;o&&o();let N=e.slice(0,l[0]);for(let w=0;w<l.length;++w){let k=l[w],S=l[w+1]||e.length;k===0?N=`
|
|
12
12
|
${t}${e.slice(0,S)}`:(i===Pr&&d[k]&&(N+=`${e[k]}\\`),N+=`
|
|
13
|
-
${t}${e.slice(k+1,S)}`)}return N}function
|
|
14
|
-
`);r=t,n=t+1,a=e[n]}return r}
|
|
15
|
-
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function
|
|
13
|
+
${t}${e.slice(k+1,S)}`)}return N}function jc(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
+
`);r=t,n=t+1,a=e[n]}return r}hi.FOLD_BLOCK=Sa;hi.FOLD_FLOW=Qh;hi.FOLD_QUOTED=Pr;hi.foldFlowLines=Zh});var mi=y(Oc=>{"use strict";var me=j(),ze=$c(),Rr=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Cr=e=>/^(%|---|\.\.\.)/m.test(e);function ep(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function pi(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Cr(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let d=i.substr(c+2,4);switch(d){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:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
20
|
-
${i}`)+"'";return t.implicitKey?r:
|
|
18
|
+
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:ze.foldFlowLines(o,a,ze.FOLD_QUOTED,Rr(t,!1))}function Ea(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return pi(e,t);let i=t.indent||(Cr(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return t.implicitKey?r:ze.foldFlowLines(r,i,ze.FOLD_FLOW,Rr(t,!1))}function At(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=pi;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=Ea:a&&!n?r=pi:r=i?Ea:pi}return r(e,t)}var Pa;try{Pa=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{Pa=/\n+(?!\n|$)/g}function xr({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return At(i,r);let l=r.indent||(r.forceBlockIndent||Cr(i)?" ":""),d=o==="literal"?!0:o==="folded"||t===me.Scalar.BLOCK_FOLDED?!1:t===me.Scalar.BLOCK_LITERAL?!0:!ep(i,c,l.length);if(!i)return d?`|
|
|
24
24
|
`:`>
|
|
25
25
|
`;let f,u;for(u=i.length;u>0;--u){let S=i[u-1];if(S!==`
|
|
26
26
|
`&&S!==" "&&S!==" ")break}let p=i.substring(u),v=p.indexOf(`
|
|
27
27
|
`);v===-1?f="-":i===p||v!==p.length-1?(f="+",a&&a()):f="",p&&(i=i.slice(0,-p.length),p[p.length-1]===`
|
|
28
|
-
`&&(p=p.slice(0,-1)),p=p.replace(
|
|
28
|
+
`&&(p=p.slice(0,-1)),p=p.replace(Pa,`$&${l}`));let h=!1,m,g=-1;for(m=0;m<i.length;++m){let S=i[m];if(S===" ")h=!0;else if(S===`
|
|
29
29
|
`)g=m;else break}let N=i.substring(0,g<m?g+1:m);N&&(i=i.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let k=(h?l?"2":"1":"")+f;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!d){let S=i.replace(/\n+/g,`
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,C=Rr(r,!0);o!=="folded"&&t!==
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,C=Rr(r,!0);o!=="folded"&&t!==me.Scalar.BLOCK_FOLDED&&(C.onOverflow=()=>{E=!0});let b=ze.foldFlowLines(`${N}${S}${p}`,l,ze.FOLD_BLOCK,C);if(!E)return`>${k}
|
|
31
31
|
${l}${b}`}return i=i.replace(/\n+/g,`$&${l}`),`|${k}
|
|
32
|
-
${l}${N}${i}${p}`}function
|
|
33
|
-
`)||d&&/[[\]{},]/.test(a))return
|
|
34
|
-
`)?
|
|
35
|
-
`))return xr(e,t,i,r);if(Cr(a)){if(c==="")return t.forceBlockIndent=!0,xr(e,t,i,r);if(s&&c===l)return
|
|
36
|
-
${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(f),{compat:p,tags:v}=t.doc.schema;if(v.some(u)||p?.some(u))return
|
|
37
|
-
${t.indent}${s}`:s}
|
|
38
|
-
${s}:`):(m=`${m}:`,u&&(m+=
|
|
32
|
+
${l}${N}${i}${p}`}function tp(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:d}=t;if(s&&a.includes(`
|
|
33
|
+
`)||d&&/[[\]{},]/.test(a))return At(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||d||!a.includes(`
|
|
34
|
+
`)?At(a,t):xr(e,t,i,r);if(!s&&!d&&n!==me.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return xr(e,t,i,r);if(Cr(a)){if(c==="")return t.forceBlockIndent=!0,xr(e,t,i,r);if(s&&c===l)return At(a,t)}let f=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(f),{compat:p,tags:v}=t.doc.schema;if(v.some(u)||p?.some(u))return At(a,t)}return s?f:ze.foldFlowLines(f,c,ze.FOLD_FLOW,Rr(t,!1))}function ip(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==me.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=me.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case me.Scalar.BLOCK_FOLDED:case me.Scalar.BLOCK_LITERAL:return n||a?At(o.value,t):xr(o,t,i,r);case me.Scalar.QUOTE_DOUBLE:return pi(o.value,t);case me.Scalar.QUOTE_SINGLE:return Ea(o.value,t);case me.Scalar.PLAIN:return tp(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:d,defaultStringType:f}=t.options,u=n&&d||f;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}Oc.stringifyString=ip});var vi=y(xa=>{"use strict";var rp=yr(),Je=P(),np=fi(),ap=mi();function op(e,t){let i=Object.assign({blockQuote:!0,commentString:np.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function sp(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(Je.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function cp(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Je.isScalar(e)||Je.isCollection(e))&&e.anchor;a&&rp.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function lp(e,t,i,r){if(Je.isPair(e))return e.toString(t,i,r);if(Je.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=Je.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=sp(t.doc.schema.tags,a));let o=cp(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):Je.isScalar(a)?ap.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Je.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}xa.createStringifyContext=op;xa.stringify=lp});var Lc=y(Bc=>{"use strict";var je=P(),Hc=j(),Dc=vi(),gi=fi();function up({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:f}}=i,u=je.isNode(e)&&e.comment||null;if(f){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(je.isCollection(e)||!je.isNode(e)&&typeof e=="object"){let C="With simple keys, collection cannot be used as a key value";throw new Error(C)}}let p=!f&&(!e||u&&t==null&&!i.inFlow||je.isCollection(e)||(je.isScalar(e)?e.type===Hc.Scalar.BLOCK_FOLDED||e.type===Hc.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(f||!a),indent:s+c});let v=!1,h=!1,m=Dc.stringify(e,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!f||t==null&&p)return m=`? ${m}`,u&&!v?m+=gi.lineComment(m,i.indent,l(u)):h&&n&&n(),m;v&&(u=null),p?(u&&(m+=gi.lineComment(m,i.indent,l(u))),m=`? ${m}
|
|
38
|
+
${s}:`):(m=`${m}:`,u&&(m+=gi.lineComment(m,i.indent,l(u))));let g,N,w;je.isNode(t)?(g=!!t.spaceBefore,N=t.commentBefore,w=t.comment):(g=!1,N=null,w=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!u&&je.isScalar(t)&&(i.indentAtStart=m.length+1),h=!1,!d&&c.length>=2&&!i.inFlow&&!p&&je.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let k=!1,S=Dc.stringify(t,i,()=>k=!0,()=>h=!0),E=" ";if(u||g||N){if(E=g?`
|
|
39
39
|
`:"",N){let C=l(N);E+=`
|
|
40
|
-
${
|
|
40
|
+
${gi.indentComment(C,i.indent)}`}S===""&&!i.inFlow?E===`
|
|
41
41
|
`&&w&&(E=`
|
|
42
42
|
|
|
43
43
|
`):E+=`
|
|
44
44
|
${i.indent}`}else if(!p&&je.isCollection(t)){let C=S[0],b=S.indexOf(`
|
|
45
|
-
`)
|
|
45
|
+
`),O=b!==-1,Me=i.inFlow??t.flow??t.items.length===0;if(O||!Me){let Pt=!1;if(O&&(C==="&"||C==="!")){let H=S.indexOf(" ");C==="&"&&H!==-1&&H<b&&S[H+1]==="!"&&(H=S.indexOf(" ",H+1)),(H===-1||b<H)&&(Pt=!0)}Pt||(E=`
|
|
46
46
|
${i.indent}`)}}else(S===""||S[0]===`
|
|
47
|
-
`)&&(E="");return m+=E+S,i.inFlow?k&&r&&r():w&&!k?m+=
|
|
47
|
+
`)&&(E="");return m+=E+S,i.inFlow?k&&r&&r():w&&!k?m+=gi.lineComment(m,i.indent,l(w)):h&&n&&n(),m}Bc.stringifyPair=up});var Ca=y(Ra=>{"use strict";var Fc=fr("process");function dp(e,...t){e==="debug"&&console.log(...t)}function fp(e,t){(e==="debug"||e==="warn")&&(typeof Fc.emitWarning=="function"?Fc.emitWarning(t):console.warn(t))}Ra.debug=dp;Ra.warn=fp});var jr=y(Ir=>{"use strict";var Tr=P(),Mc=j(),Ar="<<",_r={identify:e=>e===Ar||typeof e=="symbol"&&e.description===Ar,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Mc.Scalar(Symbol(Ar)),{addToJSMap:Vc}),stringify:()=>Ar},hp=(e,t)=>(_r.identify(t)||Tr.isScalar(t)&&(!t.type||t.type===Mc.Scalar.PLAIN)&&_r.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===_r.tag&&i.default);function Vc(e,t,i){let r=qc(e,i);if(Tr.isSeq(r))for(let n of r.items)Aa(e,t,n);else if(Array.isArray(r))for(let n of r)Aa(e,t,n);else Aa(e,t,r)}function Aa(e,t,i){let r=qc(e,i);if(!Tr.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function qc(e,t){return e&&Tr.isAlias(t)?t.resolve(e.doc,e):t}Ir.addMergeToJSMap=Vc;Ir.isMergeKey=hp;Ir.merge=_r});var Ta=y(Jc=>{"use strict";var pp=Ca(),Wc=jr(),mp=vi(),zc=P(),_a=qe();function vp(e,t,{key:i,value:r}){if(zc.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Wc.isMergeKey(e,i))Wc.addMergeToJSMap(e,t,r);else{let n=_a.toJS(i,"",e);if(t instanceof Map)t.set(n,_a.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=gp(i,n,e),o=_a.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function gp(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(zc.isNode(e)&&i?.doc){let r=mp.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),pp.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}Jc.addPairToJSMap=vp});var Ge=y(Ia=>{"use strict";var Gc=di(),wp=Lc(),yp=Ta(),$r=P();function Np(e,t,i){let r=Gc.createNode(e,void 0,i),n=Gc.createNode(t,void 0,i);return new Or(r,n)}var Or=class e{constructor(t,i=null){Object.defineProperty(this,$r.NODE_TYPE,{value:$r.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return $r.isNode(i)&&(i=i.clone(t)),$r.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return yp.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?wp.stringifyPair(this,t,i,r):JSON.stringify(this)}};Ia.Pair=Or;Ia.createPair=Np});var ja=y(Kc=>{"use strict";var ct=P(),Uc=vi(),Hr=fi();function bp(e,t,i){return(t.inFlow??e.flow?Sp:kp)(e,t,i)}function kp({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,d=Object.assign({},i,{indent:a,type:null}),f=!1,u=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(ct.isNode(h))!f&&h.spaceBefore&&u.push(""),Dr(i,u,h.commentBefore,f),h.comment&&(m=h.comment);else if(ct.isPair(h)){let N=ct.isNode(h.key)?h.key:null;N&&(!f&&N.spaceBefore&&u.push(""),Dr(i,u,N.commentBefore,f))}f=!1;let g=Uc.stringify(h,d,()=>m=null,()=>f=!0);m&&(g+=Hr.lineComment(g,a,l(m))),f&&m&&(f=!1),u.push(r+g)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let v=1;v<u.length;++v){let h=u[v];p+=h?`
|
|
48
48
|
${c}${h}`:`
|
|
49
49
|
`}}return e?(p+=`
|
|
50
|
-
`+Hr.indentComment(l(e),c),s&&s()):f&&o&&o(),p}function
|
|
50
|
+
`+Hr.indentComment(l(e),c),s&&s()):f&&o&&o(),p}function Sp({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,d=0,f=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(ct.isNode(h))h.spaceBefore&&f.push(""),Dr(t,f,h.commentBefore,!1),h.comment&&(m=h.comment);else if(ct.isPair(h)){let N=ct.isNode(h.key)?h.key:null;N&&(N.spaceBefore&&f.push(""),Dr(t,f,N.commentBefore,!1),N.comment&&(l=!0));let w=ct.isNode(h.value)?h.value:null;w?(w.comment&&(m=w.comment),w.commentBefore&&(l=!0)):h.value==null&&N?.comment&&(m=N.comment)}m&&(l=!0);let g=Uc.stringify(h,c,()=>m=null);l||(l=f.length>d||g.includes(`
|
|
51
51
|
`)),v<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=f.reduce((N,w)=>N+w.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),m&&(g+=Hr.lineComment(g,r,s(m))),f.push(g),d=f.length}let{start:u,end:p}=i;if(f.length===0)return u+p;if(!l){let v=f.reduce((h,m)=>h+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=u;for(let h of f)v+=h?`
|
|
52
52
|
${a}${n}${h}`:`
|
|
53
53
|
`;return`${v}
|
|
54
|
-
${n}${p}`}else return`${u}${o}${f.join(" ")}${o}${p}`}function Dr({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Hr.indentComment(t(r),e);i.push(a.trimStart())}}
|
|
55
|
-
`:" ")}return
|
|
54
|
+
${n}${p}`}else return`${u}${o}${f.join(" ")}${o}${p}`}function Dr({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Hr.indentComment(t(r),e);i.push(a.trimStart())}}Kc.stringifyCollection=bp});var Ke=y(Oa=>{"use strict";var Ep=ja(),Pp=Ta(),xp=Sr(),Ue=P(),Br=Ge(),Rp=j();function wi(e,t){let i=Ue.isScalar(t)?t.value:t;for(let r of e)if(Ue.isPair(r)&&(r.key===t||r.key===i||Ue.isScalar(r.key)&&r.key.value===i))return r}var $a=class extends xp.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ue.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Br.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;Ue.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Br.Pair(t,t?.value):r=new Br.Pair(t.key,t.value);let n=wi(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Ue.isScalar(n.value)&&Rp.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=wi(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=wi(this.items,t)?.value;return(!i&&Ue.isScalar(n)?n.value:n)??void 0}has(t){return!!wi(this.items,t)}set(t,i){this.add(new Br.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)Pp.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Ue.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Ep.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Oa.YAMLMap=$a;Oa.findPair=wi});var _t=y(Xc=>{"use strict";var Cp=P(),Yc=Ke(),Ap={collection:"map",default:!0,nodeClass:Yc.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Cp.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Yc.YAMLMap.from(e,t,i)};Xc.map=Ap});var Ye=y(Qc=>{"use strict";var _p=di(),Tp=ja(),Ip=Sr(),Fr=P(),jp=j(),$p=qe(),Ha=class extends Ip.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Fr.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Lr(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Lr(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Fr.isScalar(n)?n.value:n}has(t){let i=Lr(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Lr(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Fr.isScalar(n)&&jp.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push($p.toJS(a,String(n++),i));return r}toString(t,i,r){return t?Tp.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(_p.createNode(s,void 0,r))}}return a}};function Lr(e){let t=Fr.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Qc.YAMLSeq=Ha});var Tt=y(el=>{"use strict";var Op=P(),Zc=Ye(),Hp={collection:"seq",default:!0,nodeClass:Zc.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Op.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Zc.YAMLSeq.from(e,t,i)};el.seq=Hp});var yi=y(tl=>{"use strict";var Dp=mi(),Bp={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),Dp.stringifyString(e,t,i,r)}};tl.string=Bp});var Mr=y(nl=>{"use strict";var il=j(),rl={identify:e=>e==null,createNode:()=>new il.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new il.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&rl.test.test(e)?e:t.options.nullStr};nl.nullTag=rl});var Da=y(ol=>{"use strict";var Lp=j(),al={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Lp.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&al.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};ol.boolTag=al});var It=y(sl=>{"use strict";function Fp({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}sl.stringifyNumber=Fp});var La=y(Vr=>{"use strict";var Mp=j(),Ba=It(),Vp={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ba.stringifyNumber},qp={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Ba.stringifyNumber(e)}},Wp={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new Mp.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Ba.stringifyNumber};Vr.float=Wp;Vr.floatExp=qp;Vr.floatNaN=Vp});var Ma=y(Wr=>{"use strict";var cl=It(),qr=e=>typeof e=="bigint"||Number.isInteger(e),Fa=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function ll(e,t,i){let{value:r}=e;return qr(r)&&r>=0?i+r.toString(t):cl.stringifyNumber(e)}var zp={identify:e=>qr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Fa(e,2,8,i),stringify:e=>ll(e,8,"0o")},Jp={identify:qr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Fa(e,0,10,i),stringify:cl.stringifyNumber},Gp={identify:e=>qr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Fa(e,2,16,i),stringify:e=>ll(e,16,"0x")};Wr.int=Jp;Wr.intHex=Gp;Wr.intOct=zp});var dl=y(ul=>{"use strict";var Up=_t(),Kp=Mr(),Yp=Tt(),Xp=yi(),Qp=Da(),Va=La(),qa=Ma(),Zp=[Up.map,Yp.seq,Xp.string,Kp.nullTag,Qp.boolTag,qa.intOct,qa.int,qa.intHex,Va.floatNaN,Va.floatExp,Va.float];ul.schema=Zp});var pl=y(hl=>{"use strict";var em=j(),tm=_t(),im=Tt();function fl(e){return typeof e=="bigint"||Number.isInteger(e)}var zr=({value:e})=>JSON.stringify(e),rm=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:zr},{identify:e=>e==null,createNode:()=>new em.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:zr},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:zr},{identify:fl,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>fl(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:zr}],nm={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},am=[tm.map,im.seq].concat(rm,nm);hl.schema=am});var za=y(ml=>{"use strict";var Ni=fr("buffer"),Wa=j(),om=mi(),sm={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ni.Buffer=="function")return Ni.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof Ni.Buffer=="function")s=o instanceof Ni.Buffer?o.toString("base64"):Ni.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Wa.Scalar.BLOCK_LITERAL),t!==Wa.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),d=new Array(l);for(let f=0,u=0;f<l;++f,u+=c)d[f]=s.substr(u,c);s=d.join(t===Wa.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return om.stringifyString({comment:e,type:t,value:s},r,n,a)}};ml.binary=sm});var Ur=y(Gr=>{"use strict";var Jr=P(),Ja=Ge(),cm=j(),lm=Ye();function vl(e,t){if(Jr.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!Jr.isPair(r)){if(Jr.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Ja.Pair(new cm.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
|
|
56
56
|
${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
|
|
57
|
-
${a.comment}`:r.comment}r=n}e.items[i]=Jr.isPair(r)?r:new Wa.Pair(r)}}else t("Expected a sequence for this tag");return e}function pl(e,t,i){let{replacer:r}=i,n=new Xp.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Wa.createPair(s,c,i))}return n}var Qp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:hl,createNode:pl};Gr.createPairs=pl;Gr.pairs=Qp;Gr.resolvePairs=hl});var Ga=y(Ja=>{"use strict";var ml=P(),za=Ve(),wi=Ue(),Zp=Ke(),vl=Ur(),ot=class e extends Zp.YAMLSeq{constructor(){super(),this.add=wi.YAMLMap.prototype.add.bind(this),this.delete=wi.YAMLMap.prototype.delete.bind(this),this.get=wi.YAMLMap.prototype.get.bind(this),this.has=wi.YAMLMap.prototype.has.bind(this),this.set=wi.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(ml.isPair(n)?(a=za.toJS(n.key,"",i),o=za.toJS(n.value,a,i)):a=za.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=vl.createPairs(t,i,r),a=new this;return a.items=n.items,a}};ot.tag="tag:yaml.org,2002:omap";var em={collection:"seq",identify:e=>e instanceof Map,nodeClass:ot,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=vl.resolvePairs(e,t),r=[];for(let{key:n}of i.items)ml.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new ot,i)},createNode:(e,t,i)=>ot.from(e,t,i)};Ja.YAMLOMap=ot;Ja.omap=em});var bl=y(Ua=>{"use strict";var gl=I();function wl({value:e,source:t},i){return t&&(e?yl:Nl).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var yl={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new gl.Scalar(!0),stringify:wl},Nl={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new gl.Scalar(!1),stringify:wl};Ua.falseTag=Nl;Ua.trueTag=yl});var kl=y(Kr=>{"use strict";var tm=I(),Ka=_t(),im={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ka.stringifyNumber},rm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Ka.stringifyNumber(e)}},nm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new tm.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:Ka.stringifyNumber};Kr.float=nm;Kr.floatExp=rm;Kr.floatNaN=im});var El=y(Ni=>{"use strict";var Sl=_t(),yi=e=>typeof e=="bigint"||Number.isInteger(e);function Yr(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function Ya(e,t,i){let{value:r}=e;if(yi(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Sl.stringifyNumber(e)}var am={identify:yi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Yr(e,2,2,i),stringify:e=>Ya(e,2,"0b")},om={identify:yi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Yr(e,1,8,i),stringify:e=>Ya(e,8,"0")},sm={identify:yi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Yr(e,0,10,i),stringify:Sl.stringifyNumber},cm={identify:yi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Yr(e,2,16,i),stringify:e=>Ya(e,16,"0x")};Ni.int=sm;Ni.intBin=am;Ni.intHex=cm;Ni.intOct=om});var Qa=y(Xa=>{"use strict";var Zr=P(),Xr=Je(),Qr=Ue(),st=class e extends Qr.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Zr.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Xr.Pair(t.key,null):i=new Xr.Pair(t,null),Qr.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Qr.findPair(this.items,t);return!i&&Zr.isPair(r)?Zr.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Qr.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Xr.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Xr.createPair(o,null,r));return a}};st.tag="tag:yaml.org,2002:set";var lm={collection:"map",identify:e=>e instanceof Set,nodeClass:st,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>st.from(e,t,i),resolve(e,t){if(Zr.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new st,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Xa.YAMLSet=st;Xa.set=lm});var eo=y(en=>{"use strict";var um=_t();function Za(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Pl(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return um.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var dm={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>Za(e,i),stringify:Pl},fm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Za(e,!1),stringify:Pl},xl={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(xl.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),d=t[8];if(d&&d!=="Z"){let f=Za(d,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};en.floatTime=fm;en.intTime=dm;en.timestamp=xl});var Al=y(Cl=>{"use strict";var hm=Ct(),pm=Mr(),mm=At(),vm=vi(),gm=qa(),Rl=bl(),to=kl(),tn=El(),wm=jr(),ym=Ga(),Nm=Ur(),bm=Qa(),io=eo(),km=[hm.map,mm.seq,vm.string,pm.nullTag,Rl.trueTag,Rl.falseTag,tn.intBin,tn.intOct,tn.int,tn.intHex,to.floatNaN,to.floatExp,to.float,gm.binary,wm.merge,ym.omap,Nm.pairs,bm.set,io.intTime,io.floatTime,io.timestamp];Cl.schema=km});var Ll=y(ao=>{"use strict";var jl=Ct(),Sm=Mr(),$l=At(),Em=vi(),Pm=Oa(),ro=Da(),no=La(),xm=cl(),Rm=dl(),Ol=qa(),bi=jr(),Hl=Ga(),Dl=Ur(),_l=Al(),Bl=Qa(),rn=eo(),Tl=new Map([["core",xm.schema],["failsafe",[jl.map,$l.seq,Em.string]],["json",Rm.schema],["yaml11",_l.schema],["yaml-1.1",_l.schema]]),Il={binary:Ol.binary,bool:Pm.boolTag,float:ro.float,floatExp:ro.floatExp,floatNaN:ro.floatNaN,floatTime:rn.floatTime,int:no.int,intHex:no.intHex,intOct:no.intOct,intTime:rn.intTime,map:jl.map,merge:bi.merge,null:Sm.nullTag,omap:Hl.omap,pairs:Dl.pairs,seq:$l.seq,set:Bl.set,timestamp:rn.timestamp},Cm={"tag:yaml.org,2002:binary":Ol.binary,"tag:yaml.org,2002:merge":bi.merge,"tag:yaml.org,2002:omap":Hl.omap,"tag:yaml.org,2002:pairs":Dl.pairs,"tag:yaml.org,2002:set":Bl.set,"tag:yaml.org,2002:timestamp":rn.timestamp};function Am(e,t,i){let r=Tl.get(t);if(r&&!e)return i&&!r.includes(bi.merge)?r.concat(bi.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Tl.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(bi.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Il[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Il).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}ao.coreKnownTags=Cm;ao.getTags=Am});var co=y(Fl=>{"use strict";var oo=P(),_m=Ct(),Tm=At(),Im=vi(),nn=Ll(),jm=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,so=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?nn.getTags(t,"compat"):t?nn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?nn.coreKnownTags:{},this.tags=nn.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,oo.MAP,{value:_m.map}),Object.defineProperty(this,oo.SCALAR,{value:Im.string}),Object.defineProperty(this,oo.SEQ,{value:Tm.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?jm:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Fl.Schema=so});var Vl=y(Ml=>{"use strict";var $m=P(),lo=hi(),ki=li();function Om(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=lo.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(ki.indentComment(c,""))}let o=!1,s=null;if(e.contents){if($m.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let d=a(e.contents.commentBefore);i.push(ki.indentComment(d,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=lo.stringify(e.contents,n,()=>s=null,c);s&&(l+=ki.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(lo.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
-
`)?(i.push("..."),i.push(
|
|
57
|
+
${a.comment}`:r.comment}r=n}e.items[i]=Jr.isPair(r)?r:new Ja.Pair(r)}}else t("Expected a sequence for this tag");return e}function gl(e,t,i){let{replacer:r}=i,n=new lm.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Ja.createPair(s,c,i))}return n}var um={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:vl,createNode:gl};Gr.createPairs=gl;Gr.pairs=um;Gr.resolvePairs=vl});var Ka=y(Ua=>{"use strict";var wl=P(),Ga=qe(),bi=Ke(),dm=Ye(),yl=Ur(),lt=class e extends dm.YAMLSeq{constructor(){super(),this.add=bi.YAMLMap.prototype.add.bind(this),this.delete=bi.YAMLMap.prototype.delete.bind(this),this.get=bi.YAMLMap.prototype.get.bind(this),this.has=bi.YAMLMap.prototype.has.bind(this),this.set=bi.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(wl.isPair(n)?(a=Ga.toJS(n.key,"",i),o=Ga.toJS(n.value,a,i)):a=Ga.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=yl.createPairs(t,i,r),a=new this;return a.items=n.items,a}};lt.tag="tag:yaml.org,2002:omap";var fm={collection:"seq",identify:e=>e instanceof Map,nodeClass:lt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=yl.resolvePairs(e,t),r=[];for(let{key:n}of i.items)wl.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new lt,i)},createNode:(e,t,i)=>lt.from(e,t,i)};Ua.YAMLOMap=lt;Ua.omap=fm});var El=y(Ya=>{"use strict";var Nl=j();function bl({value:e,source:t},i){return t&&(e?kl:Sl).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var kl={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Nl.Scalar(!0),stringify:bl},Sl={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Nl.Scalar(!1),stringify:bl};Ya.falseTag=Sl;Ya.trueTag=kl});var Pl=y(Kr=>{"use strict";var hm=j(),Xa=It(),pm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Xa.stringifyNumber},mm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Xa.stringifyNumber(e)}},vm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new hm.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:Xa.stringifyNumber};Kr.float=vm;Kr.floatExp=mm;Kr.floatNaN=pm});var Rl=y(Si=>{"use strict";var xl=It(),ki=e=>typeof e=="bigint"||Number.isInteger(e);function Yr(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function Qa(e,t,i){let{value:r}=e;if(ki(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return xl.stringifyNumber(e)}var gm={identify:ki,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Yr(e,2,2,i),stringify:e=>Qa(e,2,"0b")},wm={identify:ki,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Yr(e,1,8,i),stringify:e=>Qa(e,8,"0")},ym={identify:ki,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Yr(e,0,10,i),stringify:xl.stringifyNumber},Nm={identify:ki,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Yr(e,2,16,i),stringify:e=>Qa(e,16,"0x")};Si.int=ym;Si.intBin=gm;Si.intHex=Nm;Si.intOct=wm});var eo=y(Za=>{"use strict";var Zr=P(),Xr=Ge(),Qr=Ke(),ut=class e extends Qr.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Zr.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Xr.Pair(t.key,null):i=new Xr.Pair(t,null),Qr.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Qr.findPair(this.items,t);return!i&&Zr.isPair(r)?Zr.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Qr.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Xr.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Xr.createPair(o,null,r));return a}};ut.tag="tag:yaml.org,2002:set";var bm={collection:"map",identify:e=>e instanceof Set,nodeClass:ut,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>ut.from(e,t,i),resolve(e,t){if(Zr.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new ut,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Za.YAMLSet=ut;Za.set=bm});var io=y(en=>{"use strict";var km=It();function to(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Cl(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return km.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Sm={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>to(e,i),stringify:Cl},Em={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>to(e,!1),stringify:Cl},Al={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(Al.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),d=t[8];if(d&&d!=="Z"){let f=to(d,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};en.floatTime=Em;en.intTime=Sm;en.timestamp=Al});var Il=y(Tl=>{"use strict";var Pm=_t(),xm=Mr(),Rm=Tt(),Cm=yi(),Am=za(),_l=El(),ro=Pl(),tn=Rl(),_m=jr(),Tm=Ka(),Im=Ur(),jm=eo(),no=io(),$m=[Pm.map,Rm.seq,Cm.string,xm.nullTag,_l.trueTag,_l.falseTag,tn.intBin,tn.intOct,tn.int,tn.intHex,ro.floatNaN,ro.floatExp,ro.float,Am.binary,_m.merge,Tm.omap,Im.pairs,jm.set,no.intTime,no.floatTime,no.timestamp];Tl.schema=$m});var Vl=y(so=>{"use strict";var Hl=_t(),Om=Mr(),Dl=Tt(),Hm=yi(),Dm=Da(),ao=La(),oo=Ma(),Bm=dl(),Lm=pl(),Bl=za(),Ei=jr(),Ll=Ka(),Fl=Ur(),jl=Il(),Ml=eo(),rn=io(),$l=new Map([["core",Bm.schema],["failsafe",[Hl.map,Dl.seq,Hm.string]],["json",Lm.schema],["yaml11",jl.schema],["yaml-1.1",jl.schema]]),Ol={binary:Bl.binary,bool:Dm.boolTag,float:ao.float,floatExp:ao.floatExp,floatNaN:ao.floatNaN,floatTime:rn.floatTime,int:oo.int,intHex:oo.intHex,intOct:oo.intOct,intTime:rn.intTime,map:Hl.map,merge:Ei.merge,null:Om.nullTag,omap:Ll.omap,pairs:Fl.pairs,seq:Dl.seq,set:Ml.set,timestamp:rn.timestamp},Fm={"tag:yaml.org,2002:binary":Bl.binary,"tag:yaml.org,2002:merge":Ei.merge,"tag:yaml.org,2002:omap":Ll.omap,"tag:yaml.org,2002:pairs":Fl.pairs,"tag:yaml.org,2002:set":Ml.set,"tag:yaml.org,2002:timestamp":rn.timestamp};function Mm(e,t,i){let r=$l.get(t);if(r&&!e)return i&&!r.includes(Ei.merge)?r.concat(Ei.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from($l.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(Ei.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Ol[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Ol).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}so.coreKnownTags=Fm;so.getTags=Mm});var uo=y(ql=>{"use strict";var co=P(),Vm=_t(),qm=Tt(),Wm=yi(),nn=Vl(),zm=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,lo=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?nn.getTags(t,"compat"):t?nn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?nn.coreKnownTags:{},this.tags=nn.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,co.MAP,{value:Vm.map}),Object.defineProperty(this,co.SCALAR,{value:Wm.string}),Object.defineProperty(this,co.SEQ,{value:qm.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?zm:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};ql.Schema=lo});var zl=y(Wl=>{"use strict";var Jm=P(),fo=vi(),Pi=fi();function Gm(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=fo.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Pi.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Jm.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let d=a(e.contents.commentBefore);i.push(Pi.indentComment(d,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=fo.stringify(e.contents,n,()=>s=null,c);s&&(l+=Pi.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(fo.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
+
`)?(i.push("..."),i.push(Pi.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(Pi.indentComment(a(c),"")))}return i.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}Wl.stringifyDocument=Gm});var xi=y(Jl=>{"use strict";var Um=ui(),jt=Sr(),le=P(),Km=Ge(),Ym=qe(),Xm=uo(),Qm=zl(),ho=yr(),Zm=va(),ev=di(),po=ma(),mo=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,le.NODE_TYPE,{value:le.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new po.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[le.NODE_TYPE]:{value:le.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=le.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){$t(this.contents)&&this.contents.add(t)}addIn(t,i){$t(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=ho.anchorNames(this);t.anchor=!i||r.has(i)?ho.findNewAnchor(i||"a",r):i}return new Um.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let m=N=>typeof N=="number"||N instanceof String||N instanceof Number,g=i.filter(m).map(String);g.length>0&&(i=i.concat(g)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:d}=r??{},{onAnchor:f,setAnchors:u,sourceObjects:p}=ho.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=ev.createNode(t,d,v);return s&&le.isCollection(h)&&(h.flow=!0),u(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new Km.Pair(n,a)}delete(t){return $t(this.contents)?this.contents.delete(t):!1}deleteIn(t){return jt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):$t(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return le.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return jt.isEmptyPath(t)?!i&&le.isScalar(this.contents)?this.contents.value:this.contents:le.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return le.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return jt.isEmptyPath(t)?this.contents!==void 0:le.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=jt.collectionFromPath(this.schema,[t],i):$t(this.contents)&&this.contents.set(t,i)}setIn(t,i){jt.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=jt.collectionFromPath(this.schema,Array.from(t),i):$t(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new po.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new po.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new Xm.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Ym.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:d}of s.anchors.values())a(d,l);return typeof o=="function"?Zm.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return Qm.stringifyDocument(this,t)}};function $t(e){if(le.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Jl.Document=mo});var Ai=y(Ci=>{"use strict";var Ri=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},vo=class extends Ri{constructor(t,i,r){super("YAMLParseError",t,i,r)}},go=class extends Ri{constructor(t,i,r){super("YAMLWarning",t,i,r)}},tv=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};
|
|
66
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(
|
|
67
|
-
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||
|
|
68
|
-
`+w.comment:N.comment=w.comment);let k=new
|
|
69
|
-
`+E.comment:l.comment=E.comment),f=E.end;continue}!o&&i.options.strict&&
|
|
70
|
-
`+C:b.comment=C,E.comment=E.comment.substring(C.length+1)}}if(!o&&!k&&!E.found){let C=S?e(i,S,E,n):t(i,E.end,k,null,E,n);l.items.push(C),f=C.range[2],
|
|
71
|
-
|
|
72
|
-
`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}
|
|
65
|
+
`}};Ci.YAMLError=Ri;Ci.YAMLParseError=vo;Ci.YAMLWarning=go;Ci.prettifyError=tv});var _i=y(Gl=>{"use strict";function iv(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,d=s,f="",u="",p=!1,v=!1,h=null,m=null,g=null,N=null,w=null,k=null,S=null;for(let b of e)switch(v&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&b.type!=="comment"&&b.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),d=!0;break;case"comment":{d||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let O=b.source.substring(1)||" ";f?f+=u+O:f=O,u="",l=!1;break}case"newline":l?f?f+=b.source:(!k||i!=="seq-item-ind")&&(c=!0):u+=b.source,l=!0,p=!0,(m||g)&&(N=b),d=!0;break;case"anchor":m&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=b,S??(S=b.offset),l=!1,d=!1,v=!0;break;case"tag":{g&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),g=b,S??(S=b.offset),l=!1,d=!1,v=!0;break}case i:(m||g)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),k&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),k=b,l=i==="seq-item-ind"||i==="explicit-key-ind",d=!1;break;case"comma":if(t){w&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=b,l=!1,d=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,d=!1}let E=e[e.length-1],C=E?E.offset+E.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:k,spaceBefore:c,comment:f,hasNewline:p,anchor:m,tag:g,newlineAfterProp:N,end:C,start:S??C}}Gl.resolveProps=iv});var an=y(Ul=>{"use strict";function wo(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(wo(t.key)||wo(t.value))return!0}return!1;default:return!0}}Ul.containsNewline=wo});var yo=y(Kl=>{"use strict";var rv=an();function nv(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&rv.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Kl.flowIndentCheck=nv});var No=y(Xl=>{"use strict";var Yl=P();function av(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Yl.isScalar(a)&&Yl.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Xl.mapIncludes=av});var ru=y(iu=>{"use strict";var Ql=Ge(),ov=Ke(),Zl=_i(),sv=an(),eu=yo(),cv=No(),tu="All mapping items must start at the same column";function lv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??ov.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let d of r.items){let{start:f,key:u,sep:p,value:v}=d,h=Zl.resolveProps(f,{indicator:"explicit-key-ind",next:u??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&n(c,"BAD_INDENT",tu)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||sv.containsNewline(u))&&n(u??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",tu);i.atKey=!0;let g=h.end,N=u?e(i,u,h,n):t(i,g,f,null,h,n);i.schema.compat&&eu.flowIndentCheck(r.indent,u,n),i.atKey=!1,cv.mapIncludes(i,s.items,N)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let w=Zl.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!u||u.type==="block-scalar"});if(c=w.end,w.found){m&&(v?.type==="block-map"&&!w.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<w.found.offset-1024&&n(N.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=v?e(i,v,w,n):t(i,c,p,null,w,n);i.schema.compat&&eu.flowIndentCheck(r.indent,v,n),c=k.range[2];let S=new Ql.Pair(N,k);i.options.keepSourceTokens&&(S.srcToken=d),s.items.push(S)}else{m&&n(N.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),w.comment&&(N.comment?N.comment+=`
|
|
68
|
+
`+w.comment:N.comment=w.comment);let k=new Ql.Pair(N);i.options.keepSourceTokens&&(k.srcToken=d),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}iu.resolveBlockMap=lv});var au=y(nu=>{"use strict";var uv=Ye(),dv=_i(),fv=yo();function hv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??uv.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:d,value:f}of r.items){let u=dv.resolveProps(d,{indicator:"seq-item-ind",next:f,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||f)f?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let p=f?e(i,f,u,n):t(i,u.end,d,null,u,n);i.schema.compat&&fv.flowIndentCheck(r.indent,f,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}nu.resolveBlockSeq=hv});var Ot=y(ou=>{"use strict";function pv(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";n?n+=o+d:n=d,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}ou.resolveEnd=pv});var uu=y(lu=>{"use strict";var mv=P(),vv=Ge(),su=Ke(),gv=Ye(),wv=Ot(),cu=_i(),yv=an(),Nv=No(),bo="Block collections are not allowed within flow collections",ko=e=>e&&(e.type==="block-map"||e.type==="block-seq");function bv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?su.YAMLMap:gv.YAMLSeq),l=new c(i.schema);l.flow=!0;let d=i.atRoot;d&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let f=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let g=r.items[m],{start:N,key:w,sep:k,value:S}=g,E=cu.resolveProps(N,{flow:s,indicator:"explicit-key-ind",next:w??k?.[0],offset:f,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!k&&!S){m===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+E.comment:l.comment=E.comment),f=E.end;continue}!o&&i.options.strict&&yv.containsNewline(w)&&n(w,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let C="";e:for(let b of N)switch(b.type){case"comma":case"space":break;case"comment":C=b.source.substring(1);break e;default:break e}if(C){let b=l.items[l.items.length-1];mv.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
|
|
70
|
+
`+C:b.comment=C,E.comment=E.comment.substring(C.length+1)}}if(!o&&!k&&!E.found){let C=S?e(i,S,E,n):t(i,E.end,k,null,E,n);l.items.push(C),f=C.range[2],ko(S)&&n(C.range,"BLOCK_IN_FLOW",bo)}else{i.atKey=!0;let C=E.end,b=w?e(i,w,E,n):t(i,C,N,null,E,n);ko(w)&&n(b.range,"BLOCK_IN_FLOW",bo),i.atKey=!1;let O=cu.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:S,offset:b.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(O.found){if(!o&&!E.found&&i.options.strict){if(k)for(let H of k){if(H===O.found)break;if(H.type==="newline"){n(H,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<O.found.offset-1024&&n(O.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?n(S,"MISSING_CHAR",`Missing space after : in ${s}`):n(O.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let Me=S?e(i,S,O,n):O.found?t(i,O.end,k,null,O,n):null;Me?ko(S)&&n(Me.range,"BLOCK_IN_FLOW",bo):O.comment&&(b.comment?b.comment+=`
|
|
71
|
+
`+O.comment:b.comment=O.comment);let Pt=new vv.Pair(b,Me);if(i.options.keepSourceTokens&&(Pt.srcToken=g),o){let H=l;Nv.mapIncludes(i,H.items,b)&&n(C,"DUPLICATE_KEY","Map keys must be unique"),H.items.push(Pt)}else{let H=new su.YAMLMap(i.schema);H.flow=!0,H.items.push(Pt);let ac=(Me??b).range;H.range=[b.range[0],ac[1],ac[2]],l.items.push(H)}f=Me?Me.range[2]:O.end}}let u=o?"}":"]",[p,...v]=r.end,h=f;if(p?.source===u)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),g=d?`${m} must end with a ${u}`:`${m} in block collection must be sufficiently indented and end with a ${u}`;n(f,d?"MISSING_CHAR":"BAD_INDENT",g),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=wv.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}lu.resolveFlowCollection=bv});var fu=y(du=>{"use strict";var kv=P(),Sv=j(),Ev=Ke(),Pv=Ye(),xv=ru(),Rv=au(),Cv=uu();function So(e,t,i,r,n,a){let o=i.type==="block-map"?xv.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?Rv.resolveBlockSeq(e,t,i,r,a):Cv.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Av(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(i.type==="block-seq"){let{anchor:u,newlineAfterProp:p}=r,v=u&&a?u.offset>a.offset?u:a:u??a;v&&(!p||p.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===Ev.YAMLMap.tagName&&s==="map"||o===Pv.YAMLSeq.tagName&&s==="seq")return So(e,t,i,n,o);let c=t.schema.tags.find(u=>u.tag===o&&u.collection===s);if(!c){let u=t.schema.knownTags[o];if(u?.collection===s)t.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),So(e,t,i,n,o)}let l=So(e,t,i,n,o,c),d=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),t.options)??l,f=kv.isNode(d)?d:new Sv.Scalar(d);return f.range=l.range,f.tag=o,c?.format&&(f.format=c.format),f}du.composeCollection=Av});var Po=y(hu=>{"use strict";var Eo=j();function _v(e,t,i){let r=t.offset,n=Tv(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Eo.Scalar.BLOCK_FOLDED:Eo.Scalar.BLOCK_LITERAL,o=t.source?Iv(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
|
|
73
73
|
`.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return t.source&&(m+=t.source.length),{value:h,type:a,comment:n.comment,range:[r,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,d=0;for(let h=0;h<s;++h){let[m,g]=o[h];if(g===""||g==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&i(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=m.length),d=h,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+g.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let f="",u="",p=!1;for(let h=0;h<d;++h)f+=o[h][0].slice(c)+`
|
|
74
|
-
`;for(let h=d;h<s;++h){let[m,g]=o[h];l+=m.length+g.length+1;let N=g[g.length-1]==="\r";if(N&&(g=g.slice(0,-1)),g&&m.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-g.length-(N?2:1),"BAD_INDENT",k),m=""}a===
|
|
74
|
+
`;for(let h=d;h<s;++h){let[m,g]=o[h];l+=m.length+g.length+1;let N=g[g.length-1]==="\r";if(N&&(g=g.slice(0,-1)),g&&m.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-g.length-(N?2:1),"BAD_INDENT",k),m=""}a===Eo.Scalar.BLOCK_LITERAL?(f+=u+m.slice(c)+g,u=`
|
|
75
75
|
`):m.length>c||g[0]===" "?(u===" "?u=`
|
|
76
76
|
`:!p&&u===`
|
|
77
77
|
`&&(u=`
|
|
@@ -84,75 +84,75 @@ ${l}
|
|
|
84
84
|
`+o[h][0].slice(c);f[f.length-1]!==`
|
|
85
85
|
`&&(f+=`
|
|
86
86
|
`);break;default:f+=`
|
|
87
|
-
`}let v=r+n.length+t.source.length;return{value:f,type:a,comment:n.comment,range:[r,v,v]}}function
|
|
87
|
+
`}let v=r+n.length+t.source.length;return{value:f,type:a,comment:n.comment,range:[r,v,v]}}function Tv({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let u=1;u<n.length;++u){let p=n[u];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+u)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,d="",f=n.length;for(let u=1;u<t.length;++u){let p=t[u];switch(p.type){case"space":l=!0;case"newline":f+=p.source.length;break;case"comment":i&&!l&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=p.source.length,d=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),f+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",v);let h=p.source;h&&typeof h=="string"&&(f+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:d,length:f}}function Iv(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}hu.resolveBlockScalar=_v});var Ro=y(mu=>{"use strict";var xo=j(),jv=Ot();function $v(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(u,p,v)=>i(r+u,p,v);switch(n){case"scalar":s=xo.Scalar.PLAIN,c=Ov(a,l);break;case"single-quoted-scalar":s=xo.Scalar.QUOTE_SINGLE,c=Hv(a,l);break;case"double-quoted-scalar":s=xo.Scalar.QUOTE_DOUBLE,c=Dv(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let d=r+a.length,f=jv.resolveEnd(o,d,t,i);return{value:c,type:s,comment:f.comment,range:[r,d,f.offset]}}function Ov(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),pu(e)}function Hv(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),pu(e.slice(1,-1)).replace(/''/g,"'")}function pu(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
89
|
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let n=r[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;r=i.exec(e);)r[1]===""?a===`
|
|
90
90
|
`?n+=a:a=`
|
|
91
|
-
`:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function
|
|
91
|
+
`:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function Dv(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
|
|
92
92
|
`))if(n===`
|
|
93
|
-
`){let{fold:a,offset:o}=
|
|
93
|
+
`){let{fold:a,offset:o}=Bv(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=Lv[a];if(o)i+=o;else if(a===`
|
|
94
94
|
`)for(a=e[r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="\r"&&e[r+1]===`
|
|
95
|
-
`)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=
|
|
95
|
+
`)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=Fv(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
|
|
96
96
|
`&&!(o==="\r"&&e[r+2]===`
|
|
97
|
-
`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function
|
|
97
|
+
`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function Bv(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
|
|
98
98
|
`||r==="\r")&&!(r==="\r"&&e[t+2]!==`
|
|
99
99
|
`);)r===`
|
|
100
100
|
`&&(i+=`
|
|
101
|
-
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Lv={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Fv(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}mu.resolveFlowScalar=$v});var wu=y(gu=>{"use strict";var dt=P(),vu=j(),Mv=Po(),Vv=Ro();function qv(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Mv.resolveBlockScalar(e,t,r):Vv.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,f=>r(i,"TAG_RESOLVE_FAILED",f)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[dt.SCALAR]:c?l=Wv(e.schema,n,c,i,r):t.type==="scalar"?l=zv(e,n,t,r):l=e.schema[dt.SCALAR];let d;try{let f=l.resolve(n,u=>r(i??t,"TAG_RESOLVE_FAILED",u),e.options);d=dt.isScalar(f)?f:new vu.Scalar(f)}catch(f){let u=f instanceof Error?f.message:String(f);r(i??t,"TAG_RESOLVE_FAILED",u),d=new vu.Scalar(n)}return d.range=s,d.source=n,a&&(d.type=a),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function Wv(e,t,i,r,n){if(i==="!")return e[dt.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[dt.SCALAR])}function zv({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[dt.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[dt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),d=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",d,!0)}}return o}gu.composeScalar=qv});var Nu=y(yu=>{"use strict";function Jv(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}yu.emptyScalarPosition=Jv});var Su=y(Ao=>{"use strict";var Gv=ui(),Uv=P(),Kv=fu(),bu=wu(),Yv=Ot(),Xv=Nu(),Qv={composeNode:ku,composeEmptyNode:Co};function ku(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,d=!0;switch(t.type){case"alias":l=Zv(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=bu.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Kv.composeCollection(Qv,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(f){let u=f instanceof Error?f.message:String(f);r(t,"RESOURCE_EXHAUSTION",u)}break;default:{let f=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",f),d=!1}}return l??(l=Co(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Uv.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&d&&(l.srcToken=t),l}function Co(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let d={type:"scalar",offset:Xv.emptyScalarPosition(t,i,r),indent:-1,source:""},f=bu.composeScalar(e,d,s,l);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(f.spaceBefore=!0),a&&(f.comment=a,f.range[2]=c),f}function Zv({options:e},{offset:t,source:i,end:r},n){let a=new Gv.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=Yv.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ao.composeEmptyNode=Co;Ao.composeNode=ku});var xu=y(Pu=>{"use strict";var eg=xi(),Eu=Su(),tg=Ot(),ig=_i();function rg(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new eg.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=ig.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Eu.composeNode(l,n,d,o):Eu.composeEmptyNode(l,d.end,r,null,d,o);let f=c.contents.range[2],u=tg.resolveEnd(a,f,!1,o);return u.comment&&(c.comment=u.comment),c.range=[i,f,u.offset],c}Pu.composeDoc=rg});var To=y(Au=>{"use strict";var ng=fr("process"),ag=ma(),og=xi(),Ti=Ai(),Ru=P(),sg=xu(),cg=Ot();function Ii(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function Cu(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var
|
|
106
|
-
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(
|
|
105
|
+
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var _o=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=Ii(i);a?this.warnings.push(new Ti.YAMLWarning(o,r,n)):this.errors.push(new Ti.YAMLParseError(o,r,n))},this.directives=new ag.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Cu(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(Ru.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Ru.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
|
|
107
107
|
${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
|
|
108
|
-
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
109
|
-
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new
|
|
108
|
+
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Cu(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(ng.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=Ii(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=sg.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new Ti.YAMLParseError(Ii(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Ti.YAMLParseError(Ii(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=cg.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
|
|
109
|
+
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new Ti.YAMLParseError(Ii(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new og.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};Au.Composer=_o});var Iu=y(on=>{"use strict";var lg=Po(),ug=Ro(),dg=Ai(),_u=mi();function fg(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new dg.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return ug.resolveFlowScalar(e,t,r);case"block-scalar":return lg.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function hg(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=_u.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
111
|
`),d=s.substring(0,l),f=s.substring(l+1)+`
|
|
112
|
-
`,u=[{type:"block-scalar-header",offset:a,indent:r,source:d}];return
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:r,props:u,source:f}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function
|
|
112
|
+
`,u=[{type:"block-scalar-header",offset:a,indent:r,source:d}];return Tu(u,c)||u.push({type:"newline",offset:-1,indent:r,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:r,props:u,source:f}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function pg(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=_u.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":mg(e,c);break;case'"':Io(e,c,"double-quoted-scalar");break;case"'":Io(e,c,"single-quoted-scalar");break;default:Io(e,c,"scalar")}}function mg(e,t){let i=t.indexOf(`
|
|
114
114
|
`),r=t.substring(0,i),n=t.substring(i+1)+`
|
|
115
|
-
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];
|
|
116
|
-
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function
|
|
117
|
-
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}on.createScalarToken=
|
|
115
|
+
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];Tu(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Tu(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function Io(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}on.createScalarToken=hg;on.resolveAsScalar=fg;on.setScalarValue=pg});var $u=y(ju=>{"use strict";var vg=e=>"type"in e?cn(e):sn(e);function cn(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=cn(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=sn(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=sn(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=sn(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function sn({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=cn(t)),i)for(let a of i)n+=a.source;return r&&(n+=cn(r)),n}ju.stringify=vg});var Bu=y(Du=>{"use strict";var jo=Symbol("break visit"),gg=Symbol("skip children"),Ou=Symbol("remove item");function ft(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Hu(Object.freeze([]),e,t)}ft.BREAK=jo;ft.SKIP=gg;ft.REMOVE=Ou;ft.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};ft.parentCollection=(e,t)=>{let i=ft.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Hu(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Hu(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===jo)return jo;s===Ou&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Du.visit=ft});var ln=y(Q=>{"use strict";var $o=Iu(),wg=$u(),yg=Bu(),Oo="\uFEFF",Ho="",Do="",Bo="",Ng=e=>!!e&&"items"in e,bg=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function kg(e){switch(e){case Oo:return"<BOM>";case Ho:return"<DOC>";case Do:return"<FLOW_END>";case Bo:return"<SCALAR>";default:return JSON.stringify(e)}}function Sg(e){switch(e){case Oo:return"byte-order-mark";case Ho:return"doc-mode";case Do:return"flow-error-end";case Bo:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
118
|
`:case`\r
|
|
119
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Q.createScalarToken
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
121
|
-
\r `),
|
|
119
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Q.createScalarToken=$o.createScalarToken;Q.resolveAsScalar=$o.resolveAsScalar;Q.setScalarValue=$o.setScalarValue;Q.stringify=wg.stringify;Q.visit=yg.visit;Q.BOM=Oo;Q.DOCUMENT=Ho;Q.FLOW_END=Do;Q.SCALAR=Bo;Q.isCollection=Ng;Q.isScalar=bg;Q.prettyToken=kg;Q.tokenType=Sg});var Mo=y(Fu=>{"use strict";var ji=ln();function ve(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var Lu=new Set("0123456789ABCDEFabcdef"),Eg=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),un=new Set(",[]{}"),Pg=new Set(` ,[]{}
|
|
121
|
+
\r `),Lo=e=>!e||Pg.has(e),Fo=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
|
|
122
122
|
`?!0:i==="\r"?this.buffer[t+1]===`
|
|
123
123
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
|
|
124
124
|
`||!n&&!this.atEnd)return t+r+1}return i===`
|
|
125
|
-
`||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&
|
|
126
|
-
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===
|
|
125
|
+
`||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&ve(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
126
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===ji.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,r=t.indexOf("#");for(;r!==-1;){let a=t[r-1];if(a===" "||a===" "){i=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield ji.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let i=this.peek(3);if((i==="---"||i==="...")&&ve(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,i==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ve(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&ve(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Lo),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&ve(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield ji.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Lo),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ve(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
|
|
127
127
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=r.indexOf(`
|
|
128
|
-
`,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>
|
|
128
|
+
`,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>ve(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,r;e:for(let a=this.pos;r=this.buffer[a];++a)switch(r){case" ":i+=1;break;case`
|
|
129
129
|
`:t=a,i=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
130
|
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
131
131
|
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
132
132
|
`;)r=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
-
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield
|
|
133
|
+
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield ji.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(ve(a)||t&&un.has(a))break;i=r}else if(ve(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(r+=1,n=`
|
|
135
135
|
`,a=this.buffer[r+1]):i=r),a==="#"||t&&un.has(a))break;if(n===`
|
|
136
|
-
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&un.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield
|
|
136
|
+
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&un.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield ji.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Lo),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(ve(r)||i&&un.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!ve(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(Eg.has(i))i=this.buffer[++t];else if(i==="%"&&Lu.has(this.buffer[t+1])&&Lu.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
137
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Fu.Lexer=Fo});var qo=y(Mu=>{"use strict";var Vo=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};Mu.LineCounter=Vo});var zo=y(Ju=>{"use strict";var xg=fr("process"),Vu=ln(),Rg=Mo();function Xe(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function qu(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function zu(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function dn(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Ht(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function fn(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function Wu(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Xe(t.start,"explicit-key-ind")&&!Xe(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,zu(t.value)?t.value.end?fn(t.value.end,t.sep):t.value.end=t.sep:fn(t.start,t.sep),delete t.sep)}var Wo=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Rg.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,xg.env.LOG_TOKENS&&console.log("|",Vu.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Vu.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&Wu(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&qu(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{qu(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let i=dn(this.peek(2)),r=Ht(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
140
|
-
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){fn(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(
|
|
140
|
+
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){fn(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Xe(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(zu(i.key)&&!Xe(i.sep,"newline")){let o=Ht(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(Xe(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Ht(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Xe(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!Xe(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){fn(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||Xe(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=dn(r),a=Ht(n);Wu(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
142
|
-
`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=dn(t),r
|
|
143
|
-
`,i)}import{createHash as ih}from"node:crypto";import{promises as he}from"node:fs";import ae from"node:path";import{TextDecoder as rh}from"node:util";var Zf=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),eh=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function th(e){return e.toLowerCase().startsWith(".env")}function ii(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>th(r))?"environment-file":i.some(r=>eh.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>Zf.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}var pr=1024*1024;function la(e,t){let i=ae.relative(e,t);return i===""||!ae.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ae.sep}`)}function nh(e){let t=ae.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ae.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=ii(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function ah(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function oh(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return te(i,r)?A(i,r):A(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function oc(e){let t=await he.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await he.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function sh(e,t){let i=ae.resolve(e),r=ae.resolve(t);if(!la(i,r))throw new Error("Native artifact path is outside its root");let n=[await oc(i)],a=i;for(let o of ae.relative(i,r).split(ae.sep).filter(Boolean)){a=ae.join(a,o);let s=await oc(a);if(!la(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function sc(e){for(let t of e){let i=await he.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!oh(t,i)||await he.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function B(e){let t=nh(e.ref),i=e.maxBytes===null?null:ah(e.maxBytes??pr),r=ae.resolve(e.root,...t.split("/")),n=await sh(e.root,ae.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await he.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await he.realpath(r);if(!la(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await he.open(r,"r");try{let[c,l,d]=await Promise.all([s.stat(),he.lstat(r),he.realpath(r)]);if(await sc(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||d!==o||!hr(a,c)||!hr(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],u=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let w=i===null?p.length:i+1-u,k=await s.read(p,0,Math.min(p.length,w),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,i!==null&&u>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);f.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),he.lstat(r),he.realpath(r)]);if(await sc(n),!h.isFile()||h.isSymbolicLink()||m!==o||!hr(c,v)||!hr(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(f,u),N;try{N=new rh("utf-8",{fatal:!0}).decode(g)}catch(w){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:w})}return{ref:t,size:u,hash:e.includeHash===!1?null:ih("sha256").update(g).digest("hex"),text:N}}finally{await s.close()}}var Is=fr(ji(),1);import Jt from"path";var Jo=fr(ji(),1);import pn from"path";var Oi=64*1024,mn=1024,vn=64,Go=5,Og=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/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/**"],Hg=["**/.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"],Dg=[...Og,...Hg].sort((e,t)=>e.localeCompare(t,"en"));var ie={include:["**/*"],exclude:[...Dg],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Bg(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||pn.posix.isAbsolute(i)||pn.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function ut(e){let t=Bg(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Xu(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Uo(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||pn.posix.isAbsolute(r)||pn.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function $i(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Qu(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function Ko(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>mn)throw new Error(`${t} exceeds ${mn} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>vn)throw new Error(`${t} contains more than ${vn} wildcard tokens`);return e}function Yu(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>Ko(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function zo(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function Lg(e){if(e===void 0)return{...ie,include:[...ie.include],exclude:[...ie.exclude]};let t=$i(e,"native.snapshot");return{include:Yu(t.include,"native.snapshot.include",ie.include),exclude:Yu(t.exclude,"native.snapshot.exclude",ie.exclude),max_files:zo(t.max_files,ie.max_files,"native.snapshot.max_files"),max_total_bytes:zo(t.max_total_bytes,ie.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:zo(t.max_duration_ms,ie.max_duration_ms,"native.snapshot.max_duration_ms")}}function Fg(e){if(e===void 0)return;let t=$i(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=$i(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,d=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 d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:i,fromArtifactRoot:ut(r),toArtifactRoot:ut(n),stage:a,...o?{cleanup:o}:{}}}function Mg(e,t={}){let i=$i(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Go;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Fg(i.pending_root_move);return{artifact_root:ut(r),language:Qu(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Lg(i.snapshot),...s?{pending_root_move:s}:{}}}function Vg(e){let t=$i(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Xu(t.artifact_layout),language:Qu(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function qg(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Wg(e,t,i,r,n){let a=e.schema!==void 0;if(!(a||e.default_workflow!==void 0||e.workflows!==void 0||!n.allowPartialProject&&e.native!==void 0)||n.allowPartialProject&&!a)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=e.workflows??[e.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!t)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:c,ambient_resume:r,...t?{native:t}:{},...i?{classic:i}:{}}}function Hi(e,t={}){let i=(0,Jo.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=qg(n.ambient_resume),o=n.native===void 0?void 0:Mg(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=n.classic===void 0?void 0:Vg(n.classic),c=Wg(n,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function gn(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:ut(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Go,snapshot:{...ie,include:[...ie.include],exclude:[...ie.exclude]}}}}import{createHash as Jg}from"crypto";import{promises as Nn}from"fs";import Qe from"path";import{constants as wn,promises as dt}from"fs";var ve=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Yo(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Zu(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Di(e){return{dev:e.dev,ino:e.ino,birthtime:Yo(e)}}function yn(e,t){let i=Di(e),r=Di(t);return te(i,r)?A(i,r):A(i,r)&&Yo(e)===Yo(t)&&Zu(e)===Zu(t)&&e.size===t.size}async function ft(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await dt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ve("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new ve("too-large",`${r} exceeds ${t} bytes`);let o=await dt.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Di(a)});let s=process.platform==="win32"?wn.O_RDONLY:wn.O_RDONLY|wn.O_NOFOLLOW|wn.O_NONBLOCK,c;try{c=await dt.open(e,s)}catch(l){throw l.code==="ELOOP"?new ve("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,d,f]=await Promise.all([c.stat({bigint:n}),dt.lstat(e,{bigint:n}),dt.realpath(e)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||f!==o||!yn(a,l)||!yn(a,d))throw new ve("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:f,identity:Di(l)}),await i.hooks?.afterOpen?.();let u=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-p,{bytesRead:w}=await c.read(v,0,Math.min(v.length,N),null);if(w===0)break;if(p+=w,p>t)throw new ve("too-large",`${r} exceeds ${t} bytes`);u.push(Buffer.from(v.subarray(0,w)))}await i.hooks?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([c.stat({bigint:n}),dt.lstat(e,{bigint:n}),dt.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!yn(a,h)||!yn(a,m))throw new ve("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:g,identity:Di(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:g}}finally{await c.close()}}function zg(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Xo(e,t){let i=Qe.relative(e,t);return i===""||!Qe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qe.sep}`)}async function ed(e,t){let i=Qe.resolve(e),r=await Nn.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Nn.realpath(i)}async function td(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Qe.join(n,i[a]);let o;try{o=await Nn.lstat(n)}catch(d){if(zg(d))return{exists:!1,kind:"missing"};throw d}let s=Qe.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await Nn.realpath(n);if(!Xo(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Ot(e,t,i){let r=Uo(t,i.label),n=Qe.resolve(e),a=await ed(n,i.label),o=r.split("/"),s=Qe.resolve(n,...o);if(!Xo(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await td(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Ze(e,t,i,r){let n=await Ot(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await ed(n.projectRoot,r.label);return ft(n.target,i,{...r,verify:async(o,s)=>{if(!Xo(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await td(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var Bi=".comet/config.yaml";function Gg(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Qo(e,t={}){return(await bn(e,t)).document}async function Ug(e){try{return(await Ze(e,Bi,Oi,{label:Bi})).bytes}catch(t){if(Gg(t))return null;throw t}}function Kg(e){return e?{exists:!0,sha256:Jg("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function bn(e,t={}){let i=await Ug(e);return{document:i?Hi(i.toString("utf8"),t):null,identity:Kg(i)}}var oE=16*1024;import{existsSync as rd,promises as ht}from"fs";import R from"path";import ew from"os";var kn=".comet/config.yaml",tw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function ts(e){try{return await ht.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function iw(e){try{let t=await ht.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Dt(e,t){let i=R.relative(e,t);return i===""||!R.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${R.sep}`)}async function Ht(e){let t=[],i=e;for(;!await ts(i);){let n=R.dirname(i);if(n===i)break;t.push(R.basename(i)),i=n}let r=await ht.realpath(i);return R.resolve(r,...t.reverse())}async function is(e){try{return(await ht.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Sn(e){let t=R.resolve(e);try{(await ht.stat(t)).isDirectory()||(t=R.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=R.resolve(ew.homedir());for(;;){if(!(t===r&&i!==r)){let o=R.join(t,...kn.split("/")),s=t===i||await iw(o);if(await ts(o)&&s)return t}if(await ts(R.join(t,".git")))return t;let a=R.dirname(t);if(a===t)return i;t=a}}function En(e){return ut(e)}async function rw(e,t){let i=En(t),r=R.resolve(e,...i.split("/")),n=await ht.realpath(e),a=await Ht(r);if(!Dt(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Bt(e,t){let i=En(t),r=await rw(e,i),n=R.join(r,"comet");if(await is(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Ht(r),Ht(n)]);if(!Dt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=R.resolve(e),c=R.join(s,".comet","runtime","native");if(await is(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,d]=await Promise.all([ht.realpath(s),Ht(c)]);if(!Dt(l,d))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:R.join(e,...kn.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:R.join(n,"specs"),changesDir:R.join(n,"changes"),archiveDir:R.join(n,"archive"),runtimeDir:c,changesRuntimeDir:R.join(c,"changes"),locksDir:R.join(c,"locks"),transactionsDir:R.join(c,"transactions")}}function nd(e){if(!tw.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ee(e,t){nd(t);let i=R.join(e.changesRuntimeDir,t);if(!D(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function rs(e,t){nd(t);let i=R.join(e.changesDir,t,"runtime");if(!D(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function Pe(e,t){let i=Ee(e,t);if(rd(i))return i;let r=rs(e,t);return rd(r)?r:i}function xe(e,t){let i=R.resolve(t);if(D(e.runtimeDir,i))return e.runtimeDir;if(D(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function D(e,t){return Dt(R.resolve(e),R.resolve(t))}async function T(e,t){let i=R.resolve(e),r=R.resolve(t);if(!Dt(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await is(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Ht(i),Ht(r)]);if(!Dt(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}function aw(e="docs",t="en"){return gn(e,t)}async function Re(e){let t=(await Qo(e))?.config??null;return t?.native?t:null}async function Fi(e){let t=await Re(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function ad(e){let t=await Sn(e.startPath),i=await Re(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${kn} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let r=e.explicitArtifactRoot?En(e.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??aw(r??"docs"),a=await Bt(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as jy}from"fs";import $y from"path";import{AsyncLocalStorage as ow}from"async_hooks";import{randomUUID as cd}from"crypto";import{promises as se}from"fs";import ld from"os";import G from"path";var od=16*1024,ud=".coordinator",sw=5e3,sd=new ow,Pn=new Map;function cw(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function lw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function dd(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function ns(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return te(i,r)?A(i,r):A(i,r)&&e.size===t.size}function as(e,t){return ns(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function $e(e){let t,i;try{let r=await ft(e,od,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof ve?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${od} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:lw(JSON.parse(t.toString("utf8")),e),identity:dd(i)}}async function uw(e){return(await $e(e))?.owner??null}function fd(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==ld.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=vw(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function dw(e,t){try{await se.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await se.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function os(e,t){let i=await $e(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!as(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await se.mkdir(t,{recursive:!0});let r=G.join(t,`${G.basename(e.file)}.${e.owner.id}.${cd()}.removed`);try{await se.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await $e(r);if(!n||n.owner.id!==e.owner.id||!ns(n.identity,e.identity))throw await dw(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await se.rm(r,{force:!0}),"removed"}function hd(e){return{id:cd(),pid:process.pid,hostname:ld.hostname(),createdAt:new Date().toISOString(),operation:e}}async function pd(e,t){let i;try{i=await se.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await uw(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
|
|
144
|
-
`,"utf8"),await i.sync(),
|
|
145
|
-
${
|
|
142
|
+
`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=dn(t),r=Ht(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=dn(t),r=Ht(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ju.Parser=Wo});var Xu=y(Oi=>{"use strict";var Gu=To(),Cg=xi(),$i=Ai(),Ag=Ca(),_g=P(),Tg=qo(),Uu=zo();function Ku(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Tg.LineCounter||null,prettyErrors:t}}function Ig(e,t={}){let{lineCounter:i,prettyErrors:r}=Ku(t),n=new Uu.Parser(i?.addNewLine),a=new Gu.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach($i.prettifyError(e,i)),s.warnings.forEach($i.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Yu(e,t={}){let{lineCounter:i,prettyErrors:r}=Ku(t),n=new Uu.Parser(i?.addNewLine),a=new Gu.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new $i.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach($i.prettifyError(e,i)),o.warnings.forEach($i.prettifyError(e,i))),o}function jg(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Yu(e,i);if(!n)return null;if(n.warnings.forEach(a=>Ag.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function $g(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return _g.isDocument(e)&&!r?e.toString(i):new Cg.Document(e,r,i).toString(i)}Oi.parse=jg;Oi.parseAllDocuments=Ig;Oi.parseDocument=Yu;Oi.stringify=$g});var Dt=y(x=>{"use strict";var Og=To(),Hg=xi(),Dg=uo(),Jo=Ai(),Bg=ui(),Qe=P(),Lg=Ge(),Fg=j(),Mg=Ke(),Vg=Ye(),qg=ln(),Wg=Mo(),zg=qo(),Jg=zo(),hn=Xu(),Qu=oi();x.Composer=Og.Composer;x.Document=Hg.Document;x.Schema=Dg.Schema;x.YAMLError=Jo.YAMLError;x.YAMLParseError=Jo.YAMLParseError;x.YAMLWarning=Jo.YAMLWarning;x.Alias=Bg.Alias;x.isAlias=Qe.isAlias;x.isCollection=Qe.isCollection;x.isDocument=Qe.isDocument;x.isMap=Qe.isMap;x.isNode=Qe.isNode;x.isPair=Qe.isPair;x.isScalar=Qe.isScalar;x.isSeq=Qe.isSeq;x.Pair=Lg.Pair;x.Scalar=Fg.Scalar;x.YAMLMap=Mg.YAMLMap;x.YAMLSeq=Vg.YAMLSeq;x.CST=qg;x.Lexer=Wg.Lexer;x.LineCounter=zg.LineCounter;x.Parser=Jg.Parser;x.parse=hn.parse;x.parseAllDocuments=hn.parseAllDocuments;x.parseDocument=hn.parseDocument;x.stringify=hn.stringify;x.visit=Qu.visit;x.visitAsync=Qu.visitAsync});import{randomUUID as vb}from"node:crypto";import{promises as W}from"node:fs";import U from"node:path";import{execFileSync as nh}from"child_process";import ri from"path";function ii(e,t){return nh("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function ah(e,t){let i=ri.normalize(e),r=ri.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function F(e){try{let t=ri.resolve(ii(e,["rev-parse","--show-toplevel"])),r=ii(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?ri.resolve(r.slice(9)):t,a=null;try{a=ii(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!ah(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function sc(e){try{ii(e,["rev-parse","--is-inside-work-tree"]);let t=ii(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:ri.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function ot(e){return sc(e).map(t=>t.root)}import{randomUUID as oh}from"crypto";import{promises as z}from"fs";import he from"path";function Ve(e){return e!==0&&e!==0n&&e!=="0"}function ie(e,t){return Ve(e.dev)&&Ve(t.dev)&&Ve(e.ino)&&Ve(t.ino)}function A(e,t){let i=Ve(e.dev)&&Ve(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Ve(e.ino)&&Ve(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}function ua(e,t){let i=he.relative(e,t);return i===""||!he.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${he.sep}`)}function sh(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function la(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ie(i,r)?A(i,r):A(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function cc(e){let t=await z.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await z.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ni(e){for(let t of e){let i=await z.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!sh(t,i)||await z.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function ch(e,t){let i=he.resolve(e),r=he.resolve(t);if(!ua(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await cc(i)],a=he.relative(i,r).split(he.sep).filter(Boolean),o=i;for(let s of a){await ni(n),o=he.join(o,s);try{await z.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await cc(o);if(!ua(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ni(n),n}async function lh(e){let t;try{t=await z.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function uh(e,t,i={}){let r=he.dirname(e),n=i.containedRoot?await ch(i.containedRoot,r):null;n||await z.mkdir(r,{recursive:!0});let a=he.join(r,`.${he.basename(e)}.${oh()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await z.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([z.lstat(a),z.realpath(a)]);if(await ni(n),!c.isFile()||c.isSymbolicLink()||!la(s,c)||!ua(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!la(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await ni(n);let c=await z.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!la(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await z.link(a,e),await z.unlink(a)):await z.rename(a,e),await lh(r)}catch(c){if(await o?.close(),!n)await z.rm(a,{force:!0});else try{await ni(n),await z.rm(a,{force:!0})}catch{}throw c}}async function K(e,t,i={}){await uh(e,t,i)}async function Y(e,t,i={}){await K(e,JSON.stringify(t,null,2)+`
|
|
143
|
+
`,i)}import{createHash as ph}from"node:crypto";import{promises as pe}from"node:fs";import ce from"node:path";import{TextDecoder as mh}from"node:util";var dh=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),fh=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function hh(e){return e.toLowerCase().startsWith(".env")}function ai(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>hh(r))?"environment-file":i.some(r=>fh.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>dh.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}var pr=1024*1024;function da(e,t){let i=ce.relative(e,t);return i===""||!ce.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ce.sep}`)}function vh(e){let t=ce.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ce.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=ai(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function gh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function wh(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ie(i,r)?A(i,r):A(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function lc(e){let t=await pe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await pe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function yh(e,t){let i=ce.resolve(e),r=ce.resolve(t);if(!da(i,r))throw new Error("Native artifact path is outside its root");let n=[await lc(i)],a=i;for(let o of ce.relative(i,r).split(ce.sep).filter(Boolean)){a=ce.join(a,o);let s=await lc(a);if(!da(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function uc(e){for(let t of e){let i=await pe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!wh(t,i)||await pe.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function I(e){let t=vh(e.ref),i=e.maxBytes===null?null:gh(e.maxBytes??pr),r=ce.resolve(e.root,...t.split("/")),n=await yh(e.root,ce.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await pe.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await pe.realpath(r);if(!da(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await pe.open(r,"r");try{let[c,l,d]=await Promise.all([s.stat(),pe.lstat(r),pe.realpath(r)]);if(await uc(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||d!==o||!hr(a,c)||!hr(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],u=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let w=i===null?p.length:i+1-u,k=await s.read(p,0,Math.min(p.length,w),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,i!==null&&u>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);f.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),pe.lstat(r),pe.realpath(r)]);if(await uc(n),!h.isFile()||h.isSymbolicLink()||m!==o||!hr(c,v)||!hr(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(f,u),N;try{N=new mh("utf-8",{fatal:!0}).decode(g)}catch(w){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:w})}return{ref:t,size:u,hash:e.includeHash===!1?null:ph("sha256").update(g).digest("hex"),text:N}}finally{await s.close()}}var js=ti(Dt(),1);import Kt from"path";var Uo=ti(Dt(),1);import pn from"path";var Hi=64*1024,mn=1024,vn=64,Ko=5,Gg=[".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/**"],Ug=["**/.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"],Kg=[...Gg,...Ug].sort((e,t)=>e.localeCompare(t,"en"));var re={include:["**/*"],exclude:[...Kg],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Yg(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||pn.posix.isAbsolute(i)||pn.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function ht(e){let t=Yg(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ed(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function gn(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||pn.posix.isAbsolute(r)||pn.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Bt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function td(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function Yo(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>mn)throw new Error(`${t} exceeds ${mn} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>vn)throw new Error(`${t} contains more than ${vn} wildcard tokens`);return e}function Zu(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>Yo(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Go(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function Xg(e){if(e===void 0)return{...re,include:[...re.include],exclude:[...re.exclude]};let t=Bt(e,"native.snapshot");return{include:Zu(t.include,"native.snapshot.include",re.include),exclude:Zu(t.exclude,"native.snapshot.exclude",re.exclude),max_files:Go(t.max_files,re.max_files,"native.snapshot.max_files"),max_total_bytes:Go(t.max_total_bytes,re.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Go(t.max_duration_ms,re.max_duration_ms,"native.snapshot.max_duration_ms")}}function Qg(e){if(e===void 0)return;let t=Bt(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Bt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,d=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 d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:i,fromArtifactRoot:ht(r),toArtifactRoot:ht(n),stage:a,...o?{cleanup:o}:{}}}function Zg(e,t={}){let i=Bt(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Ko;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Qg(i.pending_root_move);return{artifact_root:ht(r),language:td(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Xg(i.snapshot),...s?{pending_root_move:s}:{}}}function ew(e){let t=Bt(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:ed(t.artifact_layout),language:td(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function tw(e){let i=Bt(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>gn(r,`hook.allow_paths[${n}]`)))]}}function iw(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function rw(e,t,i,r,n,a){let o=e.schema!==void 0;if(!(o||e.default_workflow!==void 0||e.workflows!==void 0||!a.allowPartialProject&&e.native!==void 0)||a.allowPartialProject&&!o)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let c=e.workflows??[e.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(l.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:l,ambient_resume:n,...t?{hook:t}:{},...i?{native:i}:{},...r?{classic:r}:{}}}function Di(e,t={}){let i=(0,Uo.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=iw(n.ambient_resume),o=n.hook===void 0?void 0:tw(n.hook),s=n.native===void 0?void 0:Zg(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:ew(n.classic),l=rw(n,o,s,c,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}function wn(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:ht(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Ko,snapshot:{...re,include:[...re.include],exclude:[...re.exclude]}}}}import{createHash as aw}from"crypto";import{promises as bn}from"fs";import Ze from"path";import{constants as yn,promises as pt}from"fs";var ge=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Xo(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function id(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Bi(e){return{dev:e.dev,ino:e.ino,birthtime:Xo(e)}}function Nn(e,t){let i=Bi(e),r=Bi(t);return ie(i,r)?A(i,r):A(i,r)&&Xo(e)===Xo(t)&&id(e)===id(t)&&e.size===t.size}async function mt(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await pt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ge("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new ge("too-large",`${r} exceeds ${t} bytes`);let o=await pt.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Bi(a)});let s=process.platform==="win32"?yn.O_RDONLY:yn.O_RDONLY|yn.O_NOFOLLOW|yn.O_NONBLOCK,c;try{c=await pt.open(e,s)}catch(l){throw l.code==="ELOOP"?new ge("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,d,f]=await Promise.all([c.stat({bigint:n}),pt.lstat(e,{bigint:n}),pt.realpath(e)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||f!==o||!Nn(a,l)||!Nn(a,d))throw new ge("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:f,identity:Bi(l)}),await i.hooks?.afterOpen?.();let u=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-p,{bytesRead:w}=await c.read(v,0,Math.min(v.length,N),null);if(w===0)break;if(p+=w,p>t)throw new ge("too-large",`${r} exceeds ${t} bytes`);u.push(Buffer.from(v.subarray(0,w)))}await i.hooks?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([c.stat({bigint:n}),pt.lstat(e,{bigint:n}),pt.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!Nn(a,h)||!Nn(a,m))throw new ge("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:g,identity:Bi(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:g}}finally{await c.close()}}function nw(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Qo(e,t){let i=Ze.relative(e,t);return i===""||!Ze.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ze.sep}`)}async function rd(e,t){let i=Ze.resolve(e),r=await bn.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return bn.realpath(i)}async function nd(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Ze.join(n,i[a]);let o;try{o=await bn.lstat(n)}catch(d){if(nw(d))return{exists:!1,kind:"missing"};throw d}let s=Ze.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await bn.realpath(n);if(!Qo(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Lt(e,t,i){let r=gn(t,i.label),n=Ze.resolve(e),a=await rd(n,i.label),o=r.split("/"),s=Ze.resolve(n,...o);if(!Qo(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await nd(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function et(e,t,i,r){let n=await Lt(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await rd(n.projectRoot,r.label);return mt(n.target,i,{...r,verify:async(o,s)=>{if(!Qo(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await nd(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var Li=".comet/config.yaml";function ow(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function kn(e,t={}){return(await Sn(e,t)).document}async function sw(e){try{return(await et(e,Li,Hi,{label:Li})).bytes}catch(t){if(ow(t))return null;throw t}}function cw(e){return e?{exists:!0,sha256:aw("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Sn(e,t={}){let i=await sw(e);return{document:i?Di(i.toString("utf8"),t):null,identity:cw(i)}}async function Zo(e){return(await kn(e))?.config??null}var _E=16*1024;import{existsSync as od,promises as vt}from"fs";import R from"path";import hw from"os";var En=".comet/config.yaml",pw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function is(e){try{return await vt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function mw(e){try{let t=await vt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Mt(e,t){let i=R.relative(e,t);return i===""||!R.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${R.sep}`)}async function Ft(e){let t=[],i=e;for(;!await is(i);){let n=R.dirname(i);if(n===i)break;t.push(R.basename(i)),i=n}let r=await vt.realpath(i);return R.resolve(r,...t.reverse())}async function rs(e){try{return(await vt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Pn(e){let t=R.resolve(e);try{(await vt.stat(t)).isDirectory()||(t=R.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=R.resolve(hw.homedir());for(;;){if(!(t===r&&i!==r)){let o=R.join(t,...En.split("/")),s=t===i||await mw(o);if(await is(o)&&s)return t}if(await is(R.join(t,".git")))return t;let a=R.dirname(t);if(a===t)return i;t=a}}function xn(e){return ht(e)}async function vw(e,t){let i=xn(t),r=R.resolve(e,...i.split("/")),n=await vt.realpath(e),a=await Ft(r);if(!Mt(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function tt(e,t){let i=xn(t),r=await vw(e,i),n=R.join(r,"comet");if(await rs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Ft(r),Ft(n)]);if(!Mt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=R.resolve(e),c=R.join(s,".comet","runtime","native");if(await rs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,d]=await Promise.all([vt.realpath(s),Ft(c)]);if(!Mt(l,d))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:R.join(e,...En.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:R.join(n,"specs"),changesDir:R.join(n,"changes"),archiveDir:R.join(n,"archive"),runtimeDir:c,changesRuntimeDir:R.join(c,"changes"),locksDir:R.join(c,"locks"),transactionsDir:R.join(c,"transactions")}}function sd(e){if(!pw.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Pe(e,t){sd(t);let i=R.join(e.changesRuntimeDir,t);if(!B(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function ns(e,t){sd(t);let i=R.join(e.changesDir,t,"runtime");if(!B(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function xe(e,t){let i=Pe(e,t);if(od(i))return i;let r=ns(e,t);return od(r)?r:i}function Re(e,t){let i=R.resolve(t);if(B(e.runtimeDir,i))return e.runtimeDir;if(B(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function B(e,t){return Mt(R.resolve(e),R.resolve(t))}async function T(e,t){let i=R.resolve(e),r=R.resolve(t);if(!Mt(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await rs(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Ft(i),Ft(r)]);if(!Mt(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}function ww(e="docs",t="en"){return wn(e,t)}async function we(e){let t=(await kn(e))?.config??null;return t?.native?t:null}async function Mi(e){let t=await we(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function cd(e){let t=await Pn(e.startPath),i=await we(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${En} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let r=e.explicitArtifactRoot?xn(e.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??ww(r??"docs"),a=await tt(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as Uy}from"fs";import Ky from"path";import{AsyncLocalStorage as yw}from"async_hooks";import{randomUUID as dd}from"crypto";import{promises as ue}from"fs";import fd from"os";import G from"path";var ld=16*1024,hd=".coordinator",Nw=5e3,ud=new yw,Rn=new Map;function bw(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function kw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function pd(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function as(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return ie(i,r)?A(i,r):A(i,r)&&e.size===t.size}function os(e,t){return as(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function $e(e){let t,i;try{let r=await mt(e,ld,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof ge?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${ld} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:kw(JSON.parse(t.toString("utf8")),e),identity:pd(i)}}async function Sw(e){return(await $e(e))?.owner??null}function md(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==fd.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Aw(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Ew(e,t){try{await ue.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await ue.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function ss(e,t){let i=await $e(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!os(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ue.mkdir(t,{recursive:!0});let r=G.join(t,`${G.basename(e.file)}.${e.owner.id}.${dd()}.removed`);try{await ue.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await $e(r);if(!n||n.owner.id!==e.owner.id||!as(n.identity,e.identity))throw await Ew(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ue.rm(r,{force:!0}),"removed"}function vd(e){return{id:dd(),pid:process.pid,hostname:fd.hostname(),createdAt:new Date().toISOString(),operation:e}}async function gd(e,t){let i;try{i=await ue.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await Sw(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
|
|
144
|
+
`,"utf8"),await i.sync(),pd(await i.stat({bigint:!0}))}finally{await i.close()}}async function Pw(e,t){let i=await T(e.runtimeDir,e.locksDir);await ue.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,G.join(i,hd));await ue.mkdir(r,{recursive:!0});let n=vd(t),a=G.join(r,`.${n.id}.tmp`),o=G.join(r,`${n.id}.claim`);try{let s=await gd(a,n);await ue.rename(a,o);let c=await $e(o);if(!c||!as(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await ue.rm(a,{force:!0})}}async function xw(e){let t=G.dirname(e.file),i=!1,r=G.basename(e.file);for(let n of await ue.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=G.join(t,n.name);if(G.resolve(a)!==G.resolve(e.file))try{let o=await $e(a),s=md(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ss(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function wd(e){let t=await $e(e.file);if(t){if(t.owner.id!==e.owner.id||!os(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await ss(t,G.dirname(e.file))}}async function Rw(e,t){let i=Date.now()+Nw;for(;;){let r=await Pw(e,t);if(!await xw(r))return r;if(await wd(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function Cw(e){let t=Rn.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return Rn.set(e,n),await t,()=>{i(),Rn.get(e)===n&&Rn.delete(e)}}async function yd(e,t,i){let r=G.resolve(e.locksDir),n=ud.getStore();if(n?.has(r))return i();let a=await Cw(r);try{let o=await Rw(e,t),s=new Map(n??[]);return s.set(r,o),await ud.run(s,async()=>{try{return await i()}finally{await wd(o)}})}finally{a()}}async function Cn(e,t,i){return yd(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await ue.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,G.join(r,bw(t))),a=vd(i),o=await gd(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function An(e){await $e(e.file)&&await yd({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${G.basename(e.file)}`,async()=>{let t=await $e(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!os(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=G.join(e.locksDir,hd);await ss(t,i)})}function Aw(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Nd(e){return md(await $e(e))}import ks from"node:path";import sy from"node:path";import kd from"node:path";import{createHash as _w}from"crypto";function ye(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function Tw(e,t){t.has(e)&&ye("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||ye("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&ye("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ye("symbol properties are not supported"),`[${e.map(r=>cs(r,t)).join(",")}]`}finally{t.delete(e)}}function Iw(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&ye("only plain objects are supported"),t.has(e)&&ye("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ye("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&ye("accessor properties are not supported"),`${JSON.stringify(o)}:${cs(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function cs(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||ye("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?Tw(e,t):Iw(e,t);case"bigint":case"function":case"symbol":case"undefined":return ye(`${typeof e} values are not supported`)}return ye("unsupported value type")}function ls(e){return cs(e,new Set)}function Z(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return _w("sha256").update(`${e}
|
|
145
|
+
${ls(t)}`).digest("hex")}var jw="comet.native.acceptance.v1";var lP=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Wi=Object.freeze({maxCriteria:1024});function ds(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function us(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function bd(e){return e.includes("-->")||e.includes("--!>")}function*Vi(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
146
146
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
147
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=
|
|
148
|
-
`),[],r)),"Brief",r)}function
|
|
149
|
-
`),o.context,r)),o=null}};for(let{line:c,body:l}of Mi(e)){let d=l?us(c):null,f=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(f){for(s();a.at(-1)&&a.at(-1).level>=d.level;)a.pop();let u=Vi(f[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:d.level,title:u,body:[],context:a.map(p=>p.text)}}else if(d){for(o!==null&&d.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=d.level;)a.pop();a.push(d)}else o!==null&&l&&o.body.push(c)}return s(),fs(n,"Specification",r)}function ms(e,t="spec.md",i=qi.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(ds("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(d=>/^(?:non-?goals?|非目标)$/iu.test(d.text.trim()));for(let{line:d,body:f}of Mi(e)){let u=f?us(d):null;if(u){for(c(),o!==null&&u.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u),/^Scenario\s*:/iu.test(u.text)&&(o=u.level);continue}let p=d.trim();if(!f||o!==null||l()){c();continue}if(p.length===0||ls(d,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(d);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),fs(n,"Specification mandatory requirements",r)}var kw=/^A[1-9]\d*$/u;function Nd(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||yd.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||yd.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Sw(e,t){return e.localeCompare(t,"en")}function Cn(e){let t=Nd(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>Sw(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=hs(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=Nd(a.source,`Native spec source for ${a.capability}`);r.push(...ps(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...ms(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=Vi(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function bd(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!kw.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function kd(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var Tn=fr(ji(),1);import{promises as Ew}from"node:fs";var Lt="comet.native.v4",Wi="comet.native.local-execution.v4";function vs(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Pw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Rw=/^A[1-9][0-9]*$/u,Cw=new Set(["schema","name","language","phase","status","state_version","brief","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),_n=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Z(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ee(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function z(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function ws(e,t){return e===null?null:z(e,t)}function Ft(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function _(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function Aw(e,t){return e===null?null:_(e,t,Number.MIN_SAFE_INTEGER)}function V(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Ce(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function In(e,t){return Ce(e,t,(i,r)=>z(i,`${t}[${r}]`))}function pt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Mt(e,t){let i=z(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function ys(e,t,i=!1){let r=z(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function we(e,t){let i=Z(e,t);return ee(i,new Set(["text","truncated"]),t),{text:z(i.text,`${t}.text`,{empty:!0}),truncated:Ft(i.truncated,`${t}.truncated`)}}function _w(e,t){let i=`Native spec_changes[${t}]`,r=Z(e,i);ee(r,new Set(["capability","operation","source"]),i);let n=z(r.capability,`${i}.capability`);if(!xw.test(n))throw new Error(`${i}.capability is invalid`);let a=V(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:ys(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function Tw(e){let t="Native workspace",i=Z(e,t);ee(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=V(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=ws(i.change_branch,`${t}.change_branch`),a=ws(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:V(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function Iw(e){let t="Native loop",i=Z(e,t);ee(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=In(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return pt(r,`${t}.previous_unresolved_ids`),{stage:V(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:_(i.goal_cycle,`${t}.goal_cycle`,1),iteration:_(i.iteration,`${t}.iteration`),attempt:_(i.attempt,`${t}.attempt`),retry_epoch:_(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:_(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:_(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:_(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:ws(i.next_action,`${t}.next_action`)}}function jw(e,t){let i=`Native acceptance[${t}]`,r=Z(e,i);ee(r,new Set(["id","source","text","result","reason"]),i);let n=z(r.id,`${i}.id`);if(!Rw.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:ys(r.source,`${i}.source`),text:z(r.text,`${i}.text`),result:V(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:we(r.reason,`${i}.reason`)}}function $w(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Z(e,i);return ee(r,new Set(["name","result","note"]),i),{name:we(r.name,`${i}.name`),result:V(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:we(r.note,`${i}.note`)}}function Ow(e){let t="Native builder_handoff",i=Z(e,t);ee(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),t);let r=In(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return pt(r,`${t}.addressed_acceptance_ids`),{candidate_id:z(i.candidate_id,`${t}.candidate_id`),identity_provider:z(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:z(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:_(i.iteration,`${t}.iteration`,1),summary:we(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:Ce(i.checks,`${t}.checks`,$w),checks_truncated:Ft(i.checks_truncated,`${t}.checks_truncated`),known_limits:Ce(i.known_limits,`${t}.known_limits`,(n,a)=>we(n,`${t}.known_limits[${a}]`)),known_limits_truncated:Ft(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Mt(i.submitted_at,`${t}.submitted_at`)}}function Hw(e,t){let i=`Native blockers[${t}]`,r=Z(e,i);ee(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=In(r.acceptance_ids,`${i}.acceptance_ids`);return pt(n,`${i}.acceptance_ids`),{owner:V(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:we(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:V(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function Dw(e,t){let i=`Native verification.checks[${t}]`,r=Z(e,i);return ee(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:z(r.id,`${i}.id`),name:we(r.name,`${i}.name`),argv_display:Ce(r.argv_display,`${i}.argv_display`,(n,a)=>we(n,`${i}.argv_display[${a}]`)),argv_truncated:Ft(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:ys(r.cwd_ref,`${i}.cwd_ref`,!0),status:V(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:Aw(r.exit_code,`${i}.exit_code`),duration_ms:_(r.duration_ms,`${i}.duration_ms`)}}function Bw(e){let t="Native verification",i=Z(e,t);ee(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=Ce(i.checks,`${t}.checks`,Dw);pt(r.map(a=>a.id),`${t}.checks IDs`);let n=z(i.identity_provider,`${t}.identity_provider`);return{candidate_id:z(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:z(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:_(i.iteration,`${t}.iteration`,1),attempt:_(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":V(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:V(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:we(i.summary,`${t}.summary`),risks:Ce(i.risks,`${t}.risks`,(a,o)=>we(a,`${t}.risks[${o}]`)),risks_truncated:Ft(i.risks_truncated,`${t}.risks_truncated`),completed_at:Mt(i.completed_at,`${t}.completed_at`)}}function Sd(e,t){let i=`Native history[${t}]`,r=Z(e,i);ee(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=In(r.unresolved_ids,`${i}.unresolved_ids`);return pt(n,`${i}.unresolved_ids`),{goal_cycle:_(r.goal_cycle,`${i}.goal_cycle`,1),iteration:_(r.iteration,`${i}.iteration`),attempt:_(r.attempt,`${i}.attempt`),outcome:V(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:we(r.summary,`${i}.summary`),completed_at:Mt(r.completed_at,`${i}.completed_at`)}}function Lw(e){let t="Native history_overflow.outcome_counts",i=Z(e,t),r=["pass","fail","blocked","execution-error","recovery"];return ee(i,new Set(r),t),{pass:_(i.pass,`${t}.pass`),fail:_(i.fail,`${t}.fail`),blocked:_(i.blocked,`${t}.blocked`),"execution-error":_(i["execution-error"],`${t}.execution-error`),recovery:_(i.recovery,`${t}.recovery`)}}function Fw(e){let t="Native history_overflow",i=Z(e,t);ee(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=_(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Mt(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Mt(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=Lw(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function Mw(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff&&!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Vw(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function le(e){let t=Z(e,"Native portable state");if(ee(t,Cw,"Native portable state"),t.schema!==Lt)throw new Error(`Native portable state schema must be ${Lt}`);let i=z(t.name,"Native state name");if(!Pw.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=Ce(t.spec_changes,"Native spec_changes",_w);pt(r.map(s=>s.capability),"Native spec change capabilities");let n=Ce(t.acceptance,"Native acceptance",jw);pt(n.map(s=>s.id),"Native acceptance IDs");let a=Ce(t.history,"Native history",Sd);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Lt,name:i,language:V(t.language,["en","zh-CN"],"Native state language"),phase:V(t.phase,["shape","build","verify","archive"],"Native state phase"),status:V(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:_(t.state_version,"Native state_version",1),brief:"brief.md",spec_changes:r,workspace:Tw(t.workspace),loop:Iw(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Ow(t.builder_handoff),blockers:Ce(t.blockers,"Native blockers",Hw),verification:t.verification===null?null:Bw(t.verification),history:a,history_overflow:Fw(t.history_overflow),verification_result:V(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:V(t.verification_report,["verification.md"],"Native verification_report"),archived:Ft(t.archived,"Native archived"),created_at:Mt(t.created_at,"Native created_at")};return Mw(o),Vw(o),o}function Vt(e,t){let i=le(e),r=Sd(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return le({...i,history:n,history_overflow:a})}function qw(e,t){let i=(0,Tn.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function ue(e){let t=await Ew.readFile(e,"utf8");return le(qw(t,"Native portable state"))}async function jn(e,t,i={}){let r=le(t);await K(e,(0,Tn.stringify)(r),i)}var An=new Map;async function Ww(e,t){let i=An.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);An.set(e,a),await i;try{return await t()}finally{r(),An.get(e)===a&&An.delete(e)}}async function mt(e){return Ww(e.file,async()=>{let t=_(e.expectedStateVersion,"Native expected state version",1),i=le(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await ue(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new _n(t,r.state_version);return await jn(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await ue(e.file);if(n.state_version!==t)throw new _n(t,n.state_version)}}),i})}function zw(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function et(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(zw(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var Oe="comet.native.v3",Ae="comet.native.v2",_e="comet.native.v1";var $n="comet.native.portable-migration.v1",Gw=new Set(["schema","id","change","fromSchema","status","createdAt"]),Uw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Kw=/^[a-z0-9][a-z0-9-]{7,127}$/u,Yw=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Xw=new Set([_e,Ae,Oe]);function Qw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Zw(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function ey(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function ty(e){return e.schema===_e?zi(e):e.schema===Ae?Ji(e):Gi(e)}function iy(e){return Jw.posix.normalize(e.replaceAll("\\","/"))}function ry(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:iy(t.source)})}function ny(e){return e==="shape"?"shape":"build"}function ay(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function oy(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function Ed(e){let t=ty(e.state);bd(e.acceptance);let i=ny(t.phase),r=i==="shape"?0:1,n=Zw(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return le({schema:Lt,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:ry(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:ay(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:et(oy(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:vs(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Ns(e){let t=Qw(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!Gw.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==$n)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!Kw.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!Uw.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!Xw.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!Yw.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:$n,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:ey(t.createdAt,"Native portable migration transaction createdAt")}}function Pd(e){switch(Ns(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var On="comet.native.archive-transaction.v4",xd="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",sy=new RegExp(`^portable-archive-(${xd})\\.json$`,"u"),cy=new RegExp(`^portable-migration-(${xd})\\.json$`,"u"),ly=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,uy=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dy=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),fy=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),hy=new Set(["capability","operation","source","content"]),Rd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Cd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ad(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function py(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Cd(e,i);if(Ad(r,hy,i),typeof r.capability!="string"||!Rd.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function my(e){let t=Cd(e,"Native portable Archive transaction");if(Ad(t,fy,"Native portable Archive transaction"),t.schema!==On)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!ly.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Rd.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!uy.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!dy.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(py);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:On,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function Hn(e){let t=sy.exec(e);if(t)return{kind:"archive",change:t[1]};let i=cy.exec(e);return i?{kind:"migration",change:i[1]}:null}function vt(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Hn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return bs.join(e.transactionsDir,i)}async function ks(e,t){let i=Hn(t);if(!i)return null;let r=await B({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=bs.join(e.transactionsDir,t);if(i.kind==="archive"){let s=my(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=Ns(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function qt(e,t){let i=vt(e,t);try{return await ks(e,bs.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function _d(e){return e.kind==="archive"||e.journal.status!=="committed"}import He from"path";import{TextDecoder as Sy}from"util";import{createHash as vy}from"node:crypto";import{constants as Dn,promises as ye}from"node:fs";import Ne from"node:path";function Ln(e,t){let i=Ne.relative(e,t);return i===""||!Ne.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ne.sep}`)}function gy(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function wy(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function yy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Bn(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Ss(e,t){let i=await ye.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await ye.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Ny(e,t,i){let r=Ne.resolve(e),n=Ne.resolve(t);if(!Ln(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Ss(r,i)],o=r;for(let s of Ne.relative(r,n).split(Ne.sep).filter(Boolean)){await gt(a,i),o=Ne.join(o,s);let c=await Ss(o,i);if(!Ln(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await gt(a,i),a}async function gt(e,t){for(let i of e){let r=await ye.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!wy(i,r)||await ye.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function by(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Wt(e){let t=gy(e.maxBytes),i=Ne.resolve(e.file),r=await Ny(e.root,Ne.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(d=>Ss(Ne.resolve(d),e.label)));await e.hooks?.afterParentChainCaptured?.(),await gt(r,e.label);let a=await ye.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=yy(a),s=await ye.realpath(i);if(!Ln(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(d=>Ln(d.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Dn.O_RDONLY:Dn.O_RDONLY|Dn.O_NOFOLLOW|Dn.O_NONBLOCK,l=await ye.open(i,c);try{let d=await l.stat();await e.hooks?.afterOpen?.();let[f,u]=await Promise.all([ye.lstat(i),ye.realpath(i)]);if(await gt(r,e.label),await gt(n,e.label),!d.isFile()||!f.isFile()||f.isSymbolicLink()||u!==s||!Bn(o,d)||!Bn(o,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await by(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),ye.lstat(i),ye.realpath(i)]);if(await gt(r,e.label),await gt(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!Bn(o,v)||!Bn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:vy("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Ey=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Py=new Set(["id","type","source","target","staged","backup"]),xy=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Ry=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var jd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Cy=256*1024,SP=1024*1024,EP=16*1024;var PP=64*1024*1024;var Ay=new Sy("utf-8",{fatal:!0});function Mn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Vn(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function $d(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Es(e,t){if(typeof e!="string"||e.length===0||He.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Fn(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Td(e,t){if(Es(e,t),e.includes("\\")||e!==He.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function _y(e,t){let i=Mn(e,`transaction operations[${t}]`);if(Vn(i,Py,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Es(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Es(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function Od(e){let t=Mn(e,"Native Archive transaction journal");if(Vn(t,xy,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!jd.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!$d(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Fn(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=Mn(s,`Archive transaction operations[${c}]`);if(Vn(l,Ry,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Td(l.target,`Archive transaction operation ${l.id} target`);for(let d of["source","staged","backup"])l[d]!==void 0&&Td(l[d],`Archive transaction operation ${l.id} ${d}`);if(l.expectedTargetHash!==null&&Fn(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Fn(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Fn(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function Ty(e){let t=Mn(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Od(t);if(Vn(t,Ey,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!jd.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!He.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!He.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!$d(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(_y),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function Iy(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return He.join(e.transactionsDir,t)}function Hd(e,t){let i=Iy(e,t);return{directory:i,journal:He.join(i,"transaction.json"),events:He.join(i,"events.jsonl"),staged:He.join(i,"staged"),backups:He.join(i,"backups")}}async function xs(e,t){let i=Hd(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}async function Rs(e,t,i={}){let r=await xs(e,t),n=await Wt({root:e.runtimeDir,file:r.journal,maxBytes:Cy,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Ay.decode(n.bytes)),o=Ty(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Oy(e,t,i){let r;try{r=await jy.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Rs(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Hn(n.name))try{let a=await ks(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(_d(a))return!0}catch{return!0}return!1}async function Hy(e,t){let i=Date.now()+5e3,r=$y.join(e.locksDir,"root-move.lock");for(;;)try{return await xn(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await gd(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function J(e,t,i,r){let n=await Hy(e,t);try{if(await Fi(e.projectRoot),await Oy(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Rn(n)}}import{createHash as Dy}from"crypto";function de(e){return Dy("sha256").update(e).digest("hex")}var JP={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var GP=8*1024*1024;var UP=64*1024,KP=64*1024;var YP={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},XP={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var QP=(1n<<256n)-1n;var Wy=fr(ji(),1);var px=4*1024*1024;var cR=256*1024;var bR={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 zt from"node:path";var Ui=/^[a-f0-9]{64}$/u,Bd=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Gy=16*1024,DR=process.platform;function Uy(e,t){let i=zt.relative(e,t);return zt.isAbsolute(i)||i===".."||i.startsWith(`..${zt.sep}`)?null:i.replaceAll("\\","/")||"."}function Ld(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Fd(e,t){if(e.length===0||Ld(e)||e.includes("\\")||zt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=zt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Ky(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function Cs(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Ld(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Yy(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Cs(e.changeBranch,"Native workspace change branch"),Cs(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function Xy(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Bd.test(t.baseCommit)||typeof t.targetCommit!="string"||!Bd.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Cs(t.targetBranch,"Native workspace Git target branch")}function Qy(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Ui.test(String(t.projectRootId))||!Ui.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");Ky(t.capturedAt),Fd(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Ui.test(String(t.projectRootPathId))||a&&!Ui.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ui.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Xy(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(Yy(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function Zy(e,t){return zt.join(Pe(e,t),"workspace.json")}function eN(e,t){let i=Zy(e,t),r=xe(e,i),n=Uy(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Fd(n,"Native workspace file ref")}}async function tN(e,t){try{let i=eN(e,t),r=await B({root:i.root,ref:i.ref,maxBytes:Gy});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ki(e,t){let i=await tN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Qy(i),i)}var Vd=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],nN=new Set(Vd),qd=new Set([...Vd,"minimum_runtime_version","revision"]),aN=new Set([...qd,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),oN=new Set(["capability","operation","source","base_hash"]),sN=new Set(["shape","build","verify","archive"]),cN=new Set(["implicit","confirmed"]),lN=new Set(["pending","pass","fail"]),wt="comet-state.yaml",_s=/^[a-f0-9]{64}$/u,Wd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uN=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Ts=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Gt=class extends Error{constructor(i,r){super(i!==Oe||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},qn=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Yi=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Wn=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},sC=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
150
|
-
`);function Qi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function zd(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function js(e){if(!Wd.test(e))throw new Error(`Invalid Native change name: ${e}`)}function dN(e){if(!Wd.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Jd(e,t){if(e.length===0||Jt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function fN(e,t){let i=Qi(e,`spec_changes[${t}]`);if(zd(i,oN,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(dN(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&Jd(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!_s.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!_s.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function hN(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function $s(e,t){if(zd(e,t,wt),typeof e.name!="string")throw new Error("Native change name is required");if(js(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!sN.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!cN.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(fN),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!lN.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&Jd(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!hN(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function zi(e){let t=Qi(e,wt);if(t.schema!==_e)throw new Error(`Expected ${_e}`);return{schema:_e,...$s(t,nN)}}function Xi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function As(e,t,i){if(e===null)return null;let r=typeof e=="string"?uN.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function pN(e){if(e==null)return null;if(typeof e!="string"||!_s.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function mN(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Ji(e){let t=Qi(e,wt);if(t.schema!==Ae)throw new Error(`Expected ${Ae}`);if(Xi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ae} minimum_runtime_version must be 2`);return{schema:Ae,minimum_runtime_version:2,revision:Xi(t.revision,"Native v2 revision"),...$s(t,qd)}}function Gi(e){let t=Qi(e,wt);if(t.schema!==Oe){if(t.schema===_e||t.schema===Ae){let o=t.schema===_e?zi(t):Ji(t);throw new Ts(o.name,o.schema)}throw new Gt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Xi(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Gt(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Xi(t.revision,"Native revision"),n=$s(t,aN),a=pN(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Oe,minimum_runtime_version:3,revision:r,verification_protocol:mN(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:As(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:As(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:As(t.partial_allowance,"Native partial_allowance","allowances")}}function vN(e){let t=Qi(e,wt);if(t.schema===_e){let n=zi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Oe}`}}if(t.schema===Ae){let n=Ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Oe}`}}if(t.schema!==Oe){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Gt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Xi(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Gt(t.schema,i).message};let r=Gi(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function re(e,t){js(t);let i=Jt.join(e.changesDir,t);if(!D(e.changesDir,i))throw new Error("Native change path escaped");return i}var gN=256*1024;async function wN(e,t=Jt.dirname(e)){let i=Jt.relative(t,e).split(Jt.sep).join("/"),r=await B({root:t,ref:i,maxBytes:gN}),n=(0,Is.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function zn(e,t){let i=Jt.join(re(e,t),wt);await T(e.nativeRoot,i);let r=vN(await wN(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}import{promises as rr}from"node:fs";import Be from"node:path";var lC=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var Jn="skill-coordinated";function kN(e){return e.state_version+1}function SN(e){return e.map(t=>({...t,result:"pending",reason:null}))}function EN(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:et(e.summary),completed_at:e.completedAt}}function Os(e){let t=le(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=Vt(t,EN({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return le({...r,phase:"build",status:"active",state_version:kN(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:SN(t.acceptance),loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as Ud}from"node:fs";import er from"node:path";function Gn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Un(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Te(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function Gd(e,t){return e===null?null:Te(e,t)}function Yn(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function PN(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function xN(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Kn(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Hs(e,t){if(e===null)return null;let i=Te(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Ds(e,t){let i=Te(e,t);if(!er.isAbsolute(i))throw new Error(`${t} must be absolute`);return er.resolve(i)}function RN(e,t){let i=`Native local checks[${t}]`,r=Gn(e,i);if(Un(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,d)=>Te(l,`${i}.argv[${d}]`,!0)),a=Kn(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Hs(r.startedAt,`${i}.startedAt`),s=Hs(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=Yn(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Te(r.id,`${i}.id`),name:Te(r.name,`${i}.name`),operationId:Te(r.operationId,`${i}.operationId`),status:a,repeatable:xN(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Yn(r.executionCount,`${i}.executionCount`),argv:n,cwd:Ds(r.cwd,`${i}.cwd`),exitCode:PN(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Te(r.log,`${i}.log`)}}function Bs(e){let t="Native local execution state",i=Gn(e,t);if(Un(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Wi)throw new Error(`Native local execution schema must be ${Wi}`);let r=Gn(i.workspace,"Native local workspace");Un(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Gn(i.execution,"Native local execution");Un(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Hs(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Te(o.operationId,"Native local execution.operationId"),stage:Kn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Kn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Gd(o.executionId,"Native local execution.executionId"),status:Kn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Yn(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(RN);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:Wi,change:Te(i.change,"Native local change"),basedOnStateVersion:Yn(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Ds(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Ds(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Gd(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function yt(e){return Bs({schema:Wi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:er.resolve(e.projectRoot),worktreeRoot:er.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Ls(e){let t;try{t=await Ud.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return Bs(i)}async function it(e,t,i={}){let r=Bs(t);await Ud.mkdir(er.dirname(e),{recursive:!0}),await Y(e,r,i)}import{promises as CN}from"node:fs";function rt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
151
|
-
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function
|
|
152
|
-
`),i=e.verification.checks.length===0?"_No Runtime checks were recorded._":["| Check | Command | Working directory | Status | Exit | Duration |","| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(o=>{let s=o.argv_display.map(
|
|
153
|
-
`),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${
|
|
154
|
-
`),n=e.verification.risks.length===0?"_None reported._":e.verification.risks.map(o=>`- ${
|
|
155
|
-
`),a=e.history.length===0?"_No previous iterations._":["| Goal cycle | Iteration | Attempt | Outcome | Unresolved | Summary | Completed |","| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(o=>`| ${o.goal_cycle} | ${o.iteration} | ${o.attempt} | ${o.outcome} | ${o.unresolved_ids.join(", ")||"—"} | ${
|
|
147
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=us(l,t);else if(i)bd(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let f=us(l,null);if(f!==null)t=f;else{let u=l.trimStart();if(u.startsWith("<!--")&&!bd(u))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(u);p&&n.has(p[1].toLowerCase())&&!u.startsWith("</")&&!u.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(u)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function qi(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function fs(e,t,i,r=[],n="content-hash"){let a=qi(i),o=t.replaceAll("\\","/").trim(),s=r.map(qi);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${Z(jw,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function hs(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function $w(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of Vi(e)){n=s+1;let c=o?ds(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function ps(e,t="brief.md",i=Wi.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=$w(e);if(n===null)return[];let a=null;for(let{line:l,body:d,index:f}of Vi(e)){if(f<n.start||f>=n.end)continue;let u=d?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(u===null)continue;let p=u[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:d,index:f}of Vi(e)){if(f<n.start||f>=n.end)continue;let u=d?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;u&&u[1].length===a?(c(),s=[u[2]]):s!==null&&s.push(l)}return c(),hs(o.map(l=>fs("brief-example",t,l.join(`
|
|
148
|
+
`),[],r)),"Brief",r)}function ms(e,t="spec.md",i=Wi.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(fs("spec-scenario",t,[o.title,...o.body].join(`
|
|
149
|
+
`),o.context,r)),o=null}};for(let{line:c,body:l}of Vi(e)){let d=l?ds(c):null,f=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(f){for(s();a.at(-1)&&a.at(-1).level>=d.level;)a.pop();let u=qi(f[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:d.level,title:u,body:[],context:a.map(p=>p.text)}}else if(d){for(o!==null&&d.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=d.level;)a.pop();a.push(d)}else o!==null&&l&&o.body.push(c)}return s(),hs(n,"Specification",r)}function vs(e,t="spec.md",i=Wi.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(fs("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(d=>/^(?:non-?goals?|非目标)$/iu.test(d.text.trim()));for(let{line:d,body:f}of Vi(e)){let u=f?ds(d):null;if(u){for(c(),o!==null&&u.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u),/^Scenario\s*:/iu.test(u.text)&&(o=u.level);continue}let p=d.trim();if(!f||o!==null||l()){c();continue}if(p.length===0||us(d,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(d);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),hs(n,"Specification mandatory requirements",r)}var Ow=/^A[1-9]\d*$/u;function Sd(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||kd.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||kd.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Hw(e,t){return e.localeCompare(t,"en")}function _n(e){let t=Sd(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>Hw(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=ps(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=Sd(a.source,`Native spec source for ${a.capability}`);r.push(...ms(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...vs(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=qi(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function Ed(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!Ow.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Pd(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var jn=ti(Dt(),1);import{promises as Dw}from"node:fs";var Vt="comet.native.v4",zi="comet.native.local-execution.v4";function gs(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Bw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Lw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Fw=/^A[1-9][0-9]*$/u,Mw=/^[a-f0-9]{64}$/u,Vw=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"]),In=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function ee(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function te(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function q(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function ys(e,t){return e===null?null:q(e,t)}function qw(e,t){let i=q(e,t);if(!Mw.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function qt(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function _(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function Ww(e,t){return e===null?null:_(e,t,Number.MIN_SAFE_INTEGER)}function V(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Ce(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function $n(e,t){return Ce(e,t,(i,r)=>q(i,`${t}[${r}]`))}function gt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Wt(e,t){let i=q(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Ns(e,t,i=!1){let r=q(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function Ne(e,t){let i=ee(e,t);return te(i,new Set(["text","truncated"]),t),{text:q(i.text,`${t}.text`,{empty:!0}),truncated:qt(i.truncated,`${t}.truncated`)}}function zw(e,t){let i=`Native spec_changes[${t}]`,r=ee(e,i);te(r,new Set(["capability","operation","source"]),i);let n=q(r.capability,`${i}.capability`);if(!Lw.test(n))throw new Error(`${i}.capability is invalid`);let a=V(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Ns(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function Jw(e){let t="Native workspace",i=ee(e,t);te(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=V(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=ys(i.change_branch,`${t}.change_branch`),a=ys(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:V(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function Gw(e){let t="Native loop",i=ee(e,t);te(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=$n(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return gt(r,`${t}.previous_unresolved_ids`),{stage:V(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:_(i.goal_cycle,`${t}.goal_cycle`,1),iteration:_(i.iteration,`${t}.iteration`),attempt:_(i.attempt,`${t}.attempt`),retry_epoch:_(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:_(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:_(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:_(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:ys(i.next_action,`${t}.next_action`)}}function Uw(e,t){let i=`Native acceptance[${t}]`,r=ee(e,i);te(r,new Set(["id","source","text","result","reason"]),i);let n=q(r.id,`${i}.id`);if(!Fw.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Ns(r.source,`${i}.source`),text:q(r.text,`${i}.text`),result:V(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Ne(r.reason,`${i}.reason`)}}function Kw(e,t){let i=`Native builder_handoff.checks[${t}]`,r=ee(e,i);return te(r,new Set(["name","result","note"]),i),{name:Ne(r.name,`${i}.name`),result:V(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Ne(r.note,`${i}.note`)}}function Yw(e){let t="Native builder_handoff",i=ee(e,t);te(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),t);let r=$n(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return gt(r,`${t}.addressed_acceptance_ids`),{candidate_id:q(i.candidate_id,`${t}.candidate_id`),identity_provider:q(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:q(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:_(i.iteration,`${t}.iteration`,1),summary:Ne(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:Ce(i.checks,`${t}.checks`,Kw),checks_truncated:qt(i.checks_truncated,`${t}.checks_truncated`),known_limits:Ce(i.known_limits,`${t}.known_limits`,(n,a)=>Ne(n,`${t}.known_limits[${a}]`)),known_limits_truncated:qt(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Wt(i.submitted_at,`${t}.submitted_at`)}}function Xw(e,t){let i=`Native blockers[${t}]`,r=ee(e,i);te(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=$n(r.acceptance_ids,`${i}.acceptance_ids`);return gt(n,`${i}.acceptance_ids`),{owner:V(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Ne(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:V(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function Qw(e,t){let i=`Native verification.checks[${t}]`,r=ee(e,i);return te(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:q(r.id,`${i}.id`),name:Ne(r.name,`${i}.name`),argv_display:Ce(r.argv_display,`${i}.argv_display`,(n,a)=>Ne(n,`${i}.argv_display[${a}]`)),argv_truncated:qt(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Ns(r.cwd_ref,`${i}.cwd_ref`,!0),status:V(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:Ww(r.exit_code,`${i}.exit_code`),duration_ms:_(r.duration_ms,`${i}.duration_ms`)}}function Zw(e){let t="Native verification",i=ee(e,t);te(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=Ce(i.checks,`${t}.checks`,Qw);gt(r.map(a=>a.id),`${t}.checks IDs`);let n=q(i.identity_provider,`${t}.identity_provider`);return{candidate_id:q(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:q(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:_(i.iteration,`${t}.iteration`,1),attempt:_(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":V(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:V(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Ne(i.summary,`${t}.summary`),risks:Ce(i.risks,`${t}.risks`,(a,o)=>Ne(a,`${t}.risks[${o}]`)),risks_truncated:qt(i.risks_truncated,`${t}.risks_truncated`),completed_at:Wt(i.completed_at,`${t}.completed_at`)}}function xd(e,t){let i=`Native history[${t}]`,r=ee(e,i);te(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=$n(r.unresolved_ids,`${i}.unresolved_ids`);return gt(n,`${i}.unresolved_ids`),{goal_cycle:_(r.goal_cycle,`${i}.goal_cycle`,1),iteration:_(r.iteration,`${i}.iteration`),attempt:_(r.attempt,`${i}.attempt`),outcome:V(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Ne(r.summary,`${i}.summary`),completed_at:Wt(r.completed_at,`${i}.completed_at`)}}function ey(e){let t="Native history_overflow.outcome_counts",i=ee(e,t),r=["pass","fail","blocked","execution-error","recovery"];return te(i,new Set(r),t),{pass:_(i.pass,`${t}.pass`),fail:_(i.fail,`${t}.fail`),blocked:_(i.blocked,`${t}.blocked`),"execution-error":_(i["execution-error"],`${t}.execution-error`),recovery:_(i.recovery,`${t}.recovery`)}}function ty(e){let t="Native history_overflow",i=ee(e,t);te(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=_(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Wt(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Wt(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=ey(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function iy(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff&&!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function ry(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function ne(e){let t=ee(e,"Native portable state");if(te(t,Vw,"Native portable state"),t.schema!==Vt)throw new Error(`Native portable state schema must be ${Vt}`);let i=q(t.name,"Native state name");if(!Bw.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=Ce(t.spec_changes,"Native spec_changes",zw);gt(r.map(s=>s.capability),"Native spec change capabilities");let n=Ce(t.acceptance,"Native acceptance",Uw);gt(n.map(s=>s.id),"Native acceptance IDs");let a=Ce(t.history,"Native history",xd);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Vt,name:i,language:V(t.language,["en","zh-CN"],"Native state language"),phase:V(t.phase,["shape","build","verify","archive"],"Native state phase"),status:V(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:_(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:qw(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:Jw(t.workspace),loop:Gw(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Yw(t.builder_handoff),blockers:Ce(t.blockers,"Native blockers",Xw),verification:t.verification===null?null:Zw(t.verification),history:a,history_overflow:ty(t.history_overflow),verification_result:V(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:V(t.verification_report,["verification.md"],"Native verification_report"),archived:qt(t.archived,"Native archived"),created_at:Wt(t.created_at,"Native created_at")};return iy(o),ry(o),o}function zt(e,t){let i=ne(e),r=xd(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return ne({...i,history:n,history_overflow:a})}function ny(e,t){let i=(0,jn.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function ae(e){let t=await Dw.readFile(e,"utf8");return ne(ny(t,"Native portable state"))}async function On(e,t,i={}){let r=ne(t);await K(e,(0,jn.stringify)(r),i)}var Tn=new Map;async function ay(e,t){let i=Tn.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Tn.set(e,a),await i;try{return await t()}finally{r(),Tn.get(e)===a&&Tn.delete(e)}}async function wt(e){return ay(e.file,async()=>{let t=_(e.expectedStateVersion,"Native expected state version",1),i=ne(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await ae(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new In(t,r.state_version);return await On(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await ae(e.file);if(n.state_version!==t)throw new In(t,n.state_version)}}),i})}function oy(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function it(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(oy(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var Oe="comet.native.v3",Ae="comet.native.v2",_e="comet.native.v1";var Hn="comet.native.portable-migration.v1",cy=new Set(["schema","id","change","fromSchema","status","createdAt"]),ly=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uy=/^[a-z0-9][a-z0-9-]{7,127}$/u,dy=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),fy=new Set([_e,Ae,Oe]);function hy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function py(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function my(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function vy(e){return e.schema===_e?Ji(e):e.schema===Ae?Gi(e):Ui(e)}function gy(e){return sy.posix.normalize(e.replaceAll("\\","/"))}function wy(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:gy(t.source)})}function yy(e){return e==="shape"?"shape":"build"}function Ny(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function by(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function Rd(e){let t=vy(e.state);Ed(e.acceptance);let i=yy(t.phase),r=i==="shape"?0:1,n=py(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return ne({schema:Vt,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:wy(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:Ny(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:it(by(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:gs(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function bs(e){let t=hy(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!cy.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Hn)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!uy.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!ly.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!fy.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!dy.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Hn,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:my(t.createdAt,"Native portable migration transaction createdAt")}}function Cd(e){switch(bs(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Dn="comet.native.archive-transaction.v4",Ad="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",ky=new RegExp(`^portable-archive-(${Ad})\\.json$`,"u"),Sy=new RegExp(`^portable-migration-(${Ad})\\.json$`,"u"),Ey=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Py=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xy=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Ry=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Cy=new Set(["capability","operation","source","content"]),_d=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Td(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Id(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function Ay(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Td(e,i);if(Id(r,Cy,i),typeof r.capability!="string"||!_d.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function _y(e){let t=Td(e,"Native portable Archive transaction");if(Id(t,Ry,"Native portable Archive transaction"),t.schema!==Dn)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!Ey.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!_d.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!Py.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!xy.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(Ay);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Dn,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function Bn(e){let t=ky.exec(e);if(t)return{kind:"archive",change:t[1]};let i=Sy.exec(e);return i?{kind:"migration",change:i[1]}:null}function yt(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Bn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return ks.join(e.transactionsDir,i)}async function Ss(e,t){let i=Bn(t);if(!i)return null;let r=await I({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=ks.join(e.transactionsDir,t);if(i.kind==="archive"){let s=_y(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=bs(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function Jt(e,t){let i=yt(e,t);try{return await Ss(e,ks.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function jd(e){return e.kind==="archive"||e.journal.status!=="committed"}import He from"path";import{TextDecoder as By}from"util";import{createHash as Ty}from"node:crypto";import{constants as Ln,promises as be}from"node:fs";import ke from"node:path";function Mn(e,t){let i=ke.relative(e,t);return i===""||!ke.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ke.sep}`)}function Iy(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function jy(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function $y(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Fn(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Es(e,t){let i=await be.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await be.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Oy(e,t,i){let r=ke.resolve(e),n=ke.resolve(t);if(!Mn(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Es(r,i)],o=r;for(let s of ke.relative(r,n).split(ke.sep).filter(Boolean)){await Nt(a,i),o=ke.join(o,s);let c=await Es(o,i);if(!Mn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Nt(a,i),a}async function Nt(e,t){for(let i of e){let r=await be.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!jy(i,r)||await be.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function Hy(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Gt(e){let t=Iy(e.maxBytes),i=ke.resolve(e.file),r=await Oy(e.root,ke.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(d=>Es(ke.resolve(d),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Nt(r,e.label);let a=await be.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=$y(a),s=await be.realpath(i);if(!Mn(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(d=>Mn(d.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ln.O_RDONLY:Ln.O_RDONLY|Ln.O_NOFOLLOW|Ln.O_NONBLOCK,l=await be.open(i,c);try{let d=await l.stat();await e.hooks?.afterOpen?.();let[f,u]=await Promise.all([be.lstat(i),be.realpath(i)]);if(await Nt(r,e.label),await Nt(n,e.label),!d.isFile()||!f.isFile()||f.isSymbolicLink()||u!==s||!Fn(o,d)||!Fn(o,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Hy(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),be.lstat(i),be.realpath(i)]);if(await Nt(r,e.label),await Nt(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!Fn(o,v)||!Fn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:Ty("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Ly=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Fy=new Set(["id","type","source","target","staged","backup"]),My=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Vy=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Hd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var qy=256*1024,GP=1024*1024,UP=16*1024;var KP=64*1024*1024;var Wy=new By("utf-8",{fatal:!0});function qn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Wn(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Dd(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ps(e,t){if(typeof e!="string"||e.length===0||He.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Vn(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function $d(e,t){if(Ps(e,t),e.includes("\\")||e!==He.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function zy(e,t){let i=qn(e,`transaction operations[${t}]`);if(Wn(i,Fy,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Ps(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ps(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function Bd(e){let t=qn(e,"Native Archive transaction journal");if(Wn(t,My,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Hd.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Dd(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Vn(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=qn(s,`Archive transaction operations[${c}]`);if(Wn(l,Vy,`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`);$d(l.target,`Archive transaction operation ${l.id} target`);for(let d of["source","staged","backup"])l[d]!==void 0&&$d(l[d],`Archive transaction operation ${l.id} ${d}`);if(l.expectedTargetHash!==null&&Vn(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(Vn(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`);Vn(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function Jy(e){let t=qn(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Bd(t);if(Wn(t,Ly,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Hd.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!He.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!He.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Dd(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(zy),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function Gy(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return He.join(e.transactionsDir,t)}function Ld(e,t){let i=Gy(e,t);return{directory:i,journal:He.join(i,"transaction.json"),events:He.join(i,"events.jsonl"),staged:He.join(i,"staged"),backups:He.join(i,"backups")}}async function Rs(e,t){let i=Ld(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}async function Cs(e,t,i={}){let r=await Rs(e,t),n=await Gt({root:e.runtimeDir,file:r.journal,maxBytes:qy,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Wy.decode(n.bytes)),o=Jy(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Yy(e,t,i){let r;try{r=await Uy.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Cs(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Bn(n.name))try{let a=await Ss(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(jd(a))return!0}catch{return!0}return!1}async function Xy(e,t){let i=Date.now()+5e3,r=Ky.join(e.locksDir,"root-move.lock");for(;;)try{return await Cn(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Nd(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function J(e,t,i,r){let n=await Xy(e,t);try{if(await Mi(e.projectRoot),await Yy(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await An(n)}}import{createHash as Qy}from"crypto";function de(e){return Qy("sha256").update(e).digest("hex")}var vx={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var gx=8*1024*1024;var wx=64*1024,yx=64*1024;var Nx={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},bx={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var kx=(1n<<256n)-1n;var aN=ti(Dt(),1);var Bx=4*1024*1024;var oN=null;function sN(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Fd(e,t){return(...i)=>{let r=oN;if(r===null)return t(...i);let n=sN(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var qx=Fd("hookWritePolicy",async e=>(await Zo(e))?.hook??{allow_paths:[]});var BR=256*1024;var XR={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 Ut from"node:path";var Ki=/^[a-f0-9]{64}$/u,Vd=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,uN=16*1024,hC=process.platform;function dN(e,t){let i=Ut.relative(e,t);return Ut.isAbsolute(i)||i===".."||i.startsWith(`..${Ut.sep}`)?null:i.replaceAll("\\","/")||"."}function qd(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Wd(e,t){if(e.length===0||qd(e)||e.includes("\\")||Ut.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Ut.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function fN(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function As(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||qd(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function hN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(As(e.changeBranch,"Native workspace change branch"),As(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function pN(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Vd.test(t.baseCommit)||typeof t.targetCommit!="string"||!Vd.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");As(t.targetBranch,"Native workspace Git target branch")}function mN(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Ki.test(String(t.projectRootId))||!Ki.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");fN(t.capturedAt),Wd(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Ki.test(String(t.projectRootPathId))||a&&!Ki.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ki.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&pN(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(hN(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function vN(e,t){return Ut.join(xe(e,t),"workspace.json")}function gN(e,t){let i=vN(e,t),r=Re(e,i),n=dN(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Wd(n,"Native workspace file ref")}}async function wN(e,t){try{let i=gN(e,t),r=await I({root:i.root,ref:i.ref,maxBytes:uN});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Yi(e,t){let i=await wN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(mN(i),i)}var Jd=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],bN=new Set(Jd),Gd=new Set([...Jd,"minimum_runtime_version","revision"]),kN=new Set([...Gd,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),SN=new Set(["capability","operation","source","base_hash"]),EN=new Set(["shape","build","verify","archive"]),PN=new Set(["implicit","confirmed"]),xN=new Set(["pending","pass","fail"]),bt="comet-state.yaml",Ts=/^[a-f0-9]{64}$/u,Ud=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,RN=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Is=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Yt=class extends Error{constructor(i,r){super(i!==Oe||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},zn=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Xi=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Jn=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},DC=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
150
|
+
`);function Zi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Kd(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function $s(e){if(!Ud.test(e))throw new Error(`Invalid Native change name: ${e}`)}function CN(e){if(!Ud.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Yd(e,t){if(e.length===0||Kt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function AN(e,t){let i=Zi(e,`spec_changes[${t}]`);if(Kd(i,SN,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(CN(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&Yd(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!Ts.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!Ts.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function _N(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Os(e,t){if(Kd(e,t,bt),typeof e.name!="string")throw new Error("Native change name is required");if($s(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!EN.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!PN.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(AN),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!xN.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&Yd(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!_N(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Ji(e){let t=Zi(e,bt);if(t.schema!==_e)throw new Error(`Expected ${_e}`);return{schema:_e,...Os(t,bN)}}function Qi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function _s(e,t,i){if(e===null)return null;let r=typeof e=="string"?RN.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function TN(e){if(e==null)return null;if(typeof e!="string"||!Ts.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function IN(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Gi(e){let t=Zi(e,bt);if(t.schema!==Ae)throw new Error(`Expected ${Ae}`);if(Qi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ae} minimum_runtime_version must be 2`);return{schema:Ae,minimum_runtime_version:2,revision:Qi(t.revision,"Native v2 revision"),...Os(t,Gd)}}function Ui(e){let t=Zi(e,bt);if(t.schema!==Oe){if(t.schema===_e||t.schema===Ae){let o=t.schema===_e?Ji(t):Gi(t);throw new Is(o.name,o.schema)}throw new Yt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Yt(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Qi(t.revision,"Native revision"),n=Os(t,kN),a=TN(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Oe,minimum_runtime_version:3,revision:r,verification_protocol:IN(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:_s(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:_s(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:_s(t.partial_allowance,"Native partial_allowance","allowances")}}function jN(e){let t=Zi(e,bt);if(t.schema===_e){let n=Ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Oe}`}}if(t.schema===Ae){let n=Gi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Oe}`}}if(t.schema!==Oe){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Yt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Yt(t.schema,i).message};let r=Ui(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function oe(e,t){$s(t);let i=Kt.join(e.changesDir,t);if(!B(e.changesDir,i))throw new Error("Native change path escaped");return i}var $N=256*1024;async function ON(e,t=Kt.dirname(e)){let i=Kt.relative(t,e).split(Kt.sep).join("/"),r=await I({root:t,ref:i,maxBytes:$N}),n=(0,js.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Gn(e,t){let i=Kt.join(oe(e,t),bt);await T(e.nativeRoot,i);let r=jN(await ON(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}import{promises as nr}from"node:fs";import Le from"node:path";var nf=ti(Dt(),1);import{promises as LN}from"node:fs";import FN from"node:path";import{execFileSync as HN}from"node:child_process";var DN=3e4,BN=8*1024*1024,Hs=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function Xd(e,t){try{return HN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:DN,maxBuffer:BN,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Hs(e,t,r)}}function L(e,t){return Xd(e,t).trim()}function Un(e){return L(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Ds(e){let t=Xd(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let i=t.split("\0").filter(Boolean),r=[];for(let n=0;n<i.length;n+=1){let a=i[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(r.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=i[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");r.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(r)].sort()}function Qd(e,t){try{let r=L(e,["config","--get",`branch.${t}.remote`]);if(r&&r!==".")return r}catch{}let i=L(e,["remote"]).split(/\r?\n/u).map(r=>r.trim()).filter(Boolean);if(i.includes("origin"))return"origin";if(i.length===1)return i[0];throw new Error(i.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${i.join(", ")}`)}var Zd="children.yaml",Bs="comet.native.children.v1",MN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VN=new Set(["schema","children"]),qN=new Set(["name","depends_on","covers"]);function ef(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function tf(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0)throw new Error(`${i} fields are invalid`)}function rf(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function WN(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function zN(e,t){let i=new Set(t);for(let a of e){let o=a.covers.filter(s=>!i.has(s));if(o.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${o.join(", ")}`)}let r=new Set(e.flatMap(a=>a.covers)),n=t.filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native children do not cover parent acceptance: ${n.join(", ")}`)}function JN(e,t){let i=(0,nf.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let r=ef(i.toJS({mapAsMap:!1}),"Native children contract");if(tf(r,VN,"Native children contract"),r.schema!==Bs)throw new Error(`Native children schema must be ${Bs}`);if(!Array.isArray(r.children)||r.children.length===0)throw new Error("Native children must be a non-empty array");let n=r.children.map((s,c)=>{let l=ef(s,`Native child ${c}`);if(tf(l,qN,`Native child ${c}`),typeof l.name!="string"||!MN.test(l.name))throw new Error(`Native child ${c} name is invalid`);return{name:l.name,depends_on:rf(l.depends_on,`Native child ${l.name} depends_on`),covers:rf(l.covers,`Native child ${l.name} covers`)}}),a=n.map(({name:s})=>s);if(new Set(a).size!==a.length)throw new Error("Native child names must be unique");let o=new Set(a);for(let s of n){let c=s.depends_on.filter(l=>!o.has(l));if(c.length>0)throw new Error(`Native child ${s.name} depends on unknown child: ${c.join(", ")}`)}return WN(n),t&&zN(n,t),{schema:Bs,children:n}}async function af(e){let t=FN.join(e.changeDir,Zd);try{await LN.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await I({root:e.changeDir,ref:Zd});return{contract:JN(i.text,e.acceptanceIds),size:i.size}}function of(e){return Z("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}var XC=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var Kn="skill-coordinated";function YN(e){return e.state_version+1}function XN(e){return e.map(t=>({...t,result:"pending",reason:null}))}function QN(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:it(e.summary),completed_at:e.completedAt}}function Ls(e){let t=ne(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=zt(t,QN({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return ne({...r,phase:"build",status:"active",state_version:YN(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:XN(t.acceptance),loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as cf}from"node:fs";import tr from"node:path";function Yn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xn(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Te(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function sf(e,t){return e===null?null:Te(e,t)}function Zn(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function ZN(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function eb(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Qn(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Fs(e,t){if(e===null)return null;let i=Te(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Ms(e,t){let i=Te(e,t);if(!tr.isAbsolute(i))throw new Error(`${t} must be absolute`);return tr.resolve(i)}function tb(e,t){let i=`Native local checks[${t}]`,r=Yn(e,i);if(Xn(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,d)=>Te(l,`${i}.argv[${d}]`,!0)),a=Qn(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Fs(r.startedAt,`${i}.startedAt`),s=Fs(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=Zn(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Te(r.id,`${i}.id`),name:Te(r.name,`${i}.name`),operationId:Te(r.operationId,`${i}.operationId`),status:a,repeatable:eb(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Zn(r.executionCount,`${i}.executionCount`),argv:n,cwd:Ms(r.cwd,`${i}.cwd`),exitCode:ZN(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Te(r.log,`${i}.log`)}}function Vs(e){let t="Native local execution state",i=Yn(e,t);if(Xn(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==zi)throw new Error(`Native local execution schema must be ${zi}`);let r=Yn(i.workspace,"Native local workspace");Xn(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Yn(i.execution,"Native local execution");Xn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Fs(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Te(o.operationId,"Native local execution.operationId"),stage:Qn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Qn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:sf(o.executionId,"Native local execution.executionId"),status:Qn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Zn(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(tb);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:zi,change:Te(i.change,"Native local change"),basedOnStateVersion:Zn(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Ms(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Ms(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:sf(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function nt(e){return Vs({schema:zi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:tr.resolve(e.projectRoot),worktreeRoot:tr.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function qs(e){let t;try{t=await cf.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return Vs(i)}async function De(e,t,i={}){let r=Vs(t);await cf.mkdir(tr.dirname(e),{recursive:!0}),await Y(e,r,i)}import{promises as ib}from"node:fs";function at(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
151
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Be(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function rb(e){return e.verification?.assurance==="semantic-verification-unavailable"?"Semantic verification unavailable, user confirmation required":e.verification?.assurance==="user-confirmed-degraded"?"Passed with user-confirmed degraded assurance":e.verification_result==="pass"?e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?"Passed, user confirmation required":"Passed":e.verification_result==="blocked"?"Blocked":e.verification_result==="fail"?"Failed":"Pending"}function nb(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===Kn?Kn:"host-attested")}function ab(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${Be(o.id)} | ${Be(o.result)} | ${Be(o.source)} | ${Be(o.text)} | ${Be(at(o.reason))} |`).join(`
|
|
152
|
+
`),i=e.verification.checks.length===0?"_No Runtime checks were recorded._":["| Check | Command | Working directory | Status | Exit | Duration |","| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(o=>{let s=o.argv_display.map(at).join(" ");return`| ${Be(at(o.name))} | ${Be(s||"—")} | ${Be(o.cwd_ref)} | ${o.status} | ${o.exit_code??"—"} | ${o.duration_ms} ms |`})].join(`
|
|
153
|
+
`),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${at(o.reason)}${o.acceptance_ids.length>0?` (acceptance: ${o.acceptance_ids.join(", ")})`:""} — next: \`${o.resolution_action}\``).join(`
|
|
154
|
+
`),n=e.verification.risks.length===0?"_None reported._":e.verification.risks.map(o=>`- ${at(o)}`).join(`
|
|
155
|
+
`),a=e.history.length===0?"_No previous iterations._":["| Goal cycle | Iteration | Attempt | Outcome | Unresolved | Summary | Completed |","| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(o=>`| ${o.goal_cycle} | ${o.iteration} | ${o.attempt} | ${o.outcome} | ${o.unresolved_ids.join(", ")||"—"} | ${Be(at(o.summary))} | ${o.completed_at} |`)].join(`
|
|
156
156
|
`);return`---
|
|
157
157
|
generated_from_state_version: ${e.state_version}
|
|
158
158
|
---
|
|
@@ -161,13 +161,13 @@ generated_from_state_version: ${e.state_version}
|
|
|
161
161
|
|
|
162
162
|
## Current result
|
|
163
163
|
|
|
164
|
-
- Result: **${
|
|
165
|
-
- Assurance: **${
|
|
164
|
+
- Result: **${rb(e)}**
|
|
165
|
+
- Assurance: **${nb(e)}**
|
|
166
166
|
- Goal cycle: ${e.loop.goal_cycle}
|
|
167
167
|
- Iteration: ${e.verification.iteration}
|
|
168
168
|
- Verifier attempt: ${e.verification.attempt}
|
|
169
169
|
- Completed: ${e.verification.completed_at}
|
|
170
|
-
- Summary: ${
|
|
170
|
+
- Summary: ${at(e.verification.summary)}
|
|
171
171
|
|
|
172
172
|
## Acceptance
|
|
173
173
|
|
|
@@ -195,22 +195,22 @@ ${e.history_overflow.dropped_entries>0?`Earlier history entries folded into summ
|
|
|
195
195
|
|
|
196
196
|
`:""}## Conclusion
|
|
197
197
|
|
|
198
|
-
${
|
|
199
|
-
`}function IN(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function tr(e){let t;try{t=await CN.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=IN(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function ir(e){await K(e.file,TN(e.state))}var Kd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jN="comet-state.yaml",$N="state.json";function be(e,t){if(!Kd.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Be.join(e.changesDir,t);if(!D(e.changesDir,i))throw new Error("Native change path escaped");return i}function ne(e,t){return Be.join(be(e,t),jN)}function Ut(e,t){return Be.join(Ee(e,t),$N)}async function nr(e,t){try{let i=await rr.readFile(ne(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function ON(e){return F(e).currentBranch}async function Le(e,t){return ue(ne(e,t))}async function Yd(e){let t=await mt({file:ne(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let i=Be.join(be(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await rr.rm(i,{force:!0})}return t}async function HN(e){let t=be(e.paths,e.state.name),i=Be.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await rr.readdir(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Kd.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=Be.join(t,...s.split("/")),l=await rr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let d=Be.join(e.paths.specsDir,o.name,"spec.md"),f="create";try{let u=await rr.lstat(d);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);f="modify"}catch(u){if(u.code!=="ENOENT")throw u}a.push({capability:o.name,operation:f,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function DN(e){let t=be(e.paths,e.state.name),i=await B({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await B({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return Cn({briefMarkdown:i.text,specs:r})}async function Fs(e){let t=await HN(e);if(!(t.length===e.state.spec_changes.length&&t.every((a,o)=>{let s=e.state.spec_changes[o];return s!==void 0&&a.capability===s.capability&&a.source===s.source&&(a.operation===s.operation||e.ignoreSpecOperationFor?.has(a.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let r=await DN({...e,specChanges:t}),n=e.state.acceptance.map(({source:a,text:o})=>({source:a,text:o}));return kd(n,r)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native confirmed acceptance criteria changed"}}async function Xd(e){return J(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await Le(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let i={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},r=await Yd({paths:e.paths,previous:t,next:i});return r.verification!==null&&await ir({file:Be.join(be(e.paths,t.name),"verification.md"),state:r}),r})}async function Qd(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...Vt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:et(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}},n=await Yd({paths:e.paths,previous:t,next:r});return await it(Ut(e.paths,t.name),yt({portableState:n,projectRoot:e.paths.projectRoot,branch:ON(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Xn(e){if(e.state.verification===null)return"not-applicable";let t=Be.join(be(e.paths,e.state.name),"verification.md");return await tr({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await ir({file:t,state:e.state}),"rebuilt")}import{promises as BN}from"fs";import LN from"path";var Ms="comet.selection.v2",FN=16*1024;function Qn(e){return LN.join(e,".comet","current-change.json")}function MN(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Zd(e){return e===null||typeof e=="string"}function VN(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!MN(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Zd(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Ms,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Ms)throw new Error(`current change selection schema must be ${Ms}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Zd(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function ef(e){let t;try{let r=Qn(e),{bytes:n}=await ft(r,FN,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...VN(t)}}async function tf(e){await BN.rm(Qn(e),{force:!0})}async function rf(e,t,i){let r=await ef(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await tf(e),!0)}var IA=16*1024;function Vs(e){return Qn(e.projectRoot)}async function Zn(e,t){return await Fi(e.projectRoot),rf(e.projectRoot,"native",t)}var ar=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function qs(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Ws(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=U.join(e.archiveDir,t);if(!D(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function ea(e){try{return await q.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function nf(e,t){let i=U.normalize(U.resolve(e)),r=U.normalize(U.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function af(e,t){let i;try{i=await q.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=U.join(e.archiveDir,n.name);try{let o=await ue(U.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function zs(e,t){let i=await qt(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function of(e,t){return await zs(e,t)!==null||await af(e,t)!==null}async function Nt(e,t){await q.mkdir(e.transactionsDir,{recursive:!0}),await Y(vt(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function sf(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=St(e.paths.projectRoot);i.some(a=>nf(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await Re(a);if(!o)continue;let s=await Bt(a,o.native.artifact_root);r.some(c=>nf(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await q.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await ue(U.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await zn(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function WN(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function zN(e){let t=U.join(e.paths.specsDir,e.change.capability),i=U.join(t,"spec.md");if(!D(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await q.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await q.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([q.realpath(e.paths.specsDir),q.realpath(t)]);if(!D(o,s))throw new Error("Native canonical capability path escaped");try{let c=await q.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await q.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await q.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=U.join(be(e.paths,e.state.name),e.change.source);await K(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await q.mkdir(t,{recursive:!0}),await K(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function Js(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function JN(e,t){let i=be(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await B({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function GN(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(Js(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Gs(e){let t=await Le(e.paths,e.name),i=[];try{Js(t)}catch(o){i.push(o.message)}if(await zs(e.paths,e.name)===null)try{let o=await Fs({paths:e.paths,state:t});o.drifted&&i.push(o.reason??"Native confirmed requirements changed")}catch(o){i.push(o.message)}let n=t.verification===null?"missing":await tr({file:U.join(be(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&i.push(`verification.md is ${n}`);let a=await sf({paths:e.paths,state:t});return a.length>0&&i.push(`capabilities are also declared by: ${a.join(", ")}`),{ready:i.length===0,blockers:i,capabilityPeers:a,archiveDir:Ws(e.paths,qs(t)),stateVersion:t.state_version}}async function cf(e){return J(e.paths,`archive portable change ${e.name}`,async()=>{let t=WN(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await zs(e.paths,e.name),r=be(e.paths,e.name),n=await ea(r),a=n?null:await af(e.paths,e.name),o;if(n)o=await Le(e.paths,e.name);else if(i)o=await ue(U.join(Ws(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);if(n&&!o.archived&&i===null){let l=await Fs({paths:e.paths,state:o});if(l.drifted){let d=l.reason??"Native confirmed requirements changed";throw await Qd({paths:e.paths,state:o,reason:d}),new Error(`${d}; Native change returned to Shape and requires confirmation`)}}let s=Ws(e.paths,i?.archive_ref??qs(o)),c=await ea(s);if(i&&GN(i,o),n&&c)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await Zn(e.paths,o.name),await q.rm(Ee(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)Js(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await sf({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new ar(l);i={schema:On,id:qN(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:qs(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await JN(e.paths,o),created_at:new Date().toISOString()},await Nt(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await Nt(e.paths,i);else if(!n&&c&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);if(i.status==="prepared"){for(let l=i.next_spec_index;l<i.spec_changes.length;l+=1)await zN({paths:e.paths,state:o,change:i.spec_changes[l]}),i={...i,next_spec_index:l+1},await Nt(e.paths,i),await e.hooks?.afterSpecApplied?.(l);i={...i,status:"specs-applied"},await Nt(e.paths,i)}if(i.status==="specs-applied"){if(!o.archived){let l={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await mt({file:ne(e.paths,o.name),expectedStateVersion:o.state_version,next:l,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await Nt(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let l=await ea(r)?r:s;if(await ir({file:U.join(l,"verification.md"),state:o}),await tr({file:U.join(l,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await Nt(e.paths,i),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(await q.mkdir(e.paths.archiveDir,{recursive:!0}),await ea(s))throw new Error(`Native Archive target already exists: ${s}`);await q.rename(r,s),i={...i,status:"moved"},await Nt(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await Zn(e.paths,o.name),await q.rm(Ee(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await q.rm(vt(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:s,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function or(e){let t={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[]},i=r=>({kind:r,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...t,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:i("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...t,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...t,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...t,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:i("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...t,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary","<summary>"],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:i("none")}:{...t,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:i("none")};if(e.status==="blocked"){let r=e.blockers.some(({resolution_action:n})=>n==="retry-verifier");return{...t,disposition:"blocked",action:r?"retry-verifier":"none",commandArgs:r?["comet","native","next",e.name,"--retry-verifier","--summary","<summary>"]:null,requiredInputs:r?["summary"]:["repair-runtime"],inputOptions:r?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:i(r?"retry-verifier":"none")}}if(e.phase==="shape")return{...t,disposition:"continue",action:"confirm-shape",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")};if(e.phase==="build")return{...t,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[]}}],runnerAction:i("builder-handoff")};if(e.phase==="verify"){let r=e.loop.next_action==="await-verifier-result";return{...t,disposition:"continue",action:r?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[r?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:r?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:i(r?"await-verifier":"dispatch-verifier")}}return{...t,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:i("none")}}import{randomUUID as UN}from"node:crypto";import{promises as sr}from"node:fs";import KN from"node:path";var YN=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function XN(e,t){let i=await qt(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function lf(e,t){await sr.mkdir(e.transactionsDir,{recursive:!0}),await Y(vt(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function uf(e,t){await Promise.all([sr.rm(Ee(e,t),{recursive:!0,force:!0}),sr.rm(rs(e,t),{recursive:!0,force:!0}),...YN.map(i=>sr.rm(KN.join(re(e,t),i),{force:!0}))])}async function df(e,t){await it(Ut(e,t.name),yt({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function ff(e,t){try{let i=await Ki(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function hf(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=F(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function QN(e){let t=re(e.paths,e.state.name),i=await B({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await B({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Cn({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function pf(e,t){let i=await zn(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function mf(e){return J(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await XN(e.paths,e.name),i=await nr(e.paths,e.name)?await ue(ne(e.paths,e.name)):null;if(!t&&i)return await uf(e.paths,e.name),await df(e.paths,i),i;let r=null,n=null;for(t||(r=await pf(e.paths,e.name),n=await ff(e.paths,e.name),hf(e.paths,n),t={schema:$n,id:UN(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await lf(e.paths,t));;){let a=Pd(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await pf(e.paths,e.name),n??=await ff(e.paths,e.name),hf(e.paths,n),i=Ed({state:r,acceptance:await QN({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await jn(ne(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await uf(e.paths,e.name):a.action==="commit-transaction"&&(i??=await ue(ne(e.paths,e.name)),await df(e.paths,i)),t={...t,status:a.nextStatus},await lf(e.paths,t)}return await sr.rm(vt(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??ue(ne(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as vf}from"node:fs";import gf from"node:path";function ZN(e,t){let i=F(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function eb(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function tb(e,t){let i=new Date().toISOString(),r=e.verification===null?e:Vt(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:et(t),completed_at:i});return le({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:eb(e),verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function ib(e){try{let t=await Ls(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function wf(e){return J(e.paths,`recover portable change ${e.name}`,async()=>{let t=await Le(e.paths,e.name);if(t.status==="done")return await Xn({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let i=ZN(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=Ut(e.paths,e.name),n=await ib(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)},await it(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await Xn({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(u=>u.status==="interrupted"&&!u.repeatable):void 0;if(s){let u=Os({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await mt({file:ne(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot}),await vf.rm(gf.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=yt({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await it(r,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=c||l;if(d){let u=tb(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.");t=await mt({file:ne(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot})}let f=yt({portableState:t,projectRoot:e.paths.projectRoot,branch:F(e.paths.projectRoot).currentBranch});return await vf.mkdir(gf.dirname(Ut(e.paths,t.name)),{recursive:!0}),await it(r,f,{containedRoot:e.paths.runtimeDir}),await Xn({paths:e.paths,state:t}),{state:t,local:f,action:d?"reverify":"resume-stable-boundary",reason:a,message:d?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{promises as fb}from"node:fs";import Yt from"node:path";import{execFileSync as rb}from"node:child_process";var nb=6e4,ab=8*1024*1024,Us=class extends Error{constructor(i,r,n,a){super(`${i} ${r.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=i;this.args=r;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr};function Ks(e,t,i={}){let r=i.timeoutMs??nb,n=i.maxBufferBytes??ab;if(!Number.isSafeInteger(r)||r<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");try{return rb(e,[...t],{...i.cwd?{cwd:i.cwd}:{},encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:r,maxBuffer:n,windowsHide:!0,shell:!1})}catch(a){let o=typeof a.stderr=="string"?a.stderr.trim():Buffer.isBuffer(a.stderr)?a.stderr.toString("utf8").trim():"";throw new Us(e,t,o,{cause:a})}}import{execFileSync as ob}from"node:child_process";var sb=3e4,cb=8*1024*1024,Ys=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function yf(e,t){try{return ob("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:sb,maxBuffer:cb,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Ys(e,t,r)}}function L(e,t){return yf(e,t).trim()}function ta(e){return L(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Xs(e){let t=yf(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let i=t.split("\0").filter(Boolean),r=[];for(let n=0;n<i.length;n+=1){let a=i[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(r.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=i[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");r.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(r)].sort()}function Nf(e,t){try{let r=L(e,["config","--get",`branch.${t}.remote`]);if(r&&r!==".")return r}catch{}let i=L(e,["remote"]).split(/\r?\n/u).map(r=>r.trim()).filter(Boolean);if(i.includes("origin"))return"origin";if(i.length===1)return i[0];throw new Error(i.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${i.join(", ")}`)}import ub from"path";var db=["Outcome","Scope","Non-goals","Acceptance examples"],j_=[...db,"Constraints and invariants","Decisions","Open questions","Verification expectations"];function ia(e,t){return ub.join(e.specsDir,t,"spec.md")}var cr=class extends Error{constructor(i){super(i.message??"Native workspace finish is blocked");this.result=i;this.name="NativeWorkspaceFinishError"}result};function hb(e,t){let i=Yt.relative(e,t);return i===""||!Yt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Yt.sep}`)}function bt(e,t){let i=Yt.relative(e,t).replaceAll("\\","/");if(!i||i===".."||i.startsWith("../")||Yt.isAbsolute(i))throw new Error(`Native workspace finish path escaped the project: ${t}`);return i}function bf(e,t){return t.some(i=>e===i||e.startsWith(`${i}/`))}function pb(e){try{if(L(e,["config","--get","user.name"])&&L(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function mb(e,t){for(let i of St(e))if(F(i).currentBranch===t)return i;return null}function vb(e,t){try{Ks(e,t,{timeoutMs:1e4})}catch(i){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:i})}}async function Qs(e){let{paths:t,state:i}=e,r=i.workspace;if(r.isolation==="current")return null;if(!r.finish||!r.change_branch||!r.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(r.change_branch===r.target_branch)throw new Error("Native change and target branches must be different for workspace finish");let n=F(t.projectRoot);if(!n.primaryWorktreeRoot||n.currentBranch!==r.change_branch)throw new Error(`Native workspace finish requires branch ${r.change_branch} in the current registered worktree`);pb(t.projectRoot);let a=[bt(t.projectRoot,Vs(t))];e.archiveDir&&a.push(bt(t.projectRoot,re(t,i.name)),bt(t.projectRoot,e.archiveDir));let o=Xs(t.projectRoot).filter(l=>!bf(l,a));if(o.length>0)throw new Error(`Native workspace finish is blocked until change-owned implementation and artifacts are committed; remaining paths: ${o.slice(0,20).join(", ")}${o.length>20?", ...":""}`);let s=r.isolation==="branch"?t.projectRoot:mb(n.primaryWorktreeRoot,r.target_branch);if(r.finish==="merge"&&r.isolation==="worktree"){if(!s)throw new Error(`Native merge finish requires a registered worktree on target branch ${r.target_branch}`);if(!ta(s))throw new Error(`Native merge target worktree is not clean: ${s}`)}let c=r.finish==="push"||r.finish==="pull-request"?Nf(t.projectRoot,r.change_branch):null;return r.finish==="pull-request"&&vb("gh",["--version"]),{finish:r.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:r.change_branch,targetBranch:r.target_branch,targetRoot:s,remote:c,isolation:r.isolation}}function gb(e,t){try{return Ks("gh",t,{cwd:e,timeoutMs:6e4}).trim()}catch(i){throw new Error(`gh ${t.join(" ")} failed: ${i.message}`,{cause:i})}}async function wb(e){try{return await fb.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function yb(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},message:null,recoveryArgs:null}}async function kf(e){let t=yb(e.plan),i=null;try{let r=[bt(e.paths.projectRoot,re(e.paths,e.name)),bt(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(c=>bt(e.paths.projectRoot,ia(e.paths,c.capability))),bt(e.paths.projectRoot,Vs(e.paths))],n=Xs(e.plan.changeRoot).filter(c=>!bf(c,r));if(n.length>0)throw new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${n.slice(0,20).join(", ")}${n.length>20?", ...":""}`);let a=[];for(let c of r){let l=Yt.resolve(e.paths.projectRoot,...c.split("/")),d=L(e.plan.changeRoot,["ls-files","--",c])!=="";(await wb(l)||d)&&a.push(c)}if(a.length>0&&L(e.plan.changeRoot,["add","-A","--",...a]),L(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&L(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=L(e.plan.changeRoot,["rev-parse","HEAD"]),!ta(e.plan.changeRoot))throw new Error("Native archive commit left unexpected working-tree changes");if(e.plan.finish==="keep")return t;if(e.plan.finish==="push"||e.plan.finish==="pull-request"){if(L(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequestUrl=gb(e.plan.changeRoot,["pr","create","--base",e.plan.targetBranch,"--head",e.plan.changeBranch,"--fill"]).split(/\r?\n/u).find(l=>/^https?:\/\//u.test(l.trim()))??null,!t.pullRequestUrl))throw new Error("GitHub CLI did not return a pull request URL");let c=hb(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!c?(L(e.plan.primaryRoot,["worktree","remove",e.plan.changeRoot]),t.cleanup={performed:!0,reason:null}):e.plan.isolation==="worktree"&&(t.cleanup={performed:!1,reason:"invocation-working-directory-is-the-change-worktree"}),t}let s=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(L(s,["switch",e.plan.targetBranch]),i=s),L(s,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=s,t.cleanup={performed:!1,reason:"post-merge-validation-required-before-cleanup"},t}catch(r){if(i!==null){let n;try{L(i,["merge","--abort"])}catch{}try{F(i).currentBranch===e.plan.targetBranch&&L(i,["switch",e.plan.changeBranch]),n=F(i).currentBranch===e.plan.changeBranch}catch{n=!1}n||(t.targetRoot=i)}throw t.status="blocked",t.message=r.message,t.recoveryArgs=e.plan.finish==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new cr(t)}}import tc from"path";var Nb=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Sf=1024*1024;var Pf="scoped-text-safety",bb=1,kb=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Sb="comet.native.checker-policy.v1";var pT=ce(Sb,{policy:Pf,version:bb,limits:kb,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Eb=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],mT=new Set(Eb);var Rb=Sf,IT=3*Rb;var xf={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},Ab=de("comet-native-runtime:v3:scope-reopen"),aI=[{skillVersion:"3",skillHash:de("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:de("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:de("comet-native-runtime:v1")}];var Cf=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],LI=new Set(Cf),Hb=new Set([...Cf,"minimum_runtime_version","revision"]),FI=new Set([...Hb,"operation"]),MI=512*1024,Db=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),VI=new Set([...Db,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var JI={maxAcceptanceCriteria:qi.maxCriteria};var XI={maxSpecs:64,maxFileBytes:pr,maxTotalBytes:4*1024*1024};import{execFile as Jb}from"node:child_process";import{promisify as Gb}from"node:util";var sj={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var Cj=512*1024;var lr=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var Xj=64*1024;var Qj=3600*1e3;var Zj=Gb(Jb);var ra=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};var B$={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var U$=16*1024*1024,K$=256*1024,Y$=16*1024;var tO=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var WO=16*1024*1024,na=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},aa=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var oa=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Tf=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],ec=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:Tf,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries or inspect the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker]
|
|
200
|
-
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape, a completed skill-coordinated pass, or an explicitly degraded verifier-unavailable fallback before Archive.","--return-to-build Return Verify or Archive to Build after invalidation or user choice.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Implementation changed" --return-to-build','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
201
|
-
comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function
|
|
198
|
+
${at(e.verification.summary)}
|
|
199
|
+
`}function ob(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function ir(e){let t;try{t=await ib.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=ob(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function rr(e){await K(e.file,ab(e.state))}var lf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sb="comet-state.yaml",cb="state.json";function fe(e,t){if(!lf.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Le.join(e.changesDir,t);if(!B(e.changesDir,i))throw new Error("Native change path escaped");return i}function se(e,t){return Le.join(fe(e,t),sb)}function kt(e,t){return Le.join(Pe(e,t),cb)}async function ar(e,t){try{let i=await nr.readFile(se(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function uf(e){return F(e).currentBranch}async function Fe(e,t){return ae(se(e,t))}async function df(e){let t=await wt({file:se(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let i=Le.join(fe(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await nr.rm(i,{force:!0})}return t}async function lb(e){let t=fe(e.paths,e.state.name),i=Le.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await nr.readdir(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!lf.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=Le.join(t,...s.split("/")),l=await nr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let d=Le.join(e.paths.specsDir,o.name,"spec.md"),f="create";try{let u=await nr.lstat(d);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);f="modify"}catch(u){if(u.code!=="ENOENT")throw u}a.push({capability:o.name,operation:f,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function ub(e){let t=fe(e.paths,e.state.name),i=await I({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await I({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return _n({briefMarkdown:i.text,specs:r})}async function Ws(e){let t=await lb(e),i=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let d=e.state.spec_changes[l];return d!==void 0&&c.capability===d.capability&&c.source===d.source&&(c.operation===d.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await ub({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Pd(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await af({changeDir:fe(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c)})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?of({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function ff(e){return J(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await Fe(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let i={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},r=await df({paths:e.paths,previous:t,next:i});return await De(kt(e.paths,t.name),nt({portableState:r,projectRoot:e.paths.projectRoot,branch:uf(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r.verification!==null&&await rr({file:Le.join(fe(e.paths,t.name),"verification.md"),state:r}),r})}async function hf(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...zt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:it(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await df({paths:e.paths,previous:t,next:r});return await De(kt(e.paths,t.name),nt({portableState:n,projectRoot:e.paths.projectRoot,branch:uf(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function ea(e){if(e.state.verification===null)return"not-applicable";let t=Le.join(fe(e.paths,e.state.name),"verification.md");return await ir({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await rr({file:t,state:e.state}),"rebuilt")}import{promises as db}from"fs";import fb from"path";var zs="comet.selection.v2",hb=16*1024;function ta(e){return fb.join(e,".comet","current-change.json")}function pb(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function pf(e){return e===null||typeof e=="string"}function mb(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!pb(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!pf(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:zs,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==zs)throw new Error(`current change selection schema must be ${zs}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!pf(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function mf(e){let t;try{let r=ta(e),{bytes:n}=await mt(r,hb,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...mb(t)}}async function vf(e){await db.rm(ta(e),{force:!0})}async function gf(e,t,i){let r=await mf(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await vf(e),!0)}var S_=16*1024;function Js(e){return ta(e.projectRoot)}async function ia(e,t){return await Mi(e.projectRoot),gf(e.projectRoot,"native",t)}var or=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function Gs(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Us(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=U.join(e.archiveDir,t);if(!B(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function ra(e){try{return await W.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function wf(e,t){let i=U.normalize(U.resolve(e)),r=U.normalize(U.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function yf(e,t){let i;try{i=await W.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=U.join(e.archiveDir,n.name);try{let o=await ae(U.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function Ks(e,t){let i=await Jt(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function Nf(e,t){return await Ks(e,t)!==null||await yf(e,t)!==null}async function St(e,t){await W.mkdir(e.transactionsDir,{recursive:!0}),await Y(yt(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function bf(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=ot(e.paths.projectRoot);i.some(a=>wf(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await we(a);if(!o)continue;let s=await tt(a,o.native.artifact_root);r.some(c=>wf(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await W.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await ae(U.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await Gn(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function gb(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function wb(e){let t=U.join(e.paths.specsDir,e.change.capability),i=U.join(t,"spec.md");if(!B(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await W.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await W.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([W.realpath(e.paths.specsDir),W.realpath(t)]);if(!B(o,s))throw new Error("Native canonical capability path escaped");try{let c=await W.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await W.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await W.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=U.join(fe(e.paths,e.state.name),e.change.source);await K(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await W.mkdir(t,{recursive:!0}),await K(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function Ys(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function yb(e,t){let i=fe(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await I({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function Nb(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(Ys(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Xs(e){let t=await Fe(e.paths,e.name),i=[];try{Ys(t)}catch(o){i.push(o.message)}if(await Ks(e.paths,e.name)===null)try{let o=await Ws({paths:e.paths,state:t});o.drifted&&i.push(o.reason??"Native confirmed requirements changed")}catch(o){i.push(o.message)}let n=t.verification===null?"missing":await ir({file:U.join(fe(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&i.push(`verification.md is ${n}`);let a=await bf({paths:e.paths,state:t});return a.length>0&&i.push(`capabilities are also declared by: ${a.join(", ")}`),{ready:i.length===0,blockers:i,capabilityPeers:a,archiveDir:Us(e.paths,Gs(t)),stateVersion:t.state_version}}async function kf(e){return J(e.paths,`archive portable change ${e.name}`,async()=>{let t=gb(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await Ks(e.paths,e.name),r=fe(e.paths,e.name),n=await ra(r),a=n?null:await yf(e.paths,e.name),o;if(n)o=await Fe(e.paths,e.name);else if(i)o=await ae(U.join(Us(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);if(n&&!o.archived&&i===null){let l=await Ws({paths:e.paths,state:o});if(l.drifted){let d=l.reason??"Native confirmed requirements changed";throw await hf({paths:e.paths,state:o,reason:d}),new Error(`${d}; Native change returned to Shape and requires confirmation`)}}let s=Us(e.paths,i?.archive_ref??Gs(o)),c=await ra(s);if(i&&Nb(i,o),n&&c)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await ia(e.paths,o.name),await W.rm(Pe(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)Ys(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await bf({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new or(l);i={schema:Dn,id:vb(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:Gs(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await yb(e.paths,o),created_at:new Date().toISOString()},await St(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await St(e.paths,i);else if(!n&&c&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);if(i.status==="prepared"){for(let l=i.next_spec_index;l<i.spec_changes.length;l+=1)await wb({paths:e.paths,state:o,change:i.spec_changes[l]}),i={...i,next_spec_index:l+1},await St(e.paths,i),await e.hooks?.afterSpecApplied?.(l);i={...i,status:"specs-applied"},await St(e.paths,i)}if(i.status==="specs-applied"){if(!o.archived){let l={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await wt({file:se(e.paths,o.name),expectedStateVersion:o.state_version,next:l,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await St(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let l=await ra(r)?r:s;if(await rr({file:U.join(l,"verification.md"),state:o}),await ir({file:U.join(l,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await St(e.paths,i),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(await W.mkdir(e.paths.archiveDir,{recursive:!0}),await ra(s))throw new Error(`Native Archive target already exists: ${s}`);await W.rename(r,s),i={...i,status:"moved"},await St(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await ia(e.paths,o.name),await W.rm(Pe(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await W.rm(yt(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:s,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function sr(e,t){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary","<summary>"],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:r("none")};if(e.status==="blocked"){let n=e.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?["comet","native","next",e.name,"--retry-verifier","--summary","<summary>"]:null,requiredInputs:n?["summary"]:["repair-runtime"],inputOptions:n?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:r(n?"retry-verifier":"none")}}if(e.phase==="shape")return{...i,disposition:"continue",action:"confirm-shape",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(t.allDone)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};let n=t.children.some(({status:o})=>o==="blocked"),a=t.children.some(({status:o})=>o==="ready"||o==="active");return{...i,disposition:n&&!a?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:n&&!a?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:r("none")}}return{...i,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[]}}],runnerAction:r("builder-handoff")}}if(e.phase==="verify"){let n=e.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[n?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:n?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:r(n?"await-verifier":"dispatch-verifier")}}return{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}import{randomUUID as bb}from"node:crypto";import{promises as cr}from"node:fs";import kb from"node:path";var Sb=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function Eb(e,t){let i=await Jt(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function Sf(e,t){await cr.mkdir(e.transactionsDir,{recursive:!0}),await Y(yt(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Ef(e,t){await Promise.all([cr.rm(Pe(e,t),{recursive:!0,force:!0}),cr.rm(ns(e,t),{recursive:!0,force:!0}),...Sb.map(i=>cr.rm(kb.join(oe(e,t),i),{force:!0}))])}async function Pf(e,t){await De(kt(e,t.name),nt({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function xf(e,t){try{let i=await Yi(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Rf(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=F(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function Pb(e){let t=oe(e.paths,e.state.name),i=await I({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await I({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return _n({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Cf(e,t){let i=await Gn(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Af(e){return J(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await Eb(e.paths,e.name),i=await ar(e.paths,e.name)?await ae(se(e.paths,e.name)):null;if(!t&&i)return await Ef(e.paths,e.name),await Pf(e.paths,i),i;let r=null,n=null;for(t||(r=await Cf(e.paths,e.name),n=await xf(e.paths,e.name),Rf(e.paths,n),t={schema:Hn,id:bb(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Sf(e.paths,t));;){let a=Cd(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await Cf(e.paths,e.name),n??=await xf(e.paths,e.name),Rf(e.paths,n),i=Rd({state:r,acceptance:await Pb({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await On(se(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Ef(e.paths,e.name):a.action==="commit-transaction"&&(i??=await ae(se(e.paths,e.name)),await Pf(e.paths,i)),t={...t,status:a.nextStatus},await Sf(e.paths,t)}return await cr.rm(yt(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??ae(se(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as _f}from"node:fs";import Tf from"node:path";function xb(e,t){let i=F(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function Rb(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function Cb(e,t){let i=new Date().toISOString(),r=e.verification===null?e:zt(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:it(t),completed_at:i});return ne({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:Rb(e),verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function Ab(e){try{let t=await qs(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function If(e){return J(e.paths,`recover portable change ${e.name}`,async()=>{let t=await Fe(e.paths,e.name);if(t.status==="done")return await ea({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let i=xb(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=kt(e.paths,e.name),n=await Ab(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)},await De(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await ea({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(u=>u.status==="interrupted"&&!u.repeatable):void 0;if(s){let u=Ls({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await wt({file:se(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot}),await _f.rm(Tf.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=nt({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await De(r,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=c||l;if(d){let u=Cb(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.");t=await wt({file:se(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot})}let f=nt({portableState:t,projectRoot:e.paths.projectRoot,branch:F(e.paths.projectRoot).currentBranch});return await _f.mkdir(Tf.dirname(kt(e.paths,t.name)),{recursive:!0}),await De(r,f,{containedRoot:e.paths.runtimeDir}),await ea({paths:e.paths,state:t}),{state:t,local:f,action:d?"reverify":"resume-stable-boundary",reason:a,message:d?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{promises as Hb}from"node:fs";import Qt from"node:path";import{execFileSync as _b}from"node:child_process";var Tb=6e4,Ib=8*1024*1024,Qs=class extends Error{constructor(i,r,n,a){super(`${i} ${r.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=i;this.args=r;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr};function Zs(e,t,i={}){let r=i.timeoutMs??Tb,n=i.maxBufferBytes??Ib;if(!Number.isSafeInteger(r)||r<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");try{return _b(e,[...t],{...i.cwd?{cwd:i.cwd}:{},encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:r,maxBuffer:n,windowsHide:!0,shell:!1})}catch(a){let o=typeof a.stderr=="string"?a.stderr.trim():Buffer.isBuffer(a.stderr)?a.stderr.toString("utf8").trim():"";throw new Qs(e,t,o,{cause:a})}}import $b from"path";var Ob=["Outcome","Scope","Non-goals","Acceptance examples"],kT=[...Ob,"Constraints and invariants","Decisions","Open questions","Verification expectations"];function na(e,t){return $b.join(e.specsDir,t,"spec.md")}var lr=class extends Error{constructor(i){super(i.message??"Native workspace finish is blocked");this.result=i;this.name="NativeWorkspaceFinishError"}result};function Db(e,t){let i=Qt.relative(e,t);return i===""||!Qt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qt.sep}`)}function Et(e,t){let i=Qt.relative(e,t).replaceAll("\\","/");if(!i||i===".."||i.startsWith("../")||Qt.isAbsolute(i))throw new Error(`Native workspace finish path escaped the project: ${t}`);return i}function jf(e,t){return t.some(i=>e===i||e.startsWith(`${i}/`))}function Bb(e){try{if(L(e,["config","--get","user.name"])&&L(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function Lb(e,t){for(let i of ot(e))if(F(i).currentBranch===t)return i;return null}function Fb(e,t){try{Zs(e,t,{timeoutMs:1e4})}catch(i){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:i})}}async function ec(e){let{paths:t,state:i}=e,r=i.workspace;if(r.isolation==="current")return null;if(!r.finish||!r.change_branch||!r.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(r.change_branch===r.target_branch)throw new Error("Native change and target branches must be different for workspace finish");let n=F(t.projectRoot);if(!n.primaryWorktreeRoot||n.currentBranch!==r.change_branch)throw new Error(`Native workspace finish requires branch ${r.change_branch} in the current registered worktree`);Bb(t.projectRoot);let a=[Et(t.projectRoot,Js(t))];e.archiveDir&&a.push(Et(t.projectRoot,oe(t,i.name)),Et(t.projectRoot,e.archiveDir));let o=Ds(t.projectRoot).filter(l=>!jf(l,a));if(o.length>0)throw new Error(`Native workspace finish is blocked until change-owned implementation and artifacts are committed; remaining paths: ${o.slice(0,20).join(", ")}${o.length>20?", ...":""}`);let s=r.isolation==="branch"?t.projectRoot:Lb(n.primaryWorktreeRoot,r.target_branch);if(r.finish==="merge"&&r.isolation==="worktree"){if(!s)throw new Error(`Native merge finish requires a registered worktree on target branch ${r.target_branch}`);if(!Un(s))throw new Error(`Native merge target worktree is not clean: ${s}`)}let c=r.finish==="push"||r.finish==="pull-request"?Qd(t.projectRoot,r.change_branch):null;return r.finish==="pull-request"&&Fb("gh",["--version"]),{finish:r.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:r.change_branch,targetBranch:r.target_branch,targetRoot:s,remote:c,isolation:r.isolation}}function Mb(e,t){try{return Zs("gh",t,{cwd:e,timeoutMs:6e4}).trim()}catch(i){throw new Error(`gh ${t.join(" ")} failed: ${i.message}`,{cause:i})}}async function Vb(e){try{return await Hb.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function qb(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},message:null,recoveryArgs:null}}async function $f(e){let t=qb(e.plan),i=null;try{let r=[Et(e.paths.projectRoot,oe(e.paths,e.name)),Et(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(c=>Et(e.paths.projectRoot,na(e.paths,c.capability))),Et(e.paths.projectRoot,Js(e.paths))],n=Ds(e.plan.changeRoot).filter(c=>!jf(c,r));if(n.length>0)throw new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${n.slice(0,20).join(", ")}${n.length>20?", ...":""}`);let a=[];for(let c of r){let l=Qt.resolve(e.paths.projectRoot,...c.split("/")),d=L(e.plan.changeRoot,["ls-files","--",c])!=="";(await Vb(l)||d)&&a.push(c)}if(a.length>0&&L(e.plan.changeRoot,["add","-A","--",...a]),L(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&L(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=L(e.plan.changeRoot,["rev-parse","HEAD"]),!Un(e.plan.changeRoot))throw new Error("Native archive commit left unexpected working-tree changes");if(e.plan.finish==="keep")return t;if(e.plan.finish==="push"||e.plan.finish==="pull-request"){if(L(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequestUrl=Mb(e.plan.changeRoot,["pr","create","--base",e.plan.targetBranch,"--head",e.plan.changeBranch,"--fill"]).split(/\r?\n/u).find(l=>/^https?:\/\//u.test(l.trim()))??null,!t.pullRequestUrl))throw new Error("GitHub CLI did not return a pull request URL");let c=Db(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!c?(L(e.plan.primaryRoot,["worktree","remove",e.plan.changeRoot]),t.cleanup={performed:!0,reason:null}):e.plan.isolation==="worktree"&&(t.cleanup={performed:!1,reason:"invocation-working-directory-is-the-change-worktree"}),t}let s=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(L(s,["switch",e.plan.targetBranch]),i=s),L(s,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=s,t.cleanup={performed:!1,reason:"post-merge-validation-required-before-cleanup"},t}catch(r){if(i!==null){let n;try{L(i,["merge","--abort"])}catch{}try{F(i).currentBranch===e.plan.targetBranch&&L(i,["switch",e.plan.changeBranch]),n=F(i).currentBranch===e.plan.changeBranch}catch{n=!1}n||(t.targetRoot=i)}throw t.status="blocked",t.message=r.message,t.recoveryArgs=e.plan.finish==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new lr(t)}}import rc from"path";var Wb=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Of=1024*1024;var Df="scoped-text-safety",zb=1,Jb=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Gb="comet.native.checker-policy.v1";var rI=Z(Gb,{policy:Df,version:zb,limits:Jb,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Ub=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],nI=new Set(Ub);var Xb=Of,bI=3*Xb;var Bf={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},Zb=de("comet-native-runtime:v3:scope-reopen"),UI=[{skillVersion:"3",skillHash:de("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:de("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:de("comet-native-runtime:v1")}];var Ff=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],Cj=new Set(Ff),ok=new Set([...Ff,"minimum_runtime_version","revision"]),Aj=new Set([...ok,"operation"]),_j=512*1024,sk=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Tj=new Set([...sk,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var Oj={maxAcceptanceCriteria:Wi.maxCriteria};var Fj={maxSpecs:64,maxFileBytes:pr,maxTotalBytes:4*1024*1024};import{execFile as vk}from"node:child_process";import{promisify as gk}from"node:util";var Yj={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var g$=512*1024;var ur=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var F$=64*1024;var M$=3600*1e3;var V$=gk(vk);var aa=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};var RO={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var DO=16*1024*1024,BO=256*1024,LO=16*1024;var WO=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var j0=16*1024*1024,oa=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},sa=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var ca=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var qf=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],ic=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:qf,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction; parent changes also expose children and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker]
|
|
200
|
+
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape, a completed skill-coordinated pass, or an explicitly degraded verifier-unavailable fallback before Archive.","--return-to-build Return Verify or Archive to Build after invalidation or user choice.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Implementation changed" --return-to-build','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
201
|
+
comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function tc(e,t){return`${e}:
|
|
202
202
|
${t.map(i=>` ${i}`).join(`
|
|
203
|
-
`)}`}function
|
|
204
|
-
${i.output}`),i.examples&&r.push("",
|
|
203
|
+
`)}`}function kk(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return ic[i]||t.length>1&&ic[t[0]]?.subcommands?i:t[0]}function Sk(e=[]){let t=kk(e),i=ic[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",tc("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...qf];return n&&n.length>0&&r.push("",tc("Options",n)),r.push("",`Output:
|
|
204
|
+
${i.output}`),i.examples&&r.push("",tc("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
|
|
205
205
|
`)}
|
|
206
|
-
`}}var
|
|
207
|
-
`}}function
|
|
208
|
-
`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function
|
|
209
|
-
`);if(r){if(!h)return
|
|
210
|
-
`);if(c)h=await
|
|
211
|
-
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new
|
|
212
|
-
`)}if(s)throw new
|
|
213
|
-
`)}function
|
|
214
|
-
`}}async function
|
|
206
|
+
`}}var Ek=Sk().usage;var eH=10*1024*1024,$=class extends Error{};function dr(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new $(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Zt(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new $(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new $(`${t} requires a value`);return e.splice(r,2),n}function nc(e){if(e.length>0)throw new $(`Unexpected argument: ${e[0]}`)}function zf(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new $(`${t} is required`);return i}function Wf(e,t){let i=rc.normalize(e),r=rc.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Pk(e){let t=rc.resolve(e),i=F(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=F(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Wf(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Wf(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function Jf(e){return e?Pk(e):Pn(process.cwd())}async function Gf(e){let t=await cd({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function ei(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
|
|
207
|
+
`}}function Uf(e,t){if(t instanceof $)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof oa)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof sa)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof zn)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof Xi)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof ca)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Jn)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof aa)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ur)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Kf(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
208
|
+
`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function Yf(e,t){let i=zf(e,"change name"),r=dr(e,"--dry-run"),n=Zt(e,"--expect-preflight"),a=dr(e,"--confirmed"),o=Zt(e,"--finish"),s=Zt(e,"--serial-first");if(s!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s))throw new $("--serial-first must be one Native change name");let c=o;if(c!==void 0&&c!=="merge"&&c!=="push"&&c!=="pull-request"&&c!=="keep")throw new $("--finish must be merge, push, pull-request, or keep");let l=await Gf(t),d=await ar(l.paths,i),f=d?await Jt(l.paths,{kind:"archive",change:i}):null,u=d?!1:await Nf(l.paths,i);if(d||u){if(n)throw new $("Portable Native Archive does not use preflight hashes");if(r&&a)throw new $("--confirmed is only valid when executing Archive");if(r&&s)throw new $("--serial-first is only valid when executing Archive");if(!r&&c)throw new $("--finish is only valid with --dry-run");nc(e);let v=d&&!r&&f?.kind!=="archive"?await If({paths:l.paths,name:i}):null,h=v?.state??(d?await Fe(l.paths,i):null);if(v?.action==="reverify"||v?.action==="await-user")return ei(r?"archive --dry-run":"archive",{archived:!1,state:v.state,recovery:v,continuation:sr(v.state)},`${v.message}
|
|
209
|
+
`);if(r){if(!h)return ei("archive --dry-run",{change:i,ready:!0,archiveRecovery:!0,continuation:{disposition:"continue",reason:"Resume the interrupted Native Archive transaction.",commandArgs:["comet","native","archive",i,"--confirmed"],inputOptions:[],runnerAction:null}},`Native Archive recovery is ready for ${i}
|
|
210
|
+
`);if(c)h=await ff({paths:l.paths,name:i,finish:c});else if(h.workspace.isolation!=="current"&&h.workspace.finish===null)throw new $("Native branch and worktree isolation require --finish with --dry-run");let w=await Xs({paths:l.paths,name:i}),k=sr(h),S=w.capabilityPeers.length>0?{...k,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],runnerAction:{...k.runnerAction,kind:"none"}}:k;return ei("archive --dry-run",{...w,workspaceFinish:h.workspace.finish,continuation:S},`Native Archive preview: ${w.ready?"ready":"blocked"}
|
|
211
|
+
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new $("archive requires --confirmed when native.archive_confirmation is required");if(h&&h.workspace.isolation!=="current"&&h.workspace.finish===null)throw new $("Native branch and worktree isolation require a persisted --finish preview");let m=h?await ec({paths:l.paths,state:h}):null,g;try{g=await kf({paths:l.paths,name:i,...s?{serialFirstChange:s}:{}})}catch(w){if(!(w instanceof or)||!h)throw w;let k=await Xs({paths:l.paths,name:i}),S=w.peers.length>0?["comet","native","archive",i,"--confirmed","--serial-first",i]:["comet","native","archive",i,"--confirmed"];return{command:"archive",exitCode:73,data:{...k,workspaceFinish:h.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:w.message,commandArgs:S,inputOptions:w.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:w.message}}}h=g.state,!m&&h.workspace.isolation!=="current"&&(m=await ec({paths:l.paths,state:h,archiveDir:g.archiveDir}));let N=null;if(m)try{N=await $f({paths:l.paths,state:g.state,name:i,archiveDir:g.archiveDir,transactionId:g.transactionId,plan:m})}catch(w){if(!(w instanceof lr))throw w;return{command:"archive",exitCode:73,data:{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:w.result,continuation:{disposition:"blocked",reason:w.message,commandArgs:w.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:w.message}}}return ei("archive",{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:N,continuation:sr(g.state)},`Archived Native change ${i} to ${g.archiveDir}
|
|
212
|
+
`)}if(s)throw new $("--serial-first is only valid for portable Native changes");if(!r&&c)throw new $("--finish is only valid with --dry-run");if(nc(e),r)return{command:"archive --dry-run",exitCode:65,data:{change:i,migrationRequired:!0,repairCommand:`comet native doctor ${i} --repair`},error:{code:"invalid-data",message:`Native active change ${i} must migrate before Archive preview`}};let p=await Af({paths:l.paths,name:i});return ei("archive",{migration:{from:"legacy",to:p.schema,completed:!0},state:p,continuation:sr(p)},`Migrated Native change ${i}; follow the returned portable continuation before Archive
|
|
213
|
+
`)}function xk(e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
214
|
+
`}}async function Xf(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s,c;try{dr(n,"--json"),s=Zt(n,"--project-root");let d=[...n,...a],f=await Jf(s);c=await t(d,f)}catch(d){c=Uf(e,d)}let l=o?xk(c):Kf(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
|
|
215
215
|
`)?"":`
|
|
216
|
-
`)),l.exitCode}process.exitCode=await
|
|
216
|
+
`)),l.exitCode}process.exitCode=await Xf("archive",Yf);
|