@rpamis/comet 0.4.0-beta.14 → 0.4.0-beta.16
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 +13 -1
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/SKILL.md +6 -5
- package/assets/skills/comet/reference/subagent-dispatch.md +2 -4
- package/assets/skills/comet/rules/comet-phase-guard.en.md +4 -3
- package/assets/skills/comet/rules/comet-phase-guard.md +4 -3
- package/assets/skills/comet/rules/comet-workflow-guard.en.md +1 -1
- package/assets/skills/comet/rules/comet-workflow-guard.md +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +88 -88
- package/assets/skills/comet/scripts/comet-guard.mjs +126 -126
- package/assets/skills/comet/scripts/comet-handoff.mjs +88 -88
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +91 -89
- package/assets/skills/comet/scripts/comet-hook-router.mjs +124 -116
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +72 -72
- package/assets/skills/comet/scripts/comet-runtime.mjs +188 -185
- package/assets/skills/comet/scripts/comet-state.mjs +108 -107
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +97 -97
- package/assets/skills/comet-any/SKILL.md +1 -1
- package/assets/skills/comet-any/reference/authoring-subagents.md +3 -11
- package/assets/skills/comet-any/reference/subagents/pause-points-author.md +1 -4
- package/assets/skills/comet-any/reference/subagents/reference-author.md +1 -4
- package/assets/skills/comet-any/reference/subagents/script-author.md +1 -4
- package/assets/skills/comet-any/reference/subagents/skill-core-author.md +1 -4
- package/assets/skills/comet-any/reference/subagents/skill-reviewer.md +1 -4
- package/assets/skills/comet-any/reference/subagents/workflow-entry-author.md +1 -4
- package/assets/skills/comet-build/SKILL.md +2 -2
- package/assets/skills/comet-native/SKILL.md +85 -11
- package/assets/skills/comet-native/reference/artifacts.md +3 -1
- package/assets/skills/comet-native/reference/commands.md +15 -6
- package/assets/skills/comet-native/reference/recovery.md +12 -1
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +124 -118
- package/assets/skills/comet-native/scripts/comet-native-check.mjs +116 -110
- package/assets/skills/comet-native/scripts/comet-native-checkpoint.mjs +110 -110
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +121 -121
- package/assets/skills/comet-native/scripts/comet-native-evidence.mjs +83 -83
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +88 -82
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +85 -85
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +114 -114
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +122 -122
- package/assets/skills/comet-native/scripts/comet-native-receipt.mjs +124 -116
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +110 -110
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +154 -152
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +110 -110
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +80 -80
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +112 -112
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +107 -107
- package/assets/skills-zh/comet/SKILL.md +3 -3
- package/assets/skills-zh/comet/reference/subagent-dispatch.md +2 -4
- package/assets/skills-zh/comet-any/SKILL.md +1 -1
- package/assets/skills-zh/comet-any/reference/authoring-subagents.md +3 -14
- package/assets/skills-zh/comet-any/reference/subagents/pause-points-author.md +1 -4
- package/assets/skills-zh/comet-any/reference/subagents/reference-author.md +1 -4
- package/assets/skills-zh/comet-any/reference/subagents/script-author.md +1 -4
- package/assets/skills-zh/comet-any/reference/subagents/skill-core-author.md +1 -4
- package/assets/skills-zh/comet-any/reference/subagents/skill-reviewer.md +1 -4
- package/assets/skills-zh/comet-any/reference/subagents/workflow-entry-author.md +1 -4
- package/assets/skills-zh/comet-build/SKILL.md +2 -2
- package/assets/skills-zh/comet-native/SKILL.md +86 -12
- package/assets/skills-zh/comet-native/reference/artifacts.md +3 -1
- package/assets/skills-zh/comet-native/reference/commands.md +17 -8
- package/assets/skills-zh/comet-native/reference/recovery.md +14 -3
- package/bin/fast-runtime-router.js +1 -0
- package/dist/app/cli/index.js +1 -0
- package/dist/app/cli/index.js.map +1 -1
- package/dist/app/commands/doctor.d.ts.map +1 -1
- package/dist/app/commands/doctor.js +146 -39
- package/dist/app/commands/doctor.js.map +1 -1
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +43 -12
- 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 +42 -9
- package/dist/app/commands/update.js.map +1 -1
- package/dist/app/commands/workflow.d.ts +1 -0
- package/dist/app/commands/workflow.d.ts.map +1 -1
- package/dist/app/commands/workflow.js +9 -2
- package/dist/app/commands/workflow.js.map +1 -1
- package/dist/domains/comet-classic/classic-evidence.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-evidence.js +45 -9
- package/dist/domains/comet-classic/classic-evidence.js.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard.d.ts +5 -1
- package/dist/domains/comet-classic/classic-hook-guard.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard.js +104 -20
- package/dist/domains/comet-classic/classic-hook-guard.js.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.d.ts +4 -3
- package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.js +13 -9
- package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
- package/dist/domains/comet-classic/classic-layout.d.ts +2 -11
- package/dist/domains/comet-classic/classic-layout.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout.js +22 -28
- package/dist/domains/comet-classic/classic-layout.js.map +1 -1
- package/dist/domains/comet-classic/classic-plan-readiness.d.ts +12 -0
- package/dist/domains/comet-classic/classic-plan-readiness.d.ts.map +1 -0
- package/dist/domains/comet-classic/classic-plan-readiness.js +26 -0
- package/dist/domains/comet-classic/classic-plan-readiness.js.map +1 -0
- package/dist/domains/comet-classic/classic-project-config.d.ts +1 -0
- package/dist/domains/comet-classic/classic-project-config.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-project-config.js +13 -7
- package/dist/domains/comet-classic/classic-project-config.js.map +1 -1
- package/dist/domains/comet-classic/classic-root-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-root-command.js +6 -1
- package/dist/domains/comet-classic/classic-root-command.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 +58 -7
- package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
- package/dist/domains/comet-entry/hook-adapter.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-adapter.js +19 -2
- package/dist/domains/comet-entry/hook-adapter.js.map +1 -1
- package/dist/domains/comet-entry/hook-project-root.d.ts +3 -0
- package/dist/domains/comet-entry/hook-project-root.d.ts.map +1 -0
- package/dist/domains/comet-entry/hook-project-root.js +62 -0
- package/dist/domains/comet-entry/hook-project-root.js.map +1 -0
- package/dist/domains/comet-entry/hook-router-entry.d.ts +2 -1
- package/dist/domains/comet-entry/hook-router-entry.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-router-entry.js +6 -4
- package/dist/domains/comet-entry/hook-router-entry.js.map +1 -1
- package/dist/domains/comet-entry/hook-router.d.ts +2 -0
- package/dist/domains/comet-entry/hook-router.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-router.js +45 -9
- package/dist/domains/comet-entry/hook-router.js.map +1 -1
- package/dist/domains/comet-entry/hook-types.d.ts +1 -0
- package/dist/domains/comet-entry/hook-types.d.ts.map +1 -1
- package/dist/domains/comet-entry/project-activation.d.ts +12 -0
- package/dist/domains/comet-entry/project-activation.d.ts.map +1 -0
- package/dist/domains/comet-entry/project-activation.js +109 -0
- package/dist/domains/comet-entry/project-activation.js.map +1 -0
- package/dist/domains/comet-entry/resume-probe.d.ts.map +1 -1
- package/dist/domains/comet-entry/resume-probe.js +47 -26
- package/dist/domains/comet-entry/resume-probe.js.map +1 -1
- package/dist/domains/comet-entry/types.d.ts +1 -1
- package/dist/domains/comet-entry/types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-archive-command.js +43 -1
- package/dist/domains/comet-native/native-archive-command.js.map +1 -1
- package/dist/domains/comet-native/native-archive-inspection.d.ts.map +1 -1
- package/dist/domains/comet-native/native-archive-inspection.js +11 -0
- package/dist/domains/comet-native/native-archive-inspection.js.map +1 -1
- package/dist/domains/comet-native/native-archive-preflight.d.ts +10 -0
- package/dist/domains/comet-native/native-archive-preflight.d.ts.map +1 -1
- package/dist/domains/comet-native/native-archive-preflight.js +44 -0
- package/dist/domains/comet-native/native-archive-preflight.js.map +1 -1
- package/dist/domains/comet-native/native-change.d.ts +18 -1
- package/dist/domains/comet-native/native-change.d.ts.map +1 -1
- package/dist/domains/comet-native/native-change.js +72 -3
- package/dist/domains/comet-native/native-change.js.map +1 -1
- package/dist/domains/comet-native/native-check.d.ts.map +1 -1
- package/dist/domains/comet-native/native-check.js +13 -1
- package/dist/domains/comet-native/native-check.js.map +1 -1
- package/dist/domains/comet-native/native-cli-shared.d.ts +2 -2
- package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-shared.js +24 -3
- package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
- package/dist/domains/comet-native/native-conflict-inspection.d.ts +3 -1
- package/dist/domains/comet-native/native-conflict-inspection.d.ts.map +1 -1
- package/dist/domains/comet-native/native-conflict-inspection.js +20 -10
- package/dist/domains/comet-native/native-conflict-inspection.js.map +1 -1
- package/dist/domains/comet-native/native-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-continuation.js +16 -0
- package/dist/domains/comet-native/native-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-diagnostics.d.ts +2 -0
- package/dist/domains/comet-native/native-diagnostics.d.ts.map +1 -1
- package/dist/domains/comet-native/native-diagnostics.js +43 -32
- package/dist/domains/comet-native/native-diagnostics.js.map +1 -1
- package/dist/domains/comet-native/native-evidence-storage.d.ts +6 -0
- package/dist/domains/comet-native/native-evidence-storage.d.ts.map +1 -1
- package/dist/domains/comet-native/native-evidence-storage.js +24 -0
- package/dist/domains/comet-native/native-evidence-storage.js.map +1 -1
- package/dist/domains/comet-native/native-findings.d.ts.map +1 -1
- package/dist/domains/comet-native/native-findings.js +36 -0
- package/dist/domains/comet-native/native-findings.js.map +1 -1
- package/dist/domains/comet-native/native-hook-guard.js +2 -2
- package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
- package/dist/domains/comet-native/native-new-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-new-command.js +22 -7
- package/dist/domains/comet-native/native-new-command.js.map +1 -1
- package/dist/domains/comet-native/native-receipt-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-receipt-command.js +14 -1
- package/dist/domains/comet-native/native-receipt-command.js.map +1 -1
- package/dist/domains/comet-native/native-receipt-errors.d.ts +23 -0
- package/dist/domains/comet-native/native-receipt-errors.d.ts.map +1 -0
- package/dist/domains/comet-native/native-receipt-errors.js +9 -0
- package/dist/domains/comet-native/native-receipt-errors.js.map +1 -0
- package/dist/domains/comet-native/native-receipt-refresh.d.ts +3 -0
- package/dist/domains/comet-native/native-receipt-refresh.d.ts.map +1 -1
- package/dist/domains/comet-native/native-receipt-refresh.js +13 -2
- package/dist/domains/comet-native/native-receipt-refresh.js.map +1 -1
- package/dist/domains/comet-native/native-root-move.d.ts.map +1 -1
- package/dist/domains/comet-native/native-root-move.js +54 -1
- package/dist/domains/comet-native/native-root-move.js.map +1 -1
- package/dist/domains/comet-native/native-snapshot.d.ts.map +1 -1
- package/dist/domains/comet-native/native-snapshot.js +71 -14
- package/dist/domains/comet-native/native-snapshot.js.map +1 -1
- package/dist/domains/comet-native/native-transitions.d.ts.map +1 -1
- package/dist/domains/comet-native/native-transitions.js +74 -42
- package/dist/domains/comet-native/native-transitions.js.map +1 -1
- package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts +37 -4
- package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-verification-receipt-runtime.js +192 -4
- package/dist/domains/comet-native/native-verification-receipt-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-verification-runtime.d.ts +27 -1
- package/dist/domains/comet-native/native-verification-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-verification-runtime.js +29 -6
- package/dist/domains/comet-native/native-verification-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-workspace.d.ts +39 -3
- package/dist/domains/comet-native/native-workspace.d.ts.map +1 -1
- package/dist/domains/comet-native/native-workspace.js +200 -8
- package/dist/domains/comet-native/native-workspace.js.map +1 -1
- package/dist/domains/dashboard/collector.d.ts +26 -1
- package/dist/domains/dashboard/collector.d.ts.map +1 -1
- package/dist/domains/dashboard/collector.js +381 -1
- package/dist/domains/dashboard/collector.js.map +1 -1
- package/dist/domains/dashboard/native-adapter.d.ts +15 -0
- package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
- package/dist/domains/dashboard/native-adapter.js +1 -1
- package/dist/domains/dashboard/native-adapter.js.map +1 -1
- package/dist/domains/dashboard/native-collector.d.ts +26 -1
- package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
- package/dist/domains/dashboard/native-collector.js +284 -5
- package/dist/domains/dashboard/native-collector.js.map +1 -1
- package/dist/domains/dashboard/server.d.ts.map +1 -1
- package/dist/domains/dashboard/server.js +92 -3
- package/dist/domains/dashboard/server.js.map +1 -1
- package/dist/domains/dashboard/types.d.ts +41 -1
- package/dist/domains/dashboard/types.d.ts.map +1 -1
- package/dist/domains/dashboard/verify-parser.d.ts +1 -0
- package/dist/domains/dashboard/verify-parser.d.ts.map +1 -1
- package/dist/domains/dashboard/verify-parser.js +8 -4
- package/dist/domains/dashboard/verify-parser.js.map +1 -1
- package/dist/domains/dashboard/web/assets/{arc-mNt_SS1l.js → arc-ClrSujVb.js} +1 -1
- package/dist/domains/dashboard/web/assets/{architectureDiagram-3BPJPVTR-Bc5akVD6.js → architectureDiagram-3BPJPVTR-B4A_t84A.js} +1 -1
- package/dist/domains/dashboard/web/assets/{blockDiagram-GPEHLZMM-C43zhVBe.js → blockDiagram-GPEHLZMM-D72u2953.js} +1 -1
- package/dist/domains/dashboard/web/assets/{c4Diagram-AAUBKEIU-dToETarK.js → c4Diagram-AAUBKEIU-Ca5zba3N.js} +1 -1
- package/dist/domains/dashboard/web/assets/channel-B_u-_i2t.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-2J33WTMH-C0oO137R.js → chunk-2J33WTMH-CCVPBm0J.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-4BX2VUAB-CGms1fgI.js → chunk-4BX2VUAB-JYluRsP-.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-55IACEB6-Bugl8v6f.js → chunk-55IACEB6-DfYm7pN7.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-727SXJPM-8ATNMlBG.js → chunk-727SXJPM-CwghIMO9.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-AQP2D5EJ-BNYjSSqU.js → chunk-AQP2D5EJ-BA_zgMXZ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-FMBD7UC4-_nJAqSbe.js → chunk-FMBD7UC4-BAJLB5V6.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-ND2GUHAM-lyxYm5NX.js → chunk-ND2GUHAM-Bj6HWRwi.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-QZHKN3VN-PUMVeWpd.js → chunk-QZHKN3VN-B1kXfg5N.js} +1 -1
- package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-BpA7BPgX.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-BpA7BPgX.js +1 -0
- package/dist/domains/dashboard/web/assets/{cose-bilkent-S5V4N54A-DzMqjexn.js → cose-bilkent-S5V4N54A-BBrkuiAU.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-B67ET0eq.js → cynefin-VYW2F7L2-DlFhgQHt.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dagre-BM42HDAG-CQPMvRLK.js → dagre-BM42HDAG-B0Bk5oiP.js} +1 -1
- package/dist/domains/dashboard/web/assets/{demo-BuVau32v.js → demo-DZYPLZpF.js} +2 -2
- package/dist/domains/dashboard/web/assets/{diagram-2AECGRRQ-BRpLrFHM.js → diagram-2AECGRRQ-tvTUiBA2.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-5GNKFQAL-CPGWuGrE.js → diagram-5GNKFQAL-BZfcK29q.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-KO2AKTUF-D2wpX2iO.js → diagram-KO2AKTUF-BQahyP-C.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-LMA3HP47-D54mAbDu.js → diagram-LMA3HP47-D5bJnW2C.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-OG6HWLK6-ZGQDpSs_.js → diagram-OG6HWLK6-DTwWdzWJ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{erDiagram-TEJ5UH35-C3qDo7sd.js → erDiagram-TEJ5UH35-BbvrdCp9.js} +1 -1
- package/dist/domains/dashboard/web/assets/{flowDiagram-I6XJVG4X-B7hStPd9.js → flowDiagram-I6XJVG4X-DgbR7Tcc.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ganttDiagram-6RSMTGT7-IqcLFbTK.js → ganttDiagram-6RSMTGT7-wWMOA7F4.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraphDiagram-PVQCEYII-YrMZpzUu.js → gitGraphDiagram-PVQCEYII-DCxvMAUJ.js} +1 -1
- package/dist/domains/dashboard/web/assets/index-Bk1o-4VO.css +1 -0
- package/dist/domains/dashboard/web/assets/{index-icxk8_BP.js → index-Blit0P5Z.js} +1 -1
- package/dist/domains/dashboard/web/assets/index-g8vyW0R_.js +257 -0
- package/dist/domains/dashboard/web/assets/{infoDiagram-5YYISTIA-CcIgGK_7.js → infoDiagram-5YYISTIA-9qXEkzDe.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ishikawaDiagram-YF4QCWOH-1x3rNjGP.js → ishikawaDiagram-YF4QCWOH-Dkf5othW.js} +1 -1
- package/dist/domains/dashboard/web/assets/{journeyDiagram-JHISSGLW-B2XiqMNP.js → journeyDiagram-JHISSGLW-C2_IkO4s.js} +1 -1
- package/dist/domains/dashboard/web/assets/{kanban-definition-UN3LZRKU-x46cGuo3.js → kanban-definition-UN3LZRKU-BxWgu4DL.js} +1 -1
- package/dist/domains/dashboard/web/assets/{linear-DFLqGZWl.js → linear-Dkr6p-Ro.js} +1 -1
- package/dist/domains/dashboard/web/assets/{mermaid.core-g3J6BACc.js → mermaid.core-DZUcsoG4.js} +4 -4
- package/dist/domains/dashboard/web/assets/{mindmap-definition-RKZ34NQL-CTdeKmcX.js → mindmap-definition-RKZ34NQL-C9xyxGfa.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pieDiagram-4H26LBE5-C_obwjIf.js → pieDiagram-4H26LBE5-Dn67tdOF.js} +1 -1
- package/dist/domains/dashboard/web/assets/{quadrantDiagram-W4KKPZXB-B6Gnfz9M.js → quadrantDiagram-W4KKPZXB-Cy6iOcxc.js} +1 -1
- package/dist/domains/dashboard/web/assets/{requirementDiagram-4Y6WPE33-nX4PObnB.js → requirementDiagram-4Y6WPE33-B_gZONhx.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sankeyDiagram-5OEKKPKP-QjDwwHgl.js → sankeyDiagram-5OEKKPKP-C3u-4dOk.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sequenceDiagram-3UESZ5HK-BEEe0j6B.js → sequenceDiagram-3UESZ5HK-Xd3ByTVF.js} +1 -1
- package/dist/domains/dashboard/web/assets/{stateDiagram-AJRCARHV-CXfAaBgM.js → stateDiagram-AJRCARHV-CJGHL7Up.js} +1 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-rKvBgr6I.js +1 -0
- package/dist/domains/dashboard/web/assets/{timeline-definition-PNZ67QCA-BOzX2EnD.js → timeline-definition-PNZ67QCA-DvONX2YQ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{vennDiagram-CIIHVFJN-C40vhXRq.js → vennDiagram-CIIHVFJN-B-L4qWy4.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardleyDiagram-YWT4CUSO-B1rm89JH.js → wardleyDiagram-YWT4CUSO-cf39WX2o.js} +1 -1
- package/dist/domains/dashboard/web/assets/{xychartDiagram-2RQKCTM6-BlMr59qK.js → xychartDiagram-2RQKCTM6-Dk1vcm3u.js} +1 -1
- package/dist/domains/dashboard/web/index.html +2 -2
- package/dist/domains/factory/package.d.ts.map +1 -1
- package/dist/domains/factory/package.js +7 -22
- package/dist/domains/factory/package.js.map +1 -1
- package/dist/domains/skill/hook-lifecycle.d.ts +9 -0
- package/dist/domains/skill/hook-lifecycle.d.ts.map +1 -0
- package/dist/domains/skill/hook-lifecycle.js +48 -0
- package/dist/domains/skill/hook-lifecycle.js.map +1 -0
- package/dist/domains/skill/platform-inspect.d.ts +2 -0
- package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
- package/dist/domains/skill/platform-inspect.js +170 -32
- package/dist/domains/skill/platform-inspect.js.map +1 -1
- package/dist/domains/skill/platform-install.d.ts +21 -1
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +142 -31
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/domains/skill/project-hook-projection.d.ts +14 -0
- package/dist/domains/skill/project-hook-projection.d.ts.map +1 -0
- package/dist/domains/skill/project-hook-projection.js +41 -0
- package/dist/domains/skill/project-hook-projection.js.map +1 -0
- package/dist/domains/skill/project-instructions.d.ts +3 -0
- package/dist/domains/skill/project-instructions.d.ts.map +1 -1
- package/dist/domains/skill/project-instructions.js +8 -0
- package/dist/domains/skill/project-instructions.js.map +1 -1
- package/dist/domains/skill/uninstall.d.ts.map +1 -1
- package/dist/domains/skill/uninstall.js +50 -11
- package/dist/domains/skill/uninstall.js.map +1 -1
- package/dist/domains/workflow-contract/global-config.d.ts +10 -0
- package/dist/domains/workflow-contract/global-config.d.ts.map +1 -0
- package/dist/domains/workflow-contract/global-config.js +117 -0
- package/dist/domains/workflow-contract/global-config.js.map +1 -0
- package/dist/domains/workflow-contract/hook-target-scope.d.ts +6 -0
- package/dist/domains/workflow-contract/hook-target-scope.d.ts.map +1 -0
- package/dist/domains/workflow-contract/hook-target-scope.js +51 -0
- package/dist/domains/workflow-contract/hook-target-scope.js.map +1 -0
- package/dist/domains/workflow-contract/index.d.ts +1 -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/types.d.ts +3 -0
- package/dist/domains/workflow-contract/types.d.ts.map +1 -1
- package/dist/platform/paths/git-worktree.d.ts +4 -1
- package/dist/platform/paths/git-worktree.d.ts.map +1 -1
- package/dist/platform/paths/git-worktree.js +34 -1
- package/dist/platform/paths/git-worktree.js.map +1 -1
- package/eval/local/tests/scaffold/test_utils.py +74 -0
- package/eval/scaffold/shell/docker.sh +5 -0
- package/package.json +7 -5
- package/dist/domains/dashboard/web/assets/channel-b2wWDG4F.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-B9SWZywo.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-B9SWZywo.js +0 -1
- package/dist/domains/dashboard/web/assets/index-DhtBssCt.js +0 -257
- package/dist/domains/dashboard/web/assets/index-pr3axVDI.css +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-CD3nS4cC.js +0 -1
|
@@ -1,179 +1,187 @@
|
|
|
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 Bm=Object.create;var Vl=Object.defineProperty;var Dm=Object.getOwnPropertyDescriptor;var qm=Object.getOwnPropertyNames;var Vm=Object.getPrototypeOf,Wm=Object.prototype.hasOwnProperty;var Kn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,i)=>(typeof require<"u"?require:e)[i]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var C=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(i){throw e=0,i}};var zm=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qm(e))!Wm.call(t,r)&&r!==i&&Vl(t,r,{get:()=>e[r],enumerable:!(n=Dm(e,r))||n.enumerable});return t};var ho=(t,e,i)=>(i=t!=null?Bm(Vm(t)):{},zm(e||!t||!t.__esModule?Vl(i,"default",{value:t,enumerable:!0}):i,t));var M=C(re=>{"use strict";var mo=Symbol.for("yaml.alias"),zl=Symbol.for("yaml.document"),Un=Symbol.for("yaml.map"),Jl=Symbol.for("yaml.pair"),vo=Symbol.for("yaml.scalar"),Yn=Symbol.for("yaml.seq"),Qe=Symbol.for("yaml.node.type"),Um=t=>!!t&&typeof t=="object"&&t[Qe]===mo,Ym=t=>!!t&&typeof t=="object"&&t[Qe]===zl,Xm=t=>!!t&&typeof t=="object"&&t[Qe]===Un,Qm=t=>!!t&&typeof t=="object"&&t[Qe]===Jl,Gl=t=>!!t&&typeof t=="object"&&t[Qe]===vo,Zm=t=>!!t&&typeof t=="object"&&t[Qe]===Yn;function Kl(t){if(t&&typeof t=="object")switch(t[Qe]){case Un:case Yn:return!0}return!1}function ev(t){if(t&&typeof t=="object")switch(t[Qe]){case mo:case Un:case vo:case Yn:return!0}return!1}var tv=t=>(Gl(t)||Kl(t))&&!!t.anchor;re.ALIAS=mo;re.DOC=zl;re.MAP=Un;re.NODE_TYPE=Qe;re.PAIR=Jl;re.SCALAR=vo;re.SEQ=Yn;re.hasAnchor=tv;re.isAlias=Um;re.isCollection=Kl;re.isDocument=Ym;re.isMap=Xm;re.isNode=ev;re.isPair=Qm;re.isScalar=Gl;re.isSeq=Zm});var Ti=C(go=>{"use strict";var ne=M(),he=Symbol("break visit"),Ul=Symbol("skip children"),We=Symbol("remove node");function Xn(t,e){let i=Yl(e);ne.isDocument(t)?Zt(null,t.contents,i,Object.freeze([t]))===We&&(t.contents=null):Zt(null,t,i,Object.freeze([]))}Xn.BREAK=he;Xn.SKIP=Ul;Xn.REMOVE=We;function Zt(t,e,i,n){let r=Xl(t,e,i,n);if(ne.isNode(r)||ne.isPair(r))return Ql(t,n,r),Zt(t,r,i,n);if(typeof r!="symbol"){if(ne.isCollection(e)){n=Object.freeze(n.concat(e));for(let a=0;a<e.items.length;++a){let o=Zt(a,e.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===We&&(e.items.splice(a,1),a-=1)}}}else if(ne.isPair(e)){n=Object.freeze(n.concat(e));let a=Zt("key",e.key,i,n);if(a===he)return he;a===We&&(e.key=null);let o=Zt("value",e.value,i,n);if(o===he)return he;o===We&&(e.value=null)}}return r}async function Qn(t,e){let i=Yl(e);ne.isDocument(t)?await ei(null,t.contents,i,Object.freeze([t]))===We&&(t.contents=null):await ei(null,t,i,Object.freeze([]))}Qn.BREAK=he;Qn.SKIP=Ul;Qn.REMOVE=We;async function ei(t,e,i,n){let r=await Xl(t,e,i,n);if(ne.isNode(r)||ne.isPair(r))return Ql(t,n,r),ei(t,r,i,n);if(typeof r!="symbol"){if(ne.isCollection(e)){n=Object.freeze(n.concat(e));for(let a=0;a<e.items.length;++a){let o=await ei(a,e.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===We&&(e.items.splice(a,1),a-=1)}}}else if(ne.isPair(e)){n=Object.freeze(n.concat(e));let a=await ei("key",e.key,i,n);if(a===he)return he;a===We&&(e.key=null);let o=await ei("value",e.value,i,n);if(o===he)return he;o===We&&(e.value=null)}}return r}function Yl(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function Xl(t,e,i,n){if(typeof i=="function")return i(t,e,n);if(ne.isMap(e))return i.Map?.(t,e,n);if(ne.isSeq(e))return i.Seq?.(t,e,n);if(ne.isPair(e))return i.Pair?.(t,e,n);if(ne.isScalar(e))return i.Scalar?.(t,e,n);if(ne.isAlias(e))return i.Alias?.(t,e,n)}function Ql(t,e,i){let n=e[e.length-1];if(ne.isCollection(n))n.items[t]=i;else if(ne.isPair(n))t==="key"?n.key=i:n.value=i;else if(ne.isDocument(n))n.contents=i;else{let r=ne.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}go.visit=Xn;go.visitAsync=Qn});var wo=C(eu=>{"use strict";var Zl=M(),iv=Ti(),nv={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},rv=t=>t.replace(/[!,[\]{}]/g,e=>nv[e]),Ii=class t{constructor(e,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,i)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,i){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[a,o]=n;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=n;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${r}`,!0),!1}}tagName(e,i){if(e==="!")return"!";if(e[0]!=="!")return i(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||i(`The ${e} tag has no suffix`);let a=this.tags[n];if(a)try{return a+decodeURIComponent(r)}catch(o){return i(String(o)),null}return n==="!"?e:(i(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[i,n]of Object.entries(this.tags))if(e.startsWith(n))return i+rv(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),r;if(e&&n.length>0&&Zl.isNode(e.contents)){let a={};iv.visit(e.contents,(o,s)=>{Zl.isNode(s)&&s.tag&&(a[s.tag]=!0)}),r=Object.keys(a)}else r=[];for(let[a,o]of n)a==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
|
|
5
|
+
`)}};Ii.defaultYaml={explicit:!1,version:"1.2"};Ii.defaultTags={"!!":"tag:yaml.org,2002:"};eu.Directives=Ii});var Zn=C(_i=>{"use strict";var tu=M(),av=Ti();function ov(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(i)}return!0}function iu(t){let e=new Set;return av.visit(t,{Value(i,n){n.anchor&&e.add(n.anchor)}}),e}function nu(t,e){for(let i=1;;++i){let n=`${t}${i}`;if(!e.has(n))return n}}function sv(t,e){let i=[],n=new Map,r=null;return{onAnchor:a=>{i.push(a),r??(r=iu(t));let o=nu(e,r);return r.add(o),o},setAnchors:()=>{for(let a of i){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(tu.isScalar(o.node)||tu.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:n}}_i.anchorIsValid=ov;_i.anchorNames=iu;_i.createNodeAnchors=sv;_i.findNewAnchor=nu});var yo=C(ru=>{"use strict";function ji(t,e,i,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let r=0,a=n.length;r<a;++r){let o=n[r],s=ji(t,n,String(r),o);s===void 0?delete n[r]:s!==o&&(n[r]=s)}else if(n instanceof Map)for(let r of Array.from(n.keys())){let a=n.get(r),o=ji(t,n,r,a);o===void 0?n.delete(r):o!==a&&n.set(r,o)}else if(n instanceof Set)for(let r of Array.from(n)){let a=ji(t,n,r,r);a===void 0?n.delete(r):a!==r&&(n.delete(r),n.add(a))}else for(let[r,a]of Object.entries(n)){let o=ji(t,n,r,a);o===void 0?delete n[r]:o!==a&&(n[r]=o)}return t.call(e,i,n)}ru.applyReviver=ji});var ht=C(ou=>{"use strict";var cv=M();function au(t,e,i){if(Array.isArray(t))return t.map((n,r)=>au(n,String(r),i));if(t&&typeof t.toJSON=="function"){if(!i||!cv.hasAnchor(t))return t.toJSON(e,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(t,n),i.onCreate=a=>{n.res=a,delete i.onCreate};let r=t.toJSON(e,i);return i.onCreate&&i.onCreate(r),r}return typeof t=="bigint"&&!i?.keep?Number(t):t}ou.toJS=au});var er=C(cu=>{"use strict";var lv=yo(),su=M(),uv=ht(),No=class{constructor(e){Object.defineProperty(this,su.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:n,onAnchor:r,reviver:a}={}){if(!su.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},s=uv.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof a=="function"?lv.applyReviver(a,{"":s},"",s):s}};cu.NodeBase=No});var Oi=C(lu=>{"use strict";var fv=Zn(),dv=Ti(),ti=M(),hv=er(),pv=ht(),bo=class extends hv.NodeBase{constructor(e){super(ti.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;i?.aliasResolveCache?n=i.aliasResolveCache:(n=[],dv.visit(e,{Node:(a,o)=>{(ti.isAlias(o)||ti.hasAnchor(o))&&n.push(o)}}),i&&(i.aliasResolveCache=n));let r;for(let a of n){if(a===this)break;a.anchor===this.source&&(r=a)}return r}toJSON(e,i){if(!i)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:a}=i,o=this.resolve(r,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=n.get(o);if(s||(pv.toJS(o,null,i),s=n.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=tr(r,o,n)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(e,i,n){let r=`*${this.source}`;if(e){if(fv.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(e.implicitKey)return`${r} `}return r}};function tr(t,e,i){if(ti.isAlias(e)){let n=e.resolve(t),r=i&&n&&i.get(n);return r?r.count*r.aliasCount:0}else if(ti.isCollection(e)){let n=0;for(let r of e.items){let a=tr(t,r,i);a>n&&(n=a)}return n}else if(ti.isPair(e)){let n=tr(t,e.key,i),r=tr(t,e.value,i);return Math.max(n,r)}return 1}lu.Alias=bo});var ee=C(ko=>{"use strict";var mv=M(),vv=er(),gv=ht(),wv=t=>!t||typeof t!="function"&&typeof t!="object",pt=class extends vv.NodeBase{constructor(e){super(mv.SCALAR),this.value=e}toJSON(e,i){return i?.keep?this.value:gv.toJS(this.value,e,i)}toString(){return String(this.value)}};pt.BLOCK_FOLDED="BLOCK_FOLDED";pt.BLOCK_LITERAL="BLOCK_LITERAL";pt.PLAIN="PLAIN";pt.QUOTE_DOUBLE="QUOTE_DOUBLE";pt.QUOTE_SINGLE="QUOTE_SINGLE";ko.Scalar=pt;ko.isScalarValue=wv});var $i=C(fu=>{"use strict";var yv=Oi(),Ht=M(),uu=ee(),Nv="tag:yaml.org,2002:";function bv(t,e,i){if(e){let n=i.filter(a=>a.tag===e),r=n.find(a=>!a.format)??n[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return i.find(n=>n.identify?.(t)&&!n.format)}function kv(t,e,i){if(Ht.isDocument(t)&&(t=t.contents),Ht.isNode(t))return t;if(Ht.isPair(t)){let f=i.schema[Ht.MAP].createNode?.(i.schema,null,i);return f.items.push(t),f}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:n,onAnchor:r,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(n&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=r(t)),new yv.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=Nv+e.slice(2));let l=bv(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let f=new uu.Scalar(t);return c&&(c.node=f),f}l=t instanceof Map?o[Ht.MAP]:Symbol.iterator in Object(t)?o[Ht.SEQ]:o[Ht.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,t,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,t,i):new uu.Scalar(t);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}fu.createNode=kv});var nr=C(ir=>{"use strict";var Sv=$i(),ze=M(),Ev=er();function So(t,e,i){let n=i;for(let r=e.length-1;r>=0;--r){let a=e[r];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=n,n=o}else n=new Map([[a,n]])}return Sv.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var du=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Eo=class extends Ev.NodeBase{constructor(e,i){super(e),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(e){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(i.schema=e),i.items=i.items.map(n=>ze.isNode(n)||ze.isPair(n)?n.clone(e):n),this.range&&(i.range=this.range.slice()),i}addIn(e,i){if(du(e))this.add(i);else{let[n,...r]=e,a=this.get(n,!0);if(ze.isCollection(a))a.addIn(r,i);else if(a===void 0&&this.schema)this.set(n,So(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[i,...n]=e;if(n.length===0)return this.delete(i);let r=this.get(i,!0);if(ze.isCollection(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}getIn(e,i){let[n,...r]=e,a=this.get(n,!0);return r.length===0?!i&&ze.isScalar(a)?a.value:a:ze.isCollection(a)?a.getIn(r,i):void 0}hasAllNullValues(e){return this.items.every(i=>{if(!ze.isPair(i))return!1;let n=i.value;return n==null||e&&ze.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[i,...n]=e;if(n.length===0)return this.has(i);let r=this.get(i,!0);return ze.isCollection(r)?r.hasIn(n):!1}setIn(e,i){let[n,...r]=e;if(r.length===0)this.set(n,i);else{let a=this.get(n,!0);if(ze.isCollection(a))a.setIn(r,i);else if(a===void 0&&this.schema)this.set(n,So(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};ir.Collection=Eo;ir.collectionFromPath=So;ir.isEmptyPath=du});var Hi=C(rr=>{"use strict";var Rv=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Ro(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Cv=(t,e,i)=>t.endsWith(`
|
|
6
|
+
`)?Ro(i,e):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)i===
|
|
10
|
-
`&&p!==" "){let
|
|
11
|
-
`&&
|
|
12
|
-
${e}${t.slice(0,
|
|
13
|
-
${e}${t.slice(
|
|
14
|
-
`);n=e,r=e+1,a=t[r]}return n}
|
|
15
|
-
`){if(a-o>n)return!0;if(o=a+1,r-o<=n)return!1}return!0}function
|
|
8
|
+
`+Ro(i,e):(t.endsWith(" ")?"":" ")+i;rr.indentComment=Ro;rr.lineComment=Cv;rr.stringifyComment=Rv});var pu=C(Mi=>{"use strict";var Pv="flow",Co="block",ar="quoted";function Av(t,e,i="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!r||r<0)return t;r<a&&(a=0);let c=Math.max(1+a,1+r-e.length);if(t.length<=c)return t;let l=[],u={},f=r-e.length;typeof n=="number"&&(n>r-Math.max(2,a)?l.push(0):f=r-n);let d,p,m=!1,h=-1,v=-1,S=-1;i===Co&&(h=hu(t,h,e.length),h!==-1&&(f=h+c));for(let E;E=t[h+=1];){if(i===ar&&E==="\\"){switch(v=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}S=h}if(E===`
|
|
9
|
+
`)i===Co&&(h=hu(t,h,e.length)),f=h+e.length+c,d=void 0;else{if(E===" "&&p&&p!==" "&&p!==`
|
|
10
|
+
`&&p!==" "){let b=t[h+1];b&&b!==" "&&b!==`
|
|
11
|
+
`&&b!==" "&&(d=h)}if(h>=f)if(d)l.push(d),f=d+c,d=void 0;else if(i===ar){for(;p===" "||p===" ";)p=E,E=t[h+=1],m=!0;let b=h>S+1?h-2:v-1;if(u[b])return t;l.push(b),u[b]=!0,f=b+c,d=void 0}else m=!0}p=E}if(m&&s&&s(),l.length===0)return t;o&&o();let N=t.slice(0,l[0]);for(let E=0;E<l.length;++E){let b=l[E],k=l[E+1]||t.length;b===0?N=`
|
|
12
|
+
${e}${t.slice(0,k)}`:(i===ar&&u[b]&&(N+=`${t[b]}\\`),N+=`
|
|
13
|
+
${e}${t.slice(b+1,k)}`)}return N}function hu(t,e,i){let n=e,r=e+1,a=t[r];for(;a===" "||a===" ";)if(e<r+i)a=t[++e];else{do a=t[++e];while(a&&a!==`
|
|
14
|
+
`);n=e,r=e+1,a=t[r]}return n}Mi.FOLD_BLOCK=Co;Mi.FOLD_FLOW=Pv;Mi.FOLD_QUOTED=ar;Mi.foldFlowLines=Av});var Fi=C(mu=>{"use strict";var Te=ee(),mt=pu(),sr=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),cr=t=>/^(%|---|\.\.\.)/m.test(t);function xv(t,e,i){if(!e||e<0)return!1;let n=e-i,r=t.length;if(r<=n)return!1;for(let a=0,o=0;a<r;++a)if(t[a]===`
|
|
15
|
+
`){if(a-o>n)return!0;if(o=a+1,r-o<=n)return!1}return!0}function Li(t,e){let i=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return i;let{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(cr(t)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(n||i[c+2]==='"'||i.length<r)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,n?o:
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(t))return
|
|
20
|
-
${i}`)+"'";return e.implicitKey?n:
|
|
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,n?o:mt.foldFlowLines(o,a,mt.FOLD_QUOTED,sr(e,!1))}function Po(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(t))return Li(t,e);let i=e.indent||(cr(t)?" ":""),n="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return e.implicitKey?n:mt.foldFlowLines(n,i,mt.FOLD_FLOW,sr(e,!1))}function ii(t,e){let{singleQuote:i}=e.options,n;if(i===!1)n=Li;else{let r=t.includes('"'),a=t.includes("'");r&&!a?n=Po:a&&!r?n=Li:n=i?Po:Li}return n(t,e)}var Ao;try{Ao=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{Ao=/\n+(?!\n|$)/g}function or({comment:t,type:e,value:i},n,r,a){let{blockQuote:o,commentString:s,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(i))return ii(i,n);let l=n.indent||(n.forceBlockIndent||cr(i)?" ":""),u=o==="literal"?!0:o==="folded"||e===Te.Scalar.BLOCK_FOLDED?!1:e===Te.Scalar.BLOCK_LITERAL?!0:!xv(i,c,l.length);if(!i)return u?`|
|
|
24
24
|
`:`>
|
|
25
|
-
`;let f,d;for(d=i.length;d>0;--d){let
|
|
26
|
-
`&&
|
|
25
|
+
`;let f,d;for(d=i.length;d>0;--d){let k=i[d-1];if(k!==`
|
|
26
|
+
`&&k!==" "&&k!==" ")break}let p=i.substring(d),m=p.indexOf(`
|
|
27
27
|
`);m===-1?f="-":i===p||m!==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(
|
|
29
|
-
`)
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,
|
|
31
|
-
${l}${
|
|
32
|
-
${l}${
|
|
33
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(f),{compat:p,tags:m}=e.doc.schema;if(m.some(d)||p?.some(d))return
|
|
37
|
-
${e.indent}${s}`:s}
|
|
38
|
-
${s}:`):(v=`${v}:`,d&&(v+=
|
|
39
|
-
`:"",
|
|
40
|
-
${
|
|
41
|
-
`&&
|
|
28
|
+
`&&(p=p.slice(0,-1)),p=p.replace(Ao,`$&${l}`));let h=!1,v,S=-1;for(v=0;v<i.length;++v){let k=i[v];if(k===" ")h=!0;else if(k===`
|
|
29
|
+
`)S=v;else break}let N=i.substring(0,S<v?S+1:v);N&&(i=i.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let b=(h?l?"2":"1":"")+f;if(t&&(b+=" "+s(t.replace(/ ?[\r\n]+/g," ")),r&&r()),!u){let k=i.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,y=sr(n,!0);o!=="folded"&&e!==Te.Scalar.BLOCK_FOLDED&&(y.onOverflow=()=>{g=!0});let w=mt.foldFlowLines(`${N}${k}${p}`,l,mt.FOLD_BLOCK,y);if(!g)return`>${b}
|
|
31
|
+
${l}${w}`}return i=i.replace(/\n+/g,`$&${l}`),`|${b}
|
|
32
|
+
${l}${N}${i}${p}`}function Tv(t,e,i,n){let{type:r,value:a}=t,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=e;if(s&&a.includes(`
|
|
33
|
+
`)||u&&/[[\]{},]/.test(a))return ii(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
+
`)?ii(a,e):or(t,e,i,n);if(!s&&!u&&r!==Te.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return or(t,e,i,n);if(cr(a)){if(c==="")return e.forceBlockIndent=!0,or(t,e,i,n);if(s&&c===l)return ii(a,e)}let f=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(f),{compat:p,tags:m}=e.doc.schema;if(m.some(d)||p?.some(d))return ii(a,e)}return s?f:mt.foldFlowLines(f,c,mt.FOLD_FLOW,sr(e,!1))}function Iv(t,e,i,n){let{implicitKey:r,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==Te.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Te.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Te.Scalar.BLOCK_FOLDED:case Te.Scalar.BLOCK_LITERAL:return r||a?ii(o.value,e):or(o,e,i,n);case Te.Scalar.QUOTE_DOUBLE:return Li(o.value,e);case Te.Scalar.QUOTE_SINGLE:return Po(o.value,e);case Te.Scalar.PLAIN:return Tv(o,e,i,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:f}=e.options,d=r&&u||f;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}mu.stringifyString=Iv});var Bi=C(xo=>{"use strict";var _v=Zn(),vt=M(),jv=Hi(),Ov=Fi();function $v(t,e){let i=Object.assign({blockQuote:!0,commentString:jv.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),n;switch(i.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:t,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:n,options:i}}function Hv(t,e){if(e.tag){let r=t.filter(a=>a.tag===e.tag);if(r.length>0)return r.find(a=>a.format===e.format)??r[0]}let i,n;if(vt.isScalar(e)){n=e.value;let r=t.filter(a=>a.identify?.(n));if(r.length>1){let a=r.filter(o=>o.test);a.length>0&&(r=a)}i=r.find(a=>a.format===e.format)??r.find(a=>!a.format)}else n=e,i=t.find(r=>r.nodeClass&&n instanceof r.nodeClass);if(!i){let r=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${r} value`)}return i}function Mv(t,e,{anchors:i,doc:n}){if(!n.directives)return"";let r=[],a=(vt.isScalar(t)||vt.isCollection(t))&&t.anchor;a&&_v.anchorIsValid(a)&&(i.add(a),r.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}function Lv(t,e,i,n){if(vt.isPair(t))return t.toString(e,i,n);if(vt.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,a=vt.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=Hv(e.doc.schema.tags,a));let o=Mv(a,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof r.stringify=="function"?r.stringify(a,e,i,n):vt.isScalar(a)?Ov.stringifyString(a,e,i,n):a.toString(e,i,n);return o?vt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${e.indent}${s}`:s}xo.createStringifyContext=$v;xo.stringify=Lv});var yu=C(wu=>{"use strict";var Ze=M(),vu=ee(),gu=Bi(),Di=Hi();function Fv({key:t,value:e},i,n,r){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:f}}=i,d=Ze.isNode(t)&&t.comment||null;if(f){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Ze.isCollection(t)||!Ze.isNode(t)&&typeof t=="object"){let y="With simple keys, collection cannot be used as a key value";throw new Error(y)}}let p=!f&&(!t||d&&e==null&&!i.inFlow||Ze.isCollection(t)||(Ze.isScalar(t)?t.type===vu.Scalar.BLOCK_FOLDED||t.type===vu.Scalar.BLOCK_LITERAL:typeof t=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(f||!a),indent:s+c});let m=!1,h=!1,v=gu.stringify(t,i,()=>m=!0,()=>h=!0);if(!p&&!i.inFlow&&v.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||e==null)return m&&n&&n(),v===""?"?":p?`? ${v}`:v}else if(a&&!f||e==null&&p)return v=`? ${v}`,d&&!m?v+=Di.lineComment(v,i.indent,l(d)):h&&r&&r(),v;m&&(d=null),p?(d&&(v+=Di.lineComment(v,i.indent,l(d))),v=`? ${v}
|
|
38
|
+
${s}:`):(v=`${v}:`,d&&(v+=Di.lineComment(v,i.indent,l(d))));let S,N,E;Ze.isNode(e)?(S=!!e.spaceBefore,N=e.commentBefore,E=e.comment):(S=!1,N=null,E=null,e&&typeof e=="object"&&(e=o.createNode(e))),i.implicitKey=!1,!p&&!d&&Ze.isScalar(e)&&(i.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&Ze.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(i.indent=i.indent.substring(2));let b=!1,k=gu.stringify(e,i,()=>b=!0,()=>h=!0),g=" ";if(d||S||N){if(g=S?`
|
|
39
|
+
`:"",N){let y=l(N);g+=`
|
|
40
|
+
${Di.indentComment(y,i.indent)}`}k===""&&!i.inFlow?g===`
|
|
41
|
+
`&&E&&(g=`
|
|
42
42
|
|
|
43
43
|
`):g+=`
|
|
44
|
-
${i.indent}`}else if(!p&&
|
|
45
|
-
`),R=
|
|
46
|
-
${i.indent}`)}}else(
|
|
47
|
-
`)&&(g="");return v+=g+
|
|
44
|
+
${i.indent}`}else if(!p&&Ze.isCollection(e)){let y=k[0],w=k.indexOf(`
|
|
45
|
+
`),R=w!==-1,_=i.inFlow??e.flow??e.items.length===0;if(R||!_){let D=!1;if(R&&(y==="&"||y==="!")){let H=k.indexOf(" ");y==="&"&&H!==-1&&H<w&&k[H+1]==="!"&&(H=k.indexOf(" ",H+1)),(H===-1||w<H)&&(D=!0)}D||(g=`
|
|
46
|
+
${i.indent}`)}}else(k===""||k[0]===`
|
|
47
|
+
`)&&(g="");return v+=g+k,i.inFlow?b&&n&&n():E&&!b?v+=Di.lineComment(v,i.indent,l(E)):h&&r&&r(),v}wu.stringifyPair=Fv});var Io=C(To=>{"use strict";var Nu=Kn("process");function Bv(t,...e){t==="debug"&&console.log(...e)}function Dv(t,e){(t==="debug"||t==="warn")&&(typeof Nu.emitWarning=="function"?Nu.emitWarning(e):console.warn(e))}To.debug=Bv;To.warn=Dv});var hr=C(dr=>{"use strict";var fr=M(),bu=ee(),lr="<<",ur={identify:t=>t===lr||typeof t=="symbol"&&t.description===lr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new bu.Scalar(Symbol(lr)),{addToJSMap:ku}),stringify:()=>lr},qv=(t,e)=>(ur.identify(e)||fr.isScalar(e)&&(!e.type||e.type===bu.Scalar.PLAIN)&&ur.identify(e.value))&&t?.doc.schema.tags.some(i=>i.tag===ur.tag&&i.default);function ku(t,e,i){let n=Su(t,i);if(fr.isSeq(n))for(let r of n.items)_o(t,e,r);else if(Array.isArray(n))for(let r of n)_o(t,e,r);else _o(t,e,n)}function _o(t,e,i){let n=Su(t,i);if(!fr.isMap(n))throw new Error("Merge sources must be maps or map aliases");let r=n.toJSON(null,t,Map);for(let[a,o]of r)e instanceof Map?e.has(a)||e.set(a,o):e instanceof Set?e.add(a):Object.prototype.hasOwnProperty.call(e,a)||Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Su(t,e){return t&&fr.isAlias(e)?e.resolve(t.doc,t):e}dr.addMergeToJSMap=ku;dr.isMergeKey=qv;dr.merge=ur});var Oo=C(Cu=>{"use strict";var Vv=Io(),Eu=hr(),Wv=Bi(),Ru=M(),jo=ht();function zv(t,e,{key:i,value:n}){if(Ru.isNode(i)&&i.addToJSMap)i.addToJSMap(t,e,n);else if(Eu.isMergeKey(t,i))Eu.addMergeToJSMap(t,e,n);else{let r=jo.toJS(i,"",t);if(e instanceof Map)e.set(r,jo.toJS(n,r,t));else if(e instanceof Set)e.add(r);else{let a=Jv(i,r,t),o=jo.toJS(n,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function Jv(t,e,i){if(e===null)return"";if(typeof e!="object")return String(e);if(Ru.isNode(t)&&i?.doc){let n=Wv.createStringifyContext(i.doc,{});n.anchors=new Set;for(let a of i.anchors.keys())n.anchors.add(a.anchor);n.inFlow=!0,n.inStringifyKey=!0;let r=t.toString(n);if(!i.mapKeyWarned){let a=JSON.stringify(r);a.length>40&&(a=a.substring(0,36)+'..."'),Vv.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 r}return JSON.stringify(e)}Cu.addPairToJSMap=zv});var gt=C($o=>{"use strict";var Pu=$i(),Gv=yu(),Kv=Oo(),pr=M();function Uv(t,e,i){let n=Pu.createNode(t,void 0,i),r=Pu.createNode(e,void 0,i);return new mr(n,r)}var mr=class t{constructor(e,i=null){Object.defineProperty(this,pr.NODE_TYPE,{value:pr.PAIR}),this.key=e,this.value=i}clone(e){let{key:i,value:n}=this;return pr.isNode(i)&&(i=i.clone(e)),pr.isNode(n)&&(n=n.clone(e)),new t(i,n)}toJSON(e,i){let n=i?.mapAsMap?new Map:{};return Kv.addPairToJSMap(i,n,this)}toString(e,i,n){return e?.doc?Gv.stringifyPair(this,e,i,n):JSON.stringify(this)}};$o.Pair=mr;$o.createPair=Uv});var Ho=C(xu=>{"use strict";var Mt=M(),Au=Bi(),vr=Hi();function Yv(t,e,i){return(e.inFlow??t.flow?Qv:Xv)(t,e,i)}function Xv({comment:t,items:e},i,{blockItemPrefix:n,flowChars:r,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),f=!1,d=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(Mt.isNode(h))!f&&h.spaceBefore&&d.push(""),gr(i,d,h.commentBefore,f),h.comment&&(v=h.comment);else if(Mt.isPair(h)){let N=Mt.isNode(h.key)?h.key:null;N&&(!f&&N.spaceBefore&&d.push(""),gr(i,d,N.commentBefore,f))}f=!1;let S=Au.stringify(h,u,()=>v=null,()=>f=!0);v&&(S+=vr.lineComment(S,a,l(v))),f&&v&&(f=!1),d.push(n+S)}let p;if(d.length===0)p=r.start+r.end;else{p=d[0];for(let m=1;m<d.length;++m){let h=d[m];p+=h?`
|
|
48
48
|
${c}${h}`:`
|
|
49
49
|
`}}return t?(p+=`
|
|
50
|
-
`+
|
|
51
|
-
`)),m<t.length-1?
|
|
50
|
+
`+vr.indentComment(l(t),c),s&&s()):f&&o&&o(),p}function Qv({items:t},e,{flowChars:i,itemIndent:n}){let{indent:r,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=e;n+=a;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,u=0,f=[];for(let m=0;m<t.length;++m){let h=t[m],v=null;if(Mt.isNode(h))h.spaceBefore&&f.push(""),gr(e,f,h.commentBefore,!1),h.comment&&(v=h.comment);else if(Mt.isPair(h)){let N=Mt.isNode(h.key)?h.key:null;N&&(N.spaceBefore&&f.push(""),gr(e,f,N.commentBefore,!1),N.comment&&(l=!0));let E=Mt.isNode(h.value)?h.value:null;E?(E.comment&&(v=E.comment),E.commentBefore&&(l=!0)):h.value==null&&N?.comment&&(v=N.comment)}v&&(l=!0);let S=Au.stringify(h,c,()=>v=null);l||(l=f.length>u||S.includes(`
|
|
51
|
+
`)),m<t.length-1?S+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=f.reduce((N,E)=>N+E.length+2,2)+(S.length+2)>e.options.lineWidth)),l&&(S+=",")),v&&(S+=vr.lineComment(S,n,s(v))),f.push(S),u=f.length}let{start:d,end:p}=i;if(f.length===0)return d+p;if(!l){let m=f.reduce((h,v)=>h+v.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=d;for(let h of f)m+=h?`
|
|
52
52
|
${a}${r}${h}`:`
|
|
53
53
|
`;return`${m}
|
|
54
|
-
${r}${p}`}else return`${d}${o}${f.join(" ")}${o}${p}`}function
|
|
55
|
-
`:" ")}return
|
|
54
|
+
${r}${p}`}else return`${d}${o}${f.join(" ")}${o}${p}`}function gr({indent:t,options:{commentString:e}},i,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let a=vr.indentComment(e(n),t);i.push(a.trimStart())}}xu.stringifyCollection=Yv});var yt=C(Lo=>{"use strict";var Zv=Ho(),eg=Oo(),tg=nr(),wt=M(),wr=gt(),ig=ee();function qi(t,e){let i=wt.isScalar(e)?e.value:e;for(let n of t)if(wt.isPair(n)&&(n.key===e||n.key===i||wt.isScalar(n.key)&&n.key.value===i))return n}var Mo=class extends tg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(wt.MAP,e),this.items=[]}static from(e,i,n){let{keepUndefined:r,replacer:a}=n,o=new this(e),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||r)&&o.items.push(wr.createPair(c,l,n))};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 e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,i){let n;wt.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new wr.Pair(e,e?.value):n=new wr.Pair(e.key,e.value);let r=qi(this.items,n.key),a=this.schema?.sortMapEntries;if(r){if(!i)throw new Error(`Key ${n.key} already set`);wt.isScalar(r.value)&&ig.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(a){let o=this.items.findIndex(s=>a(n,s)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let i=qi(this.items,e);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(e,i){let r=qi(this.items,e)?.value;return(!i&&wt.isScalar(r)?r.value:r)??void 0}has(e){return!!qi(this.items,e)}set(e,i){this.add(new wr.Pair(e,i),!0)}toJSON(e,i,n){let r=n?new n:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(r);for(let a of this.items)eg.addPairToJSMap(i,r,a);return r}toString(e,i,n){if(!e)return JSON.stringify(this);for(let r of this.items)if(!wt.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Zv.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:i})}};Lo.YAMLMap=Mo;Lo.findPair=qi});var ni=C(Iu=>{"use strict";var ng=M(),Tu=yt(),rg={collection:"map",default:!0,nodeClass:Tu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return ng.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,i)=>Tu.YAMLMap.from(t,e,i)};Iu.map=rg});var Nt=C(_u=>{"use strict";var ag=$i(),og=Ho(),sg=nr(),Nr=M(),cg=ee(),lg=ht(),Fo=class extends sg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Nr.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let i=yr(e);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(e,i){let n=yr(e);if(typeof n!="number")return;let r=this.items[n];return!i&&Nr.isScalar(r)?r.value:r}has(e){let i=yr(e);return typeof i=="number"&&i<this.items.length}set(e,i){let n=yr(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let r=this.items[n];Nr.isScalar(r)&&cg.isScalarValue(i)?r.value=i:this.items[n]=i}toJSON(e,i){let n=[];i?.onCreate&&i.onCreate(n);let r=0;for(let a of this.items)n.push(lg.toJS(a,String(r++),i));return n}toString(e,i,n){return e?og.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:i}):JSON.stringify(this)}static from(e,i,n){let{replacer:r}=n,a=new this(e);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof r=="function"){let c=i instanceof Set?s:String(o++);s=r.call(i,c,s)}a.items.push(ag.createNode(s,void 0,n))}}return a}};function yr(t){let e=Nr.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}_u.YAMLSeq=Fo});var ri=C(Ou=>{"use strict";var ug=M(),ju=Nt(),fg={collection:"seq",default:!0,nodeClass:ju.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return ug.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,i)=>ju.YAMLSeq.from(t,e,i)};Ou.seq=fg});var Vi=C($u=>{"use strict";var dg=Fi(),hg={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,i,n){return e=Object.assign({actualString:!0},e),dg.stringifyString(t,e,i,n)}};$u.string=hg});var br=C(Lu=>{"use strict";var Hu=ee(),Mu={identify:t=>t==null,createNode:()=>new Hu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Hu.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Mu.test.test(t)?t:e.options.nullStr};Lu.nullTag=Mu});var Bo=C(Bu=>{"use strict";var pg=ee(),Fu={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new pg.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},i){if(t&&Fu.test.test(t)){let n=t[0]==="t"||t[0]==="T";if(e===n)return t}return e?i.options.trueStr:i.options.falseStr}};Bu.boolTag=Fu});var ai=C(Du=>{"use strict";function mg({format:t,minFractionDigits:e,tag:i,value:n}){if(typeof n=="bigint")return String(n);let r=typeof n=="number"?n:Number(n);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let a=Object.is(n,-0)?"-0":JSON.stringify(n);if(!t&&e&&(!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=e-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Du.stringifyNumber=mg});var qo=C(kr=>{"use strict";var vg=ee(),Do=ai(),gg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Do.stringifyNumber},wg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Do.stringifyNumber(t)}},yg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new vg.Scalar(parseFloat(t)),i=t.indexOf(".");return i!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-i-1),e},stringify:Do.stringifyNumber};kr.float=yg;kr.floatExp=wg;kr.floatNaN=gg});var Wo=C(Er=>{"use strict";var qu=ai(),Sr=t=>typeof t=="bigint"||Number.isInteger(t),Vo=(t,e,i,{intAsBigInt:n})=>n?BigInt(t):parseInt(t.substring(e),i);function Vu(t,e,i){let{value:n}=t;return Sr(n)&&n>=0?i+n.toString(e):qu.stringifyNumber(t)}var Ng={identify:t=>Sr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,i)=>Vo(t,2,8,i),stringify:t=>Vu(t,8,"0o")},bg={identify:Sr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,i)=>Vo(t,0,10,i),stringify:qu.stringifyNumber},kg={identify:t=>Sr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,i)=>Vo(t,2,16,i),stringify:t=>Vu(t,16,"0x")};Er.int=bg;Er.intHex=kg;Er.intOct=Ng});var zu=C(Wu=>{"use strict";var Sg=ni(),Eg=br(),Rg=ri(),Cg=Vi(),Pg=Bo(),zo=qo(),Jo=Wo(),Ag=[Sg.map,Rg.seq,Cg.string,Eg.nullTag,Pg.boolTag,Jo.intOct,Jo.int,Jo.intHex,zo.floatNaN,zo.floatExp,zo.float];Wu.schema=Ag});var Ku=C(Gu=>{"use strict";var xg=ee(),Tg=ni(),Ig=ri();function Ju(t){return typeof t=="bigint"||Number.isInteger(t)}var Rr=({value:t})=>JSON.stringify(t),_g=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Rr},{identify:t=>t==null,createNode:()=>new xg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Rr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Rr},{identify:Ju,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:i})=>i?BigInt(t):parseInt(t,10),stringify:({value:t})=>Ju(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Rr}],jg={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Og=[Tg.map,Ig.seq].concat(_g,jg);Gu.schema=Og});var Ko=C(Uu=>{"use strict";var Wi=Kn("buffer"),Go=ee(),$g=Fi(),Hg={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Wi.Buffer=="function")return Wi.Buffer.from(t,"base64");if(typeof atob=="function"){let i=atob(t.replace(/[\n\r]/g,"")),n=new Uint8Array(i.length);for(let r=0;r<i.length;++r)n[r]=i.charCodeAt(r);return n}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:i},n,r,a){if(!i)return"";let o=i,s;if(typeof Wi.Buffer=="function")s=o instanceof Wi.Buffer?o.toString("base64"):Wi.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=Go.Scalar.BLOCK_LITERAL),e!==Go.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let f=0,d=0;f<l;++f,d+=c)u[f]=s.substr(d,c);s=u.join(e===Go.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return $g.stringifyString({comment:t,type:e,value:s},n,r,a)}};Uu.binary=Hg});var Ar=C(Pr=>{"use strict";var Cr=M(),Uo=gt(),Mg=ee(),Lg=Nt();function Yu(t,e){if(Cr.isSeq(t))for(let i=0;i<t.items.length;++i){let n=t.items[i];if(!Cr.isPair(n)){if(Cr.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let r=n.items[0]||new Uo.Pair(new Mg.Scalar(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
|
|
56
56
|
${r.key.commentBefore}`:n.commentBefore),n.comment){let a=r.value??r.key;a.comment=a.comment?`${n.comment}
|
|
57
|
-
${a.comment}`:n.comment}n=r}t.items[i]=wr.isPair(n)?n:new Oo.Pair(n)}}else e("Expected a sequence for this tag");return t}function $u(t,e,i){let{replacer:n}=i,r=new dg.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;r.items.push(Oo.createPair(s,c,i))}return r}var hg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ju,createNode:$u};yr.createPairs=$u;yr.pairs=hg;yr.resolvePairs=ju});var Ho=C($o=>{"use strict";var Hu=M(),jo=ft(),Fi=gt(),pg=wt(),Mu=Nr(),Ht=class t extends pg.YAMLSeq{constructor(){super(),this.add=Fi.YAMLMap.prototype.add.bind(this),this.delete=Fi.YAMLMap.prototype.delete.bind(this),this.get=Fi.YAMLMap.prototype.get.bind(this),this.has=Fi.YAMLMap.prototype.has.bind(this),this.set=Fi.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,i){if(!i)return super.toJSON(e);let n=new Map;i?.onCreate&&i.onCreate(n);for(let r of this.items){let a,o;if(Hu.isPair(r)?(a=jo.toJS(r.key,"",i),o=jo.toJS(r.value,a,i)):a=jo.toJS(r,"",i),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(e,i,n){let r=Mu.createPairs(e,i,n),a=new this;return a.items=r.items,a}};Ht.tag="tag:yaml.org,2002:omap";var mg={collection:"seq",identify:t=>t instanceof Map,nodeClass:Ht,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=Mu.resolvePairs(t,e),n=[];for(let{key:r}of i.items)Hu.isScalar(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Ht,i)},createNode:(t,e,i)=>Ht.from(t,e,i)};$o.YAMLOMap=Ht;$o.omap=mg});var qu=C(Mo=>{"use strict";var Lu=Q();function Du({value:t,source:e},i){return e&&(t?Fu:Bu).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var Fu={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Lu.Scalar(!0),stringify:Du},Bu={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Lu.Scalar(!1),stringify:Du};Mo.falseTag=Bu;Mo.trueTag=Fu});var Vu=C(br=>{"use strict";var vg=Q(),Lo=ii(),gg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Lo.stringifyNumber},wg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Lo.stringifyNumber(t)}},yg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new vg.Scalar(parseFloat(t.replace(/_/g,""))),i=t.indexOf(".");if(i!==-1){let n=t.substring(i+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:Lo.stringifyNumber};br.float=yg;br.floatExp=wg;br.floatNaN=gg});var Wu=C(qi=>{"use strict";var zu=ii(),Bi=t=>typeof t=="bigint"||Number.isInteger(t);function Sr(t,e,i,{intAsBigInt:n}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),n){switch(i){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let a=parseInt(t,i);return r==="-"?-1*a:a}function Do(t,e,i){let{value:n}=t;if(Bi(n)){let r=n.toString(e);return n<0?"-"+i+r.substr(1):i+r}return zu.stringifyNumber(t)}var Ng={identify:Bi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>Sr(t,2,2,i),stringify:t=>Do(t,2,"0b")},bg={identify:Bi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>Sr(t,1,8,i),stringify:t=>Do(t,8,"0")},Sg={identify:Bi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>Sr(t,0,10,i),stringify:zu.stringifyNumber},kg={identify:Bi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>Sr(t,2,16,i),stringify:t=>Do(t,16,"0x")};qi.int=Sg;qi.intBin=Ng;qi.intHex=kg;qi.intOct=bg});var Bo=C(Fo=>{"use strict";var Rr=M(),kr=mt(),Er=gt(),Mt=class t extends Er.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;Rr.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new kr.Pair(e.key,null):i=new kr.Pair(e,null),Er.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let n=Er.findPair(this.items,e);return!i&&Rr.isPair(n)?Rr.isScalar(n.key)?n.key.value:n.key:n}set(e,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let n=Er.findPair(this.items,e);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new kr.Pair(e))}toJSON(e,i){return super.toJSON(e,i,Set)}toString(e,i,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),i,n);throw new Error("Set items must all have null values")}static from(e,i,n){let{replacer:r}=n,a=new this(e);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof r=="function"&&(o=r.call(i,o,o)),a.items.push(kr.createPair(o,null,n));return a}};Mt.tag="tag:yaml.org,2002:set";var Eg={collection:"map",identify:t=>t instanceof Set,nodeClass:Mt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>Mt.from(t,e,i),resolve(t,e){if(Rr.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Mt,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Fo.YAMLSet=Mt;Fo.set=Eg});var Vo=C(Cr=>{"use strict";var Rg=ii();function qo(t,e){let i=t[0],n=i==="-"||i==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),a=n.replace(/_/g,"").split(":").reduce((o,s)=>o*r(60)+r(s),r(0));return i==="-"?r(-1)*a:a}function Ju(t){let{value:e}=t,i=o=>o;if(typeof e=="bigint")i=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Rg.stringifyNumber(t);let n="";e<0&&(n="-",e*=i(-1));let r=i(60),a=[e%r];return e<60?a.unshift(0):(e=(e-a[0])/r,a.unshift(e%r),e>=60&&(e=(e-a[0])/r,a.unshift(e))),n+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Cg={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:i})=>qo(t,i),stringify:Ju},Pg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>qo(t,!1),stringify:Ju},Ku={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Ku.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,n,r,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(i,n-1,r,a||0,o||0,s||0,c),u=e[8];if(u&&u!=="Z"){let f=qo(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Cr.floatTime=Pg;Cr.intTime=Cg;Cr.timestamp=Ku});var Yu=C(Uu=>{"use strict";var Ag=ei(),xg=hr(),Tg=ti(),Ig=Li(),_g=_o(),Gu=qu(),zo=Vu(),Pr=Wu(),Og=ar(),jg=Ho(),$g=Nr(),Hg=Bo(),Wo=Vo(),Mg=[Ag.map,Tg.seq,Ig.string,xg.nullTag,Gu.trueTag,Gu.falseTag,Pr.intBin,Pr.intOct,Pr.int,Pr.intHex,zo.floatNaN,zo.floatExp,zo.float,_g.binary,Og.merge,jg.omap,$g.pairs,Hg.set,Wo.intTime,Wo.floatTime,Wo.timestamp];Uu.schema=Mg});var sf=C(Go=>{"use strict";var ef=ei(),Lg=hr(),tf=ti(),Dg=Li(),Fg=Eo(),Jo=Co(),Ko=Ao(),Bg=xu(),qg=_u(),nf=_o(),Vi=ar(),rf=Ho(),af=Nr(),Xu=Yu(),of=Bo(),Ar=Vo(),Qu=new Map([["core",Bg.schema],["failsafe",[ef.map,tf.seq,Dg.string]],["json",qg.schema],["yaml11",Xu.schema],["yaml-1.1",Xu.schema]]),Zu={binary:nf.binary,bool:Fg.boolTag,float:Jo.float,floatExp:Jo.floatExp,floatNaN:Jo.floatNaN,floatTime:Ar.floatTime,int:Ko.int,intHex:Ko.intHex,intOct:Ko.intOct,intTime:Ar.intTime,map:ef.map,merge:Vi.merge,null:Lg.nullTag,omap:rf.omap,pairs:af.pairs,seq:tf.seq,set:of.set,timestamp:Ar.timestamp},Vg={"tag:yaml.org,2002:binary":nf.binary,"tag:yaml.org,2002:merge":Vi.merge,"tag:yaml.org,2002:omap":rf.omap,"tag:yaml.org,2002:pairs":af.pairs,"tag:yaml.org,2002:set":of.set,"tag:yaml.org,2002:timestamp":Ar.timestamp};function zg(t,e,i){let n=Qu.get(e);if(n&&!t)return i&&!n.includes(Vi.merge)?n.concat(Vi.merge):n.slice();let r=n;if(!r)if(Array.isArray(t))r=[];else{let a=Array.from(Qu.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)r=r.concat(a);else typeof t=="function"&&(r=t(r.slice()));return i&&(r=r.concat(Vi.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?Zu[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Zu).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Go.coreKnownTags=Vg;Go.getTags=zg});var Xo=C(cf=>{"use strict";var Uo=M(),Wg=ei(),Jg=ti(),Kg=Li(),xr=sf(),Gg=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,Yo=class t{constructor({compat:e,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?xr.getTags(e,"compat"):e?xr.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?xr.coreKnownTags:{},this.tags=xr.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,Uo.MAP,{value:Wg.map}),Object.defineProperty(this,Uo.SCALAR,{value:Kg.string}),Object.defineProperty(this,Uo.SEQ,{value:Jg.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Gg:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};cf.Schema=Yo});var uf=C(lf=>{"use strict";var Ug=M(),Qo=$i(),zi=Ii();function Yg(t,e){let i=[],n=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(i.push(c),n=!0):t.directives.docStart&&(n=!0)}n&&i.push("---");let r=Qo.createStringifyContext(t,e),{commentString:a}=r.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=a(t.commentBefore);i.unshift(zi.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(Ug.isNode(t.contents)){if(t.contents.spaceBefore&&n&&i.push(""),t.contents.commentBefore){let u=a(t.contents.commentBefore);i.push(zi.indentComment(u,""))}r.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Qo.stringify(t.contents,r,()=>s=null,c);s&&(l+=zi.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Qo.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
|
|
58
|
-
`)?(i.push("..."),i.push(
|
|
57
|
+
${a.comment}`:n.comment}n=r}t.items[i]=Cr.isPair(n)?n:new Uo.Pair(n)}}else e("Expected a sequence for this tag");return t}function Xu(t,e,i){let{replacer:n}=i,r=new Lg.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;r.items.push(Uo.createPair(s,c,i))}return r}var Fg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Yu,createNode:Xu};Pr.createPairs=Xu;Pr.pairs=Fg;Pr.resolvePairs=Yu});var Qo=C(Xo=>{"use strict";var Qu=M(),Yo=ht(),zi=yt(),Bg=Nt(),Zu=Ar(),Lt=class t extends Bg.YAMLSeq{constructor(){super(),this.add=zi.YAMLMap.prototype.add.bind(this),this.delete=zi.YAMLMap.prototype.delete.bind(this),this.get=zi.YAMLMap.prototype.get.bind(this),this.has=zi.YAMLMap.prototype.has.bind(this),this.set=zi.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,i){if(!i)return super.toJSON(e);let n=new Map;i?.onCreate&&i.onCreate(n);for(let r of this.items){let a,o;if(Qu.isPair(r)?(a=Yo.toJS(r.key,"",i),o=Yo.toJS(r.value,a,i)):a=Yo.toJS(r,"",i),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(e,i,n){let r=Zu.createPairs(e,i,n),a=new this;return a.items=r.items,a}};Lt.tag="tag:yaml.org,2002:omap";var Dg={collection:"seq",identify:t=>t instanceof Map,nodeClass:Lt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=Zu.resolvePairs(t,e),n=[];for(let{key:r}of i.items)Qu.isScalar(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Lt,i)},createNode:(t,e,i)=>Lt.from(t,e,i)};Xo.YAMLOMap=Lt;Xo.omap=Dg});var af=C(Zo=>{"use strict";var ef=ee();function tf({value:t,source:e},i){return e&&(t?nf:rf).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var nf={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new ef.Scalar(!0),stringify:tf},rf={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new ef.Scalar(!1),stringify:tf};Zo.falseTag=rf;Zo.trueTag=nf});var of=C(xr=>{"use strict";var qg=ee(),es=ai(),Vg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:es.stringifyNumber},Wg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():es.stringifyNumber(t)}},zg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new qg.Scalar(parseFloat(t.replace(/_/g,""))),i=t.indexOf(".");if(i!==-1){let n=t.substring(i+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:es.stringifyNumber};xr.float=zg;xr.floatExp=Wg;xr.floatNaN=Vg});var cf=C(Gi=>{"use strict";var sf=ai(),Ji=t=>typeof t=="bigint"||Number.isInteger(t);function Tr(t,e,i,{intAsBigInt:n}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),n){switch(i){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let a=parseInt(t,i);return r==="-"?-1*a:a}function ts(t,e,i){let{value:n}=t;if(Ji(n)){let r=n.toString(e);return n<0?"-"+i+r.substr(1):i+r}return sf.stringifyNumber(t)}var Jg={identify:Ji,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>Tr(t,2,2,i),stringify:t=>ts(t,2,"0b")},Gg={identify:Ji,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>Tr(t,1,8,i),stringify:t=>ts(t,8,"0")},Kg={identify:Ji,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>Tr(t,0,10,i),stringify:sf.stringifyNumber},Ug={identify:Ji,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>Tr(t,2,16,i),stringify:t=>ts(t,16,"0x")};Gi.int=Kg;Gi.intBin=Jg;Gi.intHex=Ug;Gi.intOct=Gg});var ns=C(is=>{"use strict";var jr=M(),Ir=gt(),_r=yt(),Ft=class t extends _r.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;jr.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new Ir.Pair(e.key,null):i=new Ir.Pair(e,null),_r.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let n=_r.findPair(this.items,e);return!i&&jr.isPair(n)?jr.isScalar(n.key)?n.key.value:n.key:n}set(e,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let n=_r.findPair(this.items,e);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new Ir.Pair(e))}toJSON(e,i){return super.toJSON(e,i,Set)}toString(e,i,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),i,n);throw new Error("Set items must all have null values")}static from(e,i,n){let{replacer:r}=n,a=new this(e);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof r=="function"&&(o=r.call(i,o,o)),a.items.push(Ir.createPair(o,null,n));return a}};Ft.tag="tag:yaml.org,2002:set";var Yg={collection:"map",identify:t=>t instanceof Set,nodeClass:Ft,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>Ft.from(t,e,i),resolve(t,e){if(jr.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ft,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};is.YAMLSet=Ft;is.set=Yg});var as=C(Or=>{"use strict";var Xg=ai();function rs(t,e){let i=t[0],n=i==="-"||i==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),a=n.replace(/_/g,"").split(":").reduce((o,s)=>o*r(60)+r(s),r(0));return i==="-"?r(-1)*a:a}function lf(t){let{value:e}=t,i=o=>o;if(typeof e=="bigint")i=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Xg.stringifyNumber(t);let n="";e<0&&(n="-",e*=i(-1));let r=i(60),a=[e%r];return e<60?a.unshift(0):(e=(e-a[0])/r,a.unshift(e%r),e>=60&&(e=(e-a[0])/r,a.unshift(e))),n+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Qg={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:i})=>rs(t,i),stringify:lf},Zg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>rs(t,!1),stringify:lf},uf={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(uf.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,n,r,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(i,n-1,r,a||0,o||0,s||0,c),u=e[8];if(u&&u!=="Z"){let f=rs(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Or.floatTime=Zg;Or.intTime=Qg;Or.timestamp=uf});var hf=C(df=>{"use strict";var ew=ni(),tw=br(),iw=ri(),nw=Vi(),rw=Ko(),ff=af(),os=of(),$r=cf(),aw=hr(),ow=Qo(),sw=Ar(),cw=ns(),ss=as(),lw=[ew.map,iw.seq,nw.string,tw.nullTag,ff.trueTag,ff.falseTag,$r.intBin,$r.intOct,$r.int,$r.intHex,os.floatNaN,os.floatExp,os.float,rw.binary,aw.merge,ow.omap,sw.pairs,cw.set,ss.intTime,ss.floatTime,ss.timestamp];df.schema=lw});var Sf=C(us=>{"use strict";var gf=ni(),uw=br(),wf=ri(),fw=Vi(),dw=Bo(),cs=qo(),ls=Wo(),hw=zu(),pw=Ku(),yf=Ko(),Ki=hr(),Nf=Qo(),bf=Ar(),pf=hf(),kf=ns(),Hr=as(),mf=new Map([["core",hw.schema],["failsafe",[gf.map,wf.seq,fw.string]],["json",pw.schema],["yaml11",pf.schema],["yaml-1.1",pf.schema]]),vf={binary:yf.binary,bool:dw.boolTag,float:cs.float,floatExp:cs.floatExp,floatNaN:cs.floatNaN,floatTime:Hr.floatTime,int:ls.int,intHex:ls.intHex,intOct:ls.intOct,intTime:Hr.intTime,map:gf.map,merge:Ki.merge,null:uw.nullTag,omap:Nf.omap,pairs:bf.pairs,seq:wf.seq,set:kf.set,timestamp:Hr.timestamp},mw={"tag:yaml.org,2002:binary":yf.binary,"tag:yaml.org,2002:merge":Ki.merge,"tag:yaml.org,2002:omap":Nf.omap,"tag:yaml.org,2002:pairs":bf.pairs,"tag:yaml.org,2002:set":kf.set,"tag:yaml.org,2002:timestamp":Hr.timestamp};function vw(t,e,i){let n=mf.get(e);if(n&&!t)return i&&!n.includes(Ki.merge)?n.concat(Ki.merge):n.slice();let r=n;if(!r)if(Array.isArray(t))r=[];else{let a=Array.from(mf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)r=r.concat(a);else typeof t=="function"&&(r=t(r.slice()));return i&&(r=r.concat(Ki.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?vf[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(vf).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}us.coreKnownTags=mw;us.getTags=vw});var hs=C(Ef=>{"use strict";var fs=M(),gw=ni(),ww=ri(),yw=Vi(),Mr=Sf(),Nw=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,ds=class t{constructor({compat:e,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?Mr.getTags(e,"compat"):e?Mr.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?Mr.coreKnownTags:{},this.tags=Mr.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,fs.MAP,{value:gw.map}),Object.defineProperty(this,fs.SCALAR,{value:yw.string}),Object.defineProperty(this,fs.SEQ,{value:ww.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Nw:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Ef.Schema=ds});var Cf=C(Rf=>{"use strict";var bw=M(),ps=Bi(),Ui=Hi();function kw(t,e){let i=[],n=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(i.push(c),n=!0):t.directives.docStart&&(n=!0)}n&&i.push("---");let r=ps.createStringifyContext(t,e),{commentString:a}=r.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=a(t.commentBefore);i.unshift(Ui.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(bw.isNode(t.contents)){if(t.contents.spaceBefore&&n&&i.push(""),t.contents.commentBefore){let u=a(t.contents.commentBefore);i.push(Ui.indentComment(u,""))}r.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=ps.stringify(t.contents,r,()=>s=null,c);s&&(l+=Ui.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(ps.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
|
|
58
|
+
`)?(i.push("..."),i.push(Ui.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(Ui.indentComment(a(c),"")))}return i.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}Rf.stringifyDocument=kw});var Yi=C(Pf=>{"use strict";var Sw=Oi(),oi=nr(),Se=M(),Ew=gt(),Rw=ht(),Cw=hs(),Pw=Cf(),ms=Zn(),Aw=yo(),xw=$i(),vs=wo(),gs=class t{constructor(e,i,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Se.NODE_TYPE,{value:Se.DOC});let r=null;typeof i=="function"||Array.isArray(i)?r=i:n===void 0&&i&&(n=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"},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new vs.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let e=Object.create(t.prototype,{[Se.NODE_TYPE]:{value:Se.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Se.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){si(this.contents)&&this.contents.add(e)}addIn(e,i){si(this.contents)&&this.contents.addIn(e,i)}createAlias(e,i){if(!e.anchor){let n=ms.anchorNames(this);e.anchor=!i||n.has(i)?ms.findNewAnchor(i||"a",n):i}return new Sw.Alias(e.anchor)}createNode(e,i,n){let r;if(typeof i=="function")e=i.call({"":e},"",e),r=i;else if(Array.isArray(i)){let v=N=>typeof N=="number"||N instanceof String||N instanceof Number,S=i.filter(v).map(String);S.length>0&&(i=i.concat(S)),r=i}else n===void 0&&i&&(n=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:f,setAnchors:d,sourceObjects:p}=ms.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:p},h=xw.createNode(e,u,m);return s&&Se.isCollection(h)&&(h.flow=!0),d(),h}createPair(e,i,n={}){let r=this.createNode(e,null,n),a=this.createNode(i,null,n);return new Ew.Pair(r,a)}delete(e){return si(this.contents)?this.contents.delete(e):!1}deleteIn(e){return oi.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):si(this.contents)?this.contents.deleteIn(e):!1}get(e,i){return Se.isCollection(this.contents)?this.contents.get(e,i):void 0}getIn(e,i){return oi.isEmptyPath(e)?!i&&Se.isScalar(this.contents)?this.contents.value:this.contents:Se.isCollection(this.contents)?this.contents.getIn(e,i):void 0}has(e){return Se.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return oi.isEmptyPath(e)?this.contents!==void 0:Se.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,i){this.contents==null?this.contents=oi.collectionFromPath(this.schema,[e],i):si(this.contents)&&this.contents.set(e,i)}setIn(e,i){oi.isEmptyPath(e)?this.contents=i:this.contents==null?this.contents=oi.collectionFromPath(this.schema,Array.from(e),i):si(this.contents)&&this.contents.setIn(e,i)}setSchema(e,i={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new vs.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new vs.Directives({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(n)this.schema=new Cw.Schema(Object.assign(n,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:i,mapAsMap:n,maxAliasCount:r,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Rw.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?Aw.applyReviver(o,{"":c},"",c):c}toJSON(e,i){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:i})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let i=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return Pw.stringifyDocument(this,e)}};function si(t){if(Se.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Pf.Document=gs});var Zi=C(Qi=>{"use strict";var Xi=class extends Error{constructor(e,i,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=i}},ws=class extends Xi{constructor(e,i,n){super("YAMLParseError",e,i,n)}},ys=class extends Xi{constructor(e,i,n){super("YAMLWarning",e,i,n)}},Tw=(t,e)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>e.linePos(s));let{line:n,col:r}=i.linePos[0];i.message+=` at line ${n}, column ${r}`;let a=r-1,o=t.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),n>1&&/^ *$/.test(o.substring(0,a))){let s=t.substring(e.lineStarts[n-2],e.lineStarts[n-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===n&&c.col>r&&(s=Math.max(1,Math.min(c.col-r,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};
|
|
66
|
-
`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let i of e.start)if(i.type==="newline")return!0;if(e.sep){for(let i of e.sep)if(i.type==="newline")return!0}if(
|
|
67
|
-
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||
|
|
68
|
-
`+
|
|
69
|
-
`+g.comment:l.comment=g.comment),f=g.end;continue}!o&&i.options.strict&&
|
|
70
|
-
`+
|
|
71
|
-
`+R.comment:
|
|
72
|
-
`+v.comment:l.comment=v.comment),l.range=[n.offset,h,v.offset]}else l.range=[n.offset,h,h];return l}
|
|
73
|
-
`.repeat(Math.max(1,o.length-1)):"",v=n+r.length;return e.source&&(v+=e.source.length),{value:h,type:a,comment:r.comment,range:[n,v,v]}}let c=e.indent+r.indent,l=e.offset+r.length,u=0;for(let h=0;h<s;++h){let[v,
|
|
74
|
-
`;for(let h=u;h<s;++h){let[v,
|
|
75
|
-
`):v.length>c||
|
|
65
|
+
`}};Qi.YAMLError=Xi;Qi.YAMLParseError=ws;Qi.YAMLWarning=ys;Qi.prettifyError=Tw});var en=C(Af=>{"use strict";function Iw(t,{flow:e,indicator:i,next:n,offset:r,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,f="",d="",p=!1,m=!1,h=null,v=null,S=null,N=null,E=null,b=null,k=null;for(let w of t)switch(m&&(w.type!=="space"&&w.type!=="newline"&&w.type!=="comma"&&a(w.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&w.type!=="comment"&&w.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),w.type){case"space":!e&&(i!=="doc-start"||n?.type!=="flow-collection")&&w.source.includes(" ")&&(h=w),u=!0;break;case"comment":{u||a(w,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=w.source.substring(1)||" ";f?f+=d+R:f=R,d="",l=!1;break}case"newline":l?f?f+=w.source:(!b||i!=="seq-item-ind")&&(c=!0):d+=w.source,l=!0,p=!0,(v||S)&&(N=w),u=!0;break;case"anchor":v&&a(w,"MULTIPLE_ANCHORS","A node can have at most one anchor"),w.source.endsWith(":")&&a(w.offset+w.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=w,k??(k=w.offset),l=!1,u=!1,m=!0;break;case"tag":{S&&a(w,"MULTIPLE_TAGS","A node can have at most one tag"),S=w,k??(k=w.offset),l=!1,u=!1,m=!0;break}case i:(v||S)&&a(w,"BAD_PROP_ORDER",`Anchors and tags must be after the ${w.source} indicator`),b&&a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.source} in ${e??"collection"}`),b=w,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(e){E&&a(w,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),E=w,l=!1,u=!1;break}default:a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.type} token`),l=!1,u=!1}let g=t[t.length-1],y=g?g.offset+g.source.length:r;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&a(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:E,found:b,spaceBefore:c,comment:f,hasNewline:p,anchor:v,tag:S,newlineAfterProp:N,end:y,start:k??y}}Af.resolveProps=Iw});var Lr=C(xf=>{"use strict";function Ns(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
|
|
66
|
+
`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let i of e.start)if(i.type==="newline")return!0;if(e.sep){for(let i of e.sep)if(i.type==="newline")return!0}if(Ns(e.key)||Ns(e.value))return!0}return!1;default:return!0}}xf.containsNewline=Ns});var bs=C(Tf=>{"use strict";var _w=Lr();function jw(t,e,i){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===t&&(n.source==="]"||n.source==="}")&&_w.containsNewline(e)&&i(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Tf.flowIndentCheck=jw});var ks=C(_f=>{"use strict";var If=M();function Ow(t,e,i){let{uniqueKeys:n}=t.options;if(n===!1)return!1;let r=typeof n=="function"?n:(a,o)=>a===o||If.isScalar(a)&&If.isScalar(o)&&a.value===o.value;return e.some(a=>r(a.key,i))}_f.mapIncludes=Ow});var Lf=C(Mf=>{"use strict";var jf=gt(),$w=yt(),Of=en(),Hw=Lr(),$f=bs(),Mw=ks(),Hf="All mapping items must start at the same column";function Lw({composeNode:t,composeEmptyNode:e},i,n,r,a){let o=a?.nodeClass??$w.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:f,key:d,sep:p,value:m}=u,h=Of.resolveProps(f,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0}),v=!h.found;if(v){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==n.indent&&r(c,"BAD_INDENT",Hf)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Hw.containsNewline(d))&&r(d??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&r(c,"BAD_INDENT",Hf);i.atKey=!0;let S=h.end,N=d?t(i,d,h,r):e(i,S,f,null,h,r);i.schema.compat&&$f.flowIndentCheck(n.indent,d,r),i.atKey=!1,Mw.mapIncludes(i,s.items,N)&&r(S,"DUPLICATE_KEY","Map keys must be unique");let E=Of.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:N.range[2],onError:r,parentIndent:n.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=E.end,E.found){v&&(m?.type==="block-map"&&!E.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<E.found.offset-1024&&r(N.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=m?t(i,m,E,r):e(i,c,p,null,E,r);i.schema.compat&&$f.flowIndentCheck(n.indent,m,r),c=b.range[2];let k=new jf.Pair(N,b);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}else{v&&r(N.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),E.comment&&(N.comment?N.comment+=`
|
|
68
|
+
`+E.comment:N.comment=E.comment);let b=new jf.Pair(N);i.options.keepSourceTokens&&(b.srcToken=u),s.items.push(b)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}Mf.resolveBlockMap=Lw});var Bf=C(Ff=>{"use strict";var Fw=Nt(),Bw=en(),Dw=bs();function qw({composeNode:t,composeEmptyNode:e},i,n,r,a){let o=a?.nodeClass??Fw.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=n.offset,l=null;for(let{start:u,value:f}of n.items){let d=Bw.resolveProps(u,{indicator:"seq-item-ind",next:f,offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||f)f?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let p=f?t(i,f,d,r):e(i,d.end,u,null,d,r);i.schema.compat&&Dw.flowIndentCheck(n.indent,f,r),c=p.range[2],s.items.push(p)}return s.range=[n.offset,c,l??c],s}Ff.resolveBlockSeq=qw});var ci=C(Df=>{"use strict";function Vw(t,e,i,n){let r="";if(t){let a=!1,o="";for(let s of t){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&n(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";r?r+=o+u:r=u,o="";break}case"newline":r&&(o+=c),a=!0;break;default:n(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}Df.resolveEnd=Vw});var zf=C(Wf=>{"use strict";var Ww=M(),zw=gt(),qf=yt(),Jw=Nt(),Gw=ci(),Vf=en(),Kw=Lr(),Uw=ks(),Ss="Block collections are not allowed within flow collections",Es=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Yw({composeNode:t,composeEmptyNode:e},i,n,r,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?qf.YAMLMap:Jw.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let f=n.offset+n.start.source.length;for(let v=0;v<n.items.length;++v){let S=n.items[v],{start:N,key:E,sep:b,value:k}=S,g=Vf.resolveProps(N,{flow:s,indicator:"explicit-key-ind",next:E??b?.[0],offset:f,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!g.found){if(!g.anchor&&!g.tag&&!b&&!k){v===0&&g.comma?r(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<n.items.length-1&&r(g.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),g.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+g.comment:l.comment=g.comment),f=g.end;continue}!o&&i.options.strict&&Kw.containsNewline(E)&&r(E,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)g.comma&&r(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(g.comma||r(g.start,"MISSING_CHAR",`Missing , between ${s} items`),g.comment){let y="";e:for(let w of N)switch(w.type){case"comma":case"space":break;case"comment":y=w.source.substring(1);break e;default:break e}if(y){let w=l.items[l.items.length-1];Ww.isPair(w)&&(w=w.value??w.key),w.comment?w.comment+=`
|
|
70
|
+
`+y:w.comment=y,g.comment=g.comment.substring(y.length+1)}}if(!o&&!b&&!g.found){let y=k?t(i,k,g,r):e(i,g.end,b,null,g,r);l.items.push(y),f=y.range[2],Es(k)&&r(y.range,"BLOCK_IN_FLOW",Ss)}else{i.atKey=!0;let y=g.end,w=E?t(i,E,g,r):e(i,y,N,null,g,r);Es(E)&&r(w.range,"BLOCK_IN_FLOW",Ss),i.atKey=!1;let R=Vf.resolveProps(b??[],{flow:s,indicator:"map-value-ind",next:k,offset:w.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(R.found){if(!o&&!g.found&&i.options.strict){if(b)for(let H of b){if(H===R.found)break;if(H.type==="newline"){r(H,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}g.start<R.found.offset-1024&&r(R.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?r(k,"MISSING_CHAR",`Missing space after : in ${s}`):r(R.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let _=k?t(i,k,R,r):R.found?e(i,R.end,b,null,R,r):null;_?Es(k)&&r(_.range,"BLOCK_IN_FLOW",Ss):R.comment&&(w.comment?w.comment+=`
|
|
71
|
+
`+R.comment:w.comment=R.comment);let D=new zw.Pair(w,_);if(i.options.keepSourceTokens&&(D.srcToken=S),o){let H=l;Uw.mapIncludes(i,H.items,w)&&r(y,"DUPLICATE_KEY","Map keys must be unique"),H.items.push(D)}else{let H=new qf.YAMLMap(i.schema);H.flow=!0,H.items.push(D);let F=(_??w).range;H.range=[w.range[0],F[1],F[2]],l.items.push(H)}f=_?_.range[2]:R.end}}let d=o?"}":"]",[p,...m]=n.end,h=f;if(p?.source===d)h=p.offset+p.source.length;else{let v=s[0].toUpperCase()+s.substring(1),S=u?`${v} must end with a ${d}`:`${v} in block collection must be sufficiently indented and end with a ${d}`;r(f,u?"MISSING_CHAR":"BAD_INDENT",S),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let v=Gw.resolveEnd(m,h,i.options.strict,r);v.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+v.comment:l.comment=v.comment),l.range=[n.offset,h,v.offset]}else l.range=[n.offset,h,h];return l}Wf.resolveFlowCollection=Yw});var Gf=C(Jf=>{"use strict";var Xw=M(),Qw=ee(),Zw=yt(),ey=Nt(),ty=Lf(),iy=Bf(),ny=zf();function Rs(t,e,i,n,r,a){let o=i.type==="block-map"?ty.resolveBlockMap(t,e,i,n,a):i.type==="block-seq"?iy.resolveBlockSeq(t,e,i,n,a):ny.resolveFlowCollection(t,e,i,n,a),s=o.constructor;return r==="!"||r===s.tagName?(o.tag=s.tagName,o):(r&&(o.tag=r),o)}function ry(t,e,i,n,r){let a=n.tag,o=a?e.directives.tagName(a.source,d=>r(a,"TAG_RESOLVE_FAILED",d)):null;if(i.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=n,m=d&&a?d.offset>a.offset?d:a:d??a;m&&(!p||p.offset<m.offset)&&r(m,"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===Zw.YAMLMap.tagName&&s==="map"||o===ey.YAMLSeq.tagName&&s==="seq")return Rs(t,e,i,r,o);let c=e.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=e.schema.knownTags[o];if(d?.collection===s)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):r(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Rs(t,e,i,r,o)}let l=Rs(t,e,i,r,o,c),u=c.resolve?.(l,d=>r(a,"TAG_RESOLVE_FAILED",d),e.options)??l,f=Xw.isNode(u)?u:new Qw.Scalar(u);return f.range=l.range,f.tag=o,c?.format&&(f.format=c.format),f}Jf.composeCollection=ry});var Ps=C(Kf=>{"use strict";var Cs=ee();function ay(t,e,i){let n=e.offset,r=oy(e,t.options.strict,i);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let a=r.mode===">"?Cs.Scalar.BLOCK_FOLDED:Cs.Scalar.BLOCK_LITERAL,o=e.source?sy(e.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let v=o[h][1];if(v===""||v==="\r")s=h;else break}if(s===0){let h=r.chomp==="+"&&o.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,o.length-1)):"",v=n+r.length;return e.source&&(v+=e.source.length),{value:h,type:a,comment:r.comment,range:[n,v,v]}}let c=e.indent+r.indent,l=e.offset+r.length,u=0;for(let h=0;h<s;++h){let[v,S]=o[h];if(S===""||S==="\r")r.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&i(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(c=v.length),u=h,c===0&&!t.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+S.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let f="",d="",p=!1;for(let h=0;h<u;++h)f+=o[h][0].slice(c)+`
|
|
74
|
+
`;for(let h=u;h<s;++h){let[v,S]=o[h];l+=v.length+S.length+1;let N=S[S.length-1]==="\r";if(N&&(S=S.slice(0,-1)),S&&v.length<c){let b=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;i(l-S.length-(N?2:1),"BAD_INDENT",b),v=""}a===Cs.Scalar.BLOCK_LITERAL?(f+=d+v.slice(c)+S,d=`
|
|
75
|
+
`):v.length>c||S[0]===" "?(d===" "?d=`
|
|
76
76
|
`:!p&&d===`
|
|
77
77
|
`&&(d=`
|
|
78
78
|
|
|
79
|
-
`),f+=d+v.slice(c)+
|
|
80
|
-
`,p=!0):
|
|
79
|
+
`),f+=d+v.slice(c)+S,d=`
|
|
80
|
+
`,p=!0):S===""?d===`
|
|
81
81
|
`?f+=`
|
|
82
82
|
`:d=`
|
|
83
|
-
`:(f+=d+
|
|
83
|
+
`:(f+=d+S,d=" ",p=!1)}switch(r.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)f+=`
|
|
84
84
|
`+o[h][0].slice(c);f[f.length-1]!==`
|
|
85
85
|
`&&(f+=`
|
|
86
86
|
`);break;default:f+=`
|
|
87
|
-
`}let m=n+r.length+e.source.length;return{value:f,type:a,comment:r.comment,range:[n,m,m]}}function
|
|
87
|
+
`}let m=n+r.length+e.source.length;return{value:f,type:a,comment:r.comment,range:[n,m,m]}}function oy({offset:t,props:e},i,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],a=r[0],o=0,s="",c=-1;for(let d=1;d<r.length;++d){let p=r[d];if(!s&&(p==="-"||p==="+"))s=p;else{let m=Number(p);!o&&m?o=m:c===-1&&(c=t+d)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let l=!1,u="",f=r.length;for(let d=1;d<e.length;++d){let p=e[d];switch(p.type){case"space":l=!0;case"newline":f+=p.source.length;break;case"comment":i&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=p.source.length,u=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),f+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",m);let h=p.source;h&&typeof h=="string"&&(f+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:f}}function sy(t){let e=t.split(/\n( *)/),i=e[0],n=i.match(/^( *)/),a=[n?.[1]?[n[1],i.slice(n[1].length)]:["",i]];for(let o=1;o<e.length;o+=2)a.push([e[o],e[o+1]]);return a}Kf.resolveBlockScalar=ay});var xs=C(Yf=>{"use strict";var As=ee(),cy=ci();function ly(t,e,i){let{offset:n,type:r,source:a,end:o}=t,s,c,l=(d,p,m)=>i(n+d,p,m);switch(r){case"scalar":s=As.Scalar.PLAIN,c=uy(a,l);break;case"single-quoted-scalar":s=As.Scalar.QUOTE_SINGLE,c=fy(a,l);break;case"double-quoted-scalar":s=As.Scalar.QUOTE_DOUBLE,c=dy(a,l);break;default:return i(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[n,n+a.length,n+a.length]}}let u=n+a.length,f=cy.resolveEnd(o,u,e,i);return{value:c,type:s,comment:f.comment,range:[n,u,f.offset]}}function uy(t,e){let i="";switch(t[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 ${t[0]}`;break}case"@":case"`":{i=`reserved character ${t[0]}`;break}}return i&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),Uf(t)}function fy(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Uf(t.slice(1,-1)).replace(/''/g,"'")}function Uf(t){let e,i;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
89
|
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(t);if(!n)return t;let r=n[1],a=" ",o=e.lastIndex;for(i.lastIndex=o;n=i.exec(t);)n[1]===""?a===`
|
|
90
90
|
`?r+=a:a=`
|
|
91
|
-
`:(r+=a+n[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,n=s.exec(t),r+a+(n?.[1]??"")}function
|
|
91
|
+
`:(r+=a+n[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,n=s.exec(t),r+a+(n?.[1]??"")}function dy(t,e){let i="";for(let n=1;n<t.length-1;++n){let r=t[n];if(!(r==="\r"&&t[n+1]===`
|
|
92
92
|
`))if(r===`
|
|
93
|
-
`){let{fold:a,offset:o}=
|
|
93
|
+
`){let{fold:a,offset:o}=hy(t,n);i+=a,n=o}else if(r==="\\"){let a=t[++n],o=py[a];if(o)i+=o;else if(a===`
|
|
94
94
|
`)for(a=t[n+1];a===" "||a===" ";)a=t[++n+1];else if(a==="\r"&&t[n+1]===`
|
|
95
|
-
`)for(a=t[++n+1];a===" "||a===" ";)a=t[++n+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=
|
|
95
|
+
`)for(a=t[++n+1];a===" "||a===" ";)a=t[++n+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=my(t,n+1,s,e),n+=s}else{let s=t.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(r===" "||r===" "){let a=n,o=t[n+1];for(;o===" "||o===" ";)o=t[++n+1];o!==`
|
|
96
96
|
`&&!(o==="\r"&&t[n+2]===`
|
|
97
|
-
`)&&(i+=n>a?t.slice(a,n+1):r)}else i+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),i}function
|
|
97
|
+
`)&&(i+=n>a?t.slice(a,n+1):r)}else i+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),i}function hy(t,e){let i="",n=t[e+1];for(;(n===" "||n===" "||n===`
|
|
98
98
|
`||n==="\r")&&!(n==="\r"&&t[e+2]!==`
|
|
99
99
|
`);)n===`
|
|
100
100
|
`&&(i+=`
|
|
101
|
-
`),e+=1,n=t[e+1];return i||(i=" "),{fold:i,offset:e}}var
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),e+=1,n=t[e+1];return i||(i=" "),{fold:i,offset:e}}var py={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function my(t,e,i,n){let r=t.substr(e,i),o=r.length===i&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(o)}catch{let s=t.substr(e-2,i+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Yf.resolveFlowScalar=ly});var Zf=C(Qf=>{"use strict";var Bt=M(),Xf=ee(),vy=Ps(),gy=xs();function wy(t,e,i,n){let{value:r,type:a,comment:o,range:s}=e.type==="block-scalar"?vy.resolveBlockScalar(t,e,n):gy.resolveFlowScalar(e,t.options.strict,n),c=i?t.directives.tagName(i.source,f=>n(i,"TAG_RESOLVE_FAILED",f)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[Bt.SCALAR]:c?l=yy(t.schema,r,c,i,n):e.type==="scalar"?l=Ny(t,r,e,n):l=t.schema[Bt.SCALAR];let u;try{let f=l.resolve(r,d=>n(i??e,"TAG_RESOLVE_FAILED",d),t.options);u=Bt.isScalar(f)?f:new Xf.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);n(i??e,"TAG_RESOLVE_FAILED",d),u=new Xf.Scalar(r)}return u.range=s,u.source=r,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function yy(t,e,i,n,r){if(i==="!")return t[Bt.SCALAR];let a=[];for(let s of t.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(e))return s;let o=t.knownTags[i];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),t[Bt.SCALAR])}function Ny({atKey:t,directives:e,schema:i},n,r,a){let o=i.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(n))||i[Bt.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(n))??i[Bt.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(r,"TAG_RESOLVE_FAILED",u,!0)}}return o}Qf.composeScalar=wy});var td=C(ed=>{"use strict";function by(t,e,i){if(e){i??(i=e.length);for(let n=i-1;n>=0;--n){let r=e[n];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++n];r?.type==="space";)t+=r.source.length,r=e[++n];break}}return t}ed.emptyScalarPosition=by});var rd=C(Is=>{"use strict";var ky=Oi(),Sy=M(),Ey=Gf(),id=Zf(),Ry=ci(),Cy=td(),Py={composeNode:nd,composeEmptyNode:Ts};function nd(t,e,i,n){let r=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(e.type){case"alias":l=Ay(t,e,n),(s||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=id.composeScalar(t,e,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Ey.composeCollection(Py,t,e,i,n),s&&(l.anchor=s.source.substring(1))}catch(f){let d=f instanceof Error?f.message:String(f);n(e,"RESOURCE_EXHAUSTION",d)}break;default:{let f=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",f),u=!1}}return l??(l=Ts(t,e.offset,void 0,null,i,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!Sy.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&u&&(l.srcToken=e),l}function Ts(t,e,i,n,{spaceBefore:r,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Cy.emptyScalarPosition(e,i,n),indent:-1,source:""},f=id.composeScalar(t,u,s,l);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(f.spaceBefore=!0),a&&(f.comment=a,f.range[2]=c),f}function Ay({options:t},{offset:e,source:i,end:n},r){let a=new ky.Alias(i.substring(1));a.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&r(e+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+i.length,s=Ry.resolveEnd(n,o,t.strict,r);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}Is.composeEmptyNode=Ts;Is.composeNode=nd});var sd=C(od=>{"use strict";var xy=Yi(),ad=rd(),Ty=ci(),Iy=en();function _y(t,e,{offset:i,start:n,value:r,end:a},o){let s=Object.assign({_directives:e},t),c=new xy.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Iy.resolveProps(n,{indicator:"doc-start",next:r??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?ad.composeNode(l,r,u,o):ad.composeEmptyNode(l,u.end,n,null,u,o);let f=c.contents.range[2],d=Ty.resolveEnd(a,f,!1,o);return d.comment&&(c.comment=d.comment),c.range=[i,f,d.offset],c}od.composeDoc=_y});var js=C(ud=>{"use strict";var jy=Kn("process"),Oy=wo(),$y=Yi(),tn=Zi(),cd=M(),Hy=sd(),My=ci();function nn(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:i}=t;return[e,e+(typeof i=="string"?i.length:1)]}function ld(t){let e="",i=!1,n=!1;for(let r=0;r<t.length;++r){let a=t[r];switch(a[0]){case"#":e+=(e===""?"":n?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.substring(1)||" "),i=!0,n=!1;break;case"%":t[r+1]?.[0]!=="#"&&(r+=1),i=!1;break;default:i||(n=!0),i=!1}}return{comment:e,afterEmptyLine:n}}var
|
|
106
|
-
${n}`:n;else if(r||e.directives.docStart||!a)e.commentBefore=n;else if(
|
|
105
|
+
`)+(a.substring(1)||" "),i=!0,n=!1;break;case"%":t[r+1]?.[0]!=="#"&&(r+=1),i=!1;break;default:i||(n=!0),i=!1}}return{comment:e,afterEmptyLine:n}}var _s=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,n,r,a)=>{let o=nn(i);a?this.warnings.push(new tn.YAMLWarning(o,n,r)):this.errors.push(new tn.YAMLParseError(o,n,r))},this.directives=new Oy.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,i){let{comment:n,afterEmptyLine:r}=ld(this.prelude);if(n){let a=e.contents;if(i)e.comment=e.comment?`${e.comment}
|
|
106
|
+
${n}`:n;else if(r||e.directives.docStart||!a)e.commentBefore=n;else if(cd.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];cd.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${n}
|
|
107
107
|
${s}`:n}else{let o=a.commentBefore;a.commentBefore=o?`${n}
|
|
108
|
-
${o}`:n}}if(i){for(let a=0;a<this.errors.length;++a)e.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)e.warnings.push(this.warnings[a])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
109
|
-
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new
|
|
108
|
+
${o}`:n}}if(i){for(let a=0;a<this.errors.length;++a)e.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)e.warnings.push(this.warnings[a])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:ld(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,i=!1,n=-1){for(let r of e)yield*this.next(r);yield*this.end(i,n)}*next(e){switch(jy.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(i,n,r)=>{let a=nn(e);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let i=Hy.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(e,"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(e.source);break;case"error":{let i=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new tn.YAMLParseError(nn(e),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new tn.YAMLParseError(nn(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let i=My.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
|
|
109
|
+
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new tn.YAMLParseError(nn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),r=new $y.Document(void 0,n);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,i,i],this.decorate(r,!1),yield r}}};ud.Composer=_s});var hd=C(Fr=>{"use strict";var Ly=Ps(),Fy=xs(),By=Zi(),fd=Fi();function Dy(t,e=!0,i){if(t){let n=(r,a,o)=>{let s=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(i)i(s,a,o);else throw new By.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Fy.resolveFlowScalar(t,e,n);case"block-scalar":return Ly.resolveBlockScalar({options:{strict:e}},t,n)}}return null}function qy(t,e){let{implicitKey:i=!1,indent:n,inFlow:r=!1,offset:a=-1,type:o="PLAIN"}=e,s=fd.stringifyString({type:o,value:t},{implicitKey:i,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
111
|
`),u=s.substring(0,l),f=s.substring(l+1)+`
|
|
112
|
-
`,d=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:n,props:d,source:f}}case'"':return{type:"double-quoted-scalar",offset:a,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:n,source:s,end:c};default:return{type:"scalar",offset:a,indent:n,source:s,end:c}}}function
|
|
112
|
+
`,d=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return dd(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:n,props:d,source:f}}case'"':return{type:"double-quoted-scalar",offset:a,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:n,source:s,end:c};default:return{type:"scalar",offset:a,indent:n,source:s,end:c}}}function Vy(t,e,i={}){let{afterKey:n=!1,implicitKey:r=!1,inFlow:a=!1,type:o}=i,s="indent"in t?t.indent:null;if(n&&typeof s=="number"&&(s+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=fd.stringifyString({type:o,value:e},{implicitKey:r||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Wy(t,c);break;case'"':Os(t,c,"double-quoted-scalar");break;case"'":Os(t,c,"single-quoted-scalar");break;default:Os(t,c,"scalar")}}function Wy(t,e){let i=e.indexOf(`
|
|
114
114
|
`),n=e.substring(0,i),r=e.substring(i+1)+`
|
|
115
|
-
`;if(t.type==="block-scalar"){let a=t.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=n,t.source=r}else{let{offset:a}=t,o="indent"in t?t.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:n}];
|
|
116
|
-
`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:r})}}function
|
|
117
|
-
`};delete t.items,Object.assign(t,{type:i,source:e,end:[r]});break}default:{let n="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:i,indent:n,source:e,end:r})}}}
|
|
115
|
+
`;if(t.type==="block-scalar"){let a=t.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=n,t.source=r}else{let{offset:a}=t,o="indent"in t?t.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:n}];dd(s,"end"in t?t.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:r})}}function dd(t,e){if(e)for(let i of e)switch(i.type){case"space":case"comment":t.push(i);break;case"newline":return t.push(i),!0}return!1}function Os(t,e,i){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=i,t.source=e;break;case"block-scalar":{let n=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let a of n)a.offset+=r;delete t.props,Object.assign(t,{type:i,source:e,end:n});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:`
|
|
117
|
+
`};delete t.items,Object.assign(t,{type:i,source:e,end:[r]});break}default:{let n="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:i,indent:n,source:e,end:r})}}}Fr.createScalarToken=qy;Fr.resolveAsScalar=Dy;Fr.setScalarValue=Vy});var md=C(pd=>{"use strict";var zy=t=>"type"in t?Dr(t):Br(t);function Dr(t){switch(t.type){case"block-scalar":{let e="";for(let i of t.props)e+=Dr(i);return e+t.source}case"block-map":case"block-seq":{let e="";for(let i of t.items)e+=Br(i);return e}case"flow-collection":{let e=t.start.source;for(let i of t.items)e+=Br(i);for(let i of t.end)e+=i.source;return e}case"document":{let e=Br(t);if(t.end)for(let i of t.end)e+=i.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let i of t.end)e+=i.source;return e}}}function Br({start:t,key:e,sep:i,value:n}){let r="";for(let a of t)r+=a.source;if(e&&(r+=Dr(e)),i)for(let a of i)r+=a.source;return n&&(r+=Dr(n)),r}pd.stringify=zy});var yd=C(wd=>{"use strict";var $s=Symbol("break visit"),Jy=Symbol("skip children"),vd=Symbol("remove item");function Dt(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),gd(Object.freeze([]),t,e)}Dt.BREAK=$s;Dt.SKIP=Jy;Dt.REMOVE=vd;Dt.itemAtPath=(t,e)=>{let i=t;for(let[n,r]of e){let a=i?.[n];if(a&&"items"in a)i=a.items[r];else return}return i};Dt.parentCollection=(t,e)=>{let i=Dt.itemAtPath(t,e.slice(0,-1)),n=e[e.length-1][0],r=i?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function gd(t,e,i){let n=i(e,t);if(typeof n=="symbol")return n;for(let r of["key","value"]){let a=e[r];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=gd(Object.freeze(t.concat([[r,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===$s)return $s;s===vd&&(a.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(e,t))}}return typeof n=="function"?n(e,t):n}wd.visit=Dt});var qr=C(pe=>{"use strict";var Hs=hd(),Gy=md(),Ky=yd(),Ms="\uFEFF",Ls="",Fs="",Bs="",Uy=t=>!!t&&"items"in t,Yy=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Xy(t){switch(t){case Ms:return"<BOM>";case Ls:return"<DOC>";case Fs:return"<FLOW_END>";case Bs:return"<SCALAR>";default:return JSON.stringify(t)}}function Qy(t){switch(t){case Ms:return"byte-order-mark";case Ls:return"doc-mode";case Fs:return"flow-error-end";case Bs:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
118
|
`:case`\r
|
|
119
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
121
|
-
\r `),
|
|
119
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}pe.createScalarToken=Hs.createScalarToken;pe.resolveAsScalar=Hs.resolveAsScalar;pe.setScalarValue=Hs.setScalarValue;pe.stringify=Gy.stringify;pe.visit=Ky.visit;pe.BOM=Ms;pe.DOCUMENT=Ls;pe.FLOW_END=Fs;pe.SCALAR=Bs;pe.isCollection=Uy;pe.isScalar=Yy;pe.prettyToken=Xy;pe.tokenType=Qy});var Vs=C(bd=>{"use strict";var rn=qr();function Ie(t){switch(t){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var Nd=new Set("0123456789ABCDEFabcdef"),Zy=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Vr=new Set(",[]{}"),eN=new Set(` ,[]{}
|
|
121
|
+
\r `),Ds=t=>!t||eN.has(t),qs=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,i=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!i;let n=this.next??"stream";for(;n&&(i||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,i=this.buffer[e];for(;i===" "||i===" ";)i=this.buffer[++e];return!i||i==="#"||i===`
|
|
122
122
|
`?!0:i==="\r"?this.buffer[e+1]===`
|
|
123
123
|
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let i=this.buffer[e];if(this.indentNext>0){let n=0;for(;i===" ";)i=this.buffer[++n+e];if(i==="\r"){let r=this.buffer[n+e+1];if(r===`
|
|
124
124
|
`||!r&&!this.atEnd)return e+n+1}return i===`
|
|
125
|
-
`||n>=this.indentNext||!i&&!this.atEnd?e+n:-1}if(i==="-"||i==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&
|
|
126
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===
|
|
125
|
+
`||n>=this.indentNext||!i&&!this.atEnd?e+n:-1}if(i==="-"||i==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&Ie(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
126
|
+
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===rn.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let i=e.length,n=e.indexOf("#");for(;n!==-1;){let a=e[n-1];if(a===" "||a===" "){i=n-1;break}else n=e.indexOf("#",n+1)}for(;;){let a=e[i-1];if(a===" "||a===" ")i-=1;else break}let r=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-i),yield*this.pushNewline(),"stream"}return yield rn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let i=this.peek(3);if((i==="---"||i==="...")&&Ie(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&&!Ie(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Ie(i)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(e[i]){case"#":yield*this.pushCount(e.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(Ds),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,i,n=-1;do e=yield*this.pushNewline(),e>0?(i=yield*this.pushSpaces(!1),this.indentValue=n=i):i=0,i+=yield*this.pushSpaces(!0);while(e+i>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&r[0]!=="#"||n===0&&(r.startsWith("---")||r.startsWith("..."))&&Ie(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield rn.FLOW_END,yield*this.parseLineStart();let a=0;for(;r[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),r[a]){case void 0:return"flow";case"#":return yield*this.pushCount(r.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(Ds),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ie(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),i=this.buffer.indexOf(e,this.pos+1);if(e==="'")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 n=this.buffer.substring(0,i),r=n.indexOf(`
|
|
127
127
|
`,this.pos);if(r!==-1){for(;r!==-1;){let a=this.continueScalar(r+1);if(a===-1)break;r=n.indexOf(`
|
|
128
|
-
`,a)}r!==-1&&(i=r-(n[r-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 e=this.pos;for(;;){let i=this.buffer[++e];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)}r!==-1&&(i=r-(n[r-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 e=this.pos;for(;;){let i=this.buffer[++e];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=>Ie(i)||i==="#")}*parseBlockScalar(){let e=this.pos-1,i=0,n;e:for(let a=this.pos;n=this.buffer[a];++a)switch(n){case" ":i+=1;break;case`
|
|
129
129
|
`:e=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(!n&&!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(e+1);if(a===-1)break;e=this.buffer.indexOf(`
|
|
131
131
|
`,a)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let r=e+1;for(n=this.buffer[r];n===" ";)n=this.buffer[++r];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
|
|
132
132
|
`;)n=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let a=e-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
-
`&&a>=this.pos&&a+1+i>s)e=a;else break}while(!0);return yield
|
|
133
|
+
`&&a>=this.pos&&a+1+i>s)e=a;else break}while(!0);return yield rn.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,i=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===":"){let a=this.buffer[n+1];if(Ie(a)||e&&Vr.has(a))break;i=n}else if(Ie(r)){let a=this.buffer[n+1];if(r==="\r"&&(a===`
|
|
134
134
|
`?(n+=1,r=`
|
|
135
|
-
`,a=this.buffer[n+1]):i=n),a==="#"||e
|
|
136
|
-
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e
|
|
135
|
+
`,a=this.buffer[n+1]):i=n),a==="#"||e&&Vr.has(a))break;if(r===`
|
|
136
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Vr.has(r))break;i=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield rn.SCALAR,yield*this.pushToIndex(i+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,i){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(i&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Ds),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,n=this.charAt(1);if(Ie(n)||i&&Vr.has(n)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,i=this.buffer[e];for(;!Ie(i)&&i!==">";)i=this.buffer[++e];return yield*this.pushToIndex(i===">"?e+1:e,!1)}else{let e=this.pos+1,i=this.buffer[e];for(;i;)if(Zy.has(i))i=this.buffer[++e];else if(i==="%"&&Nd.has(this.buffer[e+1])&&Nd.has(this.buffer[e+2]))i=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
137
137
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let i=this.pos-1,n;do n=this.buffer[++i];while(n===" "||e&&n===" ");let r=i-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=i),r}*pushUntil(e){let i=this.pos,n=this.buffer[i];for(;!e(n);)n=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let i=this.pos-1,n;do n=this.buffer[++i];while(n===" "||e&&n===" ");let r=i-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=i),r}*pushUntil(e){let i=this.pos,n=this.buffer[i];for(;!e(n);)n=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};bd.Lexer=qs});var zs=C(kd=>{"use strict";var Ws=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let i=0,n=this.lineStarts.length;for(;i<n;){let a=i+n>>1;this.lineStarts[a]<e?i=a+1:n=a}if(this.lineStarts[i]===e)return{line:i+1,col:1};if(i===0)return{line:0,col:e};let r=this.lineStarts[i-1];return{line:i,col:e-r+1}}}};kd.LineCounter=Ws});var Gs=C(Pd=>{"use strict";var tN=Kn("process"),Sd=qr(),iN=Vs();function bt(t,e){for(let i=0;i<t.length;++i)if(t[i].type===e)return!0;return!1}function Ed(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Cd(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Wr(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function li(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function zr(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let i=0;i<e.length;++i)t.push(e[i])}function Rd(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!bt(e.start,"explicit-key-ind")&&!bt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Cd(e.value)?e.value.end?zr(e.value.end,e.sep):e.value.end=e.sep:zr(e.start,e.sep),delete e.sep)}var Js=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new iN.Lexer,this.onNewLine=e}*parse(e,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,i))yield*this.next(n);i||(yield*this.end())}*next(e){if(this.source=e,tN.env.LOG_TOKENS&&console.log("|",Sd.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let i=Sd.tokenType(e);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+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let n=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let i=e??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 n=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in n?n.indent:0:i.type==="flow-collection"&&n.type==="document"&&(i.indent=0),i.type==="flow-collection"&&Rd(i),n.type){case"document":n.value=i;break;case"block-scalar":n.props.push(i);break;case"block-map":{let r=n.items[n.items.length-1];if(r.value){n.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=i;else{Object.assign(r,{key:i,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=n.items[n.items.length-1];r.value?n.items.push({start:[],value:i}):r.value=i;break}case"flow-collection":{let r=n.items[n.items.length-1];!r||r.value?n.items.push({start:[],key:i,sep:[]}):r.sep?r.value=i:Object.assign(r,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let r=i.items[i.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Ed(r.start)===-1&&(i.indent===0||r.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(n.type==="document"?n.end=r.start:n.items.push({start:r.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 e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Ed(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let i=Wr(this.peek(2)),n=li(i),r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let 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(e){let i=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){
|
|
140
|
+
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let i=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){zr(r,i.start),r.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(r&&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>e.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":r||i.value?(a.push(this.sourceToken),e.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):r||i.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(bt(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(Cd(i.key)&&!bt(i.sep,"newline")){let o=li(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(bt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=li(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||r?e.items.push({start:a,key:null,sep:[this.sourceToken]}):bt(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);r||i.value?(e.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(e);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!bt(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 n&&e.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let i=e.items[e.items.length-1];switch(this.type){case"newline":if(i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){zr(r,i.start),r.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=e.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;i.value||bt(i.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let i=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?e.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?e.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 r=this.flowScalar(this.type);!i||i.value?e.items.push({start:[],key:r,sep:[]}):i.sep?this.stack.push(r):Object.assign(i,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let r=Wr(n),a=li(r);Rd(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let i=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
142
|
-
`,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Hr(e),n=oi(i);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Hr(e),n=oi(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};fd.Parser=Ts});var vd=C(en=>{"use strict";var dd=gs(),Iy=Wi(),Zi=Gi(),_y=mo(),Oy=M(),jy=xs(),hd=Is();function pd(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new jy.LineCounter||null,prettyErrors:e}}function $y(t,e={}){let{lineCounter:i,prettyErrors:n}=pd(e),r=new hd.Parser(i?.addNewLine),a=new dd.Composer(e),o=Array.from(a.compose(r.parse(t)));if(n&&i)for(let s of o)s.errors.forEach(Zi.prettifyError(t,i)),s.warnings.forEach(Zi.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function md(t,e={}){let{lineCounter:i,prettyErrors:n}=pd(e),r=new hd.Parser(i?.addNewLine),a=new dd.Composer(e),o=null;for(let s of a.compose(r.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Zi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(Zi.prettifyError(t,i)),o.warnings.forEach(Zi.prettifyError(t,i))),o}function Hy(t,e,i){let n;typeof e=="function"?n=e:i===void 0&&e&&typeof e=="object"&&(i=e);let r=md(t,i);if(!r)return null;if(r.warnings.forEach(a=>_y.warn(r.options.logLevel,a)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},i))}function My(t,e,i){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:i===void 0&&e&&(i=e),typeof i=="string"&&(i=i.length),typeof i=="number"){let r=Math.round(i);i=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=i??e??{};if(!r)return}return Oy.isDocument(t)&&!n?t.toString(i):new Iy.Document(t,n,i).toString(i)}en.parse=Hy;en.parseAllDocuments=$y;en.parseDocument=md;en.stringify=My});var Os=C(z=>{"use strict";var Ly=gs(),Dy=Wi(),Fy=Xo(),_s=Gi(),By=xi(),Nt=M(),qy=mt(),Vy=Q(),zy=gt(),Wy=wt(),Jy=jr(),Ky=Ps(),Gy=xs(),Uy=Is(),Lr=vd(),gd=Ri();z.Composer=Ly.Composer;z.Document=Dy.Document;z.Schema=Fy.Schema;z.YAMLError=_s.YAMLError;z.YAMLParseError=_s.YAMLParseError;z.YAMLWarning=_s.YAMLWarning;z.Alias=By.Alias;z.isAlias=Nt.isAlias;z.isCollection=Nt.isCollection;z.isDocument=Nt.isDocument;z.isMap=Nt.isMap;z.isNode=Nt.isNode;z.isPair=Nt.isPair;z.isScalar=Nt.isScalar;z.isSeq=Nt.isSeq;z.Pair=qy.Pair;z.Scalar=Vy.Scalar;z.YAMLMap=zy.YAMLMap;z.YAMLSeq=Wy.YAMLSeq;z.CST=Jy;z.Lexer=Ky.Lexer;z.LineCounter=Gy.LineCounter;z.Parser=Uy.Parser;z.parse=Lr.parse;z.parseAllDocuments=Lr.parseAllDocuments;z.parseDocument=Lr.parseDocument;z.stringify=Lr.stringify;z.visit=gd.visit;z.visitAsync=gd.visitAsync});import{execFile as KE,spawn as yl}from"node:child_process";import{createHash as GE}from"node:crypto";import{existsSync as im}from"node:fs";import Ye from"node:path";import{promisify as UE}from"node:util";import{spawn as Nm}from"node:child_process";import Xa from"node:path";var bm=1e3,Sm=2;async function Al(t){let e=t.pid;if(e===void 0){t.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&Xa.win32.isAbsolute(i)?Xa.win32.resolve(i):"C:\\Windows",r=Xa.win32.join(n,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(f,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(f))};try{c=Nm(r,["/pid",String(e),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",f=>u(f===0)),l=setTimeout(()=>u(!1,!0),bm)}catch{u(!1)}});for(let o=0;o<Sm;o+=1)if(await a()){t.kill("SIGKILL");return}t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.stderr?.destroy();return}try{process.kill(-e,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}t.kill("SIGKILL")}var wa=Pl(Os(),1);import{promises as Th}from"fs";import nt from"path";import{createHash as Zy}from"node:crypto";import{promises as Te}from"node:fs";import Se from"node:path";import{TextDecoder as eN}from"node:util";import js from"path";var Yy=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Xy=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Qy(t){return t.toLowerCase().startsWith(".env")}function We(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>Qy(n))?"environment-file":i.some(n=>Xy.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>Yy.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function wd(t,e){let i=We(e);if(i)return i;let n=js.resolve(t.projectRoot,...e.split("/")),r=js.relative(t.projectRoot,t.nativeRoot).replaceAll("\\","/"),a=e.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===js.resolve(t.configFile)?"native-runtime":null}function bt(t){return t!==0&&t!==0n&&t!=="0"}function se(t,e){return bt(t.dev)&&bt(e.dev)&&bt(t.ino)&&bt(e.ino)}function F(t,e){let i=bt(t.dev)&&bt(e.dev);if(i&&t.dev!==e.dev)return!1;let n=bt(t.ino)&&bt(e.ino);return n&&t.ino!==e.ino?!1:i&&n?!0:t.birthtime===e.birthtime}var Fr=1024*1024;function $s(t,e){let i=Se.relative(t,e);return i===""||!Se.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Se.sep}`)}function tN(t){let e=Se.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||Se.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),n=We(t);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${t}`);return t}function iN(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function nN(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Dr(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?F(i,n):F(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function yd(t){let e=await Te.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await Te.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function rN(t,e){let i=Se.resolve(t),n=Se.resolve(e);if(!$s(i,n))throw new Error("Native artifact path is outside its root");let r=[await yd(i)],a=i;for(let o of Se.relative(i,n).split(Se.sep).filter(Boolean)){a=Se.join(a,o);let s=await yd(a);if(!$s(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Nd(t){for(let e of t){let i=await Te.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!nN(e,i)||await Te.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function Ie(t){let e=tN(t.ref),i=iN(t.maxBytes??Fr),n=Se.resolve(t.root,...e.split("/")),r=await rN(t.root,Se.dirname(n));await t.hooks?.afterParentChainCaptured?.();let a=await Te.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await Te.realpath(n);if(!$s(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await Te.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Te.lstat(n),Te.realpath(n)]);if(await Nd(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Dr(a,c)||!Dr(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let f=[],d=0,p=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let k=i+1-d,N=await s.read(p,0,Math.min(p.length,k),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);f.push(Buffer.from(p.subarray(0,N.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),Te.lstat(n),Te.realpath(n)]);if(await Nd(r),!h.isFile()||h.isSymbolicLink()||v!==o||!Dr(c,m)||!Dr(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let w=Buffer.concat(f,d),E;try{E=new eN("utf-8",{fatal:!0}).decode(w)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:d,hash:Zy("sha256").update(w).digest("hex"),text:E}}finally{await s.close()}}import{randomUUID as aN}from"crypto";import{promises as re}from"fs";import _e from"path";function Ms(t,e){let i=_e.relative(t,e);return i===""||!_e.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${_e.sep}`)}function oN(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Hs(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?F(i,n):F(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function bd(t){let e=await re.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await re.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function tn(t){for(let e of t){let i=await re.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!oN(e,i)||await re.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function sN(t,e){let i=_e.resolve(t),n=_e.resolve(e);if(!Ms(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let r=[await bd(i)],a=_e.relative(i,n).split(_e.sep).filter(Boolean),o=i;for(let s of a){await tn(r),o=_e.join(o,s);try{await re.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await bd(o);if(!Ms(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await tn(r),r}async function cN(t){let e;try{e=await re.open(t,"r"),await e.sync()}catch(i){let n=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw i}finally{await e?.close()}}async function lN(t,e,i={}){let n=_e.dirname(t),r=i.containedRoot?await sN(i.containedRoot,n):null;r||await re.mkdir(n,{recursive:!0});let a=_e.join(n,`.${_e.basename(t)}.${aN()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await re.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([re.lstat(a),re.realpath(a)]);if(await tn(r),!c.isFile()||c.isSymbolicLink()||!Hs(s,c)||!Ms(r[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Hs(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?.(),r){await tn(r);let c=await re.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Hs(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await re.link(a,t),await re.unlink(a)):await re.rename(a,t),await cN(n)}catch(c){if(await o?.close(),!r)await re.rm(a,{force:!0});else try{await tn(r),await re.rm(a,{force:!0})}catch{}throw c}}async function Ze(t,e,i={}){await lN(t,e,i)}async function Oe(t,e,i={}){await Ze(t,JSON.stringify(e,null,2)+`
|
|
143
|
-
`,i)}var Ds=Pl(Os(),1);import Br from"path";var zr=64*1024,qr=1024,Vr=64,Fs=5,uN=[".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/**"],de={include:["**/*"],exclude:[...uN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function fN(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Br.posix.isAbsolute(i)||Br.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return n}function Ft(t){let e=fN(t,"native.artifact_root");return e.length===0?".":e.join("/")}function kd(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Bs(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim().replaceAll("\\","/");if(n.length===0||Br.posix.isAbsolute(n)||Br.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function nn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Ed(t,e,i){let n=t??e;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function Wr(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>qr)throw new Error(`${e} exceeds ${qr} characters`);let i=0;for(let n=0;n<t.length;n+=1)t[n]==="?"?i+=1:t[n]==="*"&&(i+=1,t[n+1]==="*"&&(n+=1));if(i>Vr)throw new Error(`${e} contains more than ${Vr} wildcard tokens`);return t}function Sd(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(n=>Wr(n,e)))].sort((n,r)=>n.localeCompare(r,"en"))}function Ls(t,e,i){let n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function dN(t){if(t===void 0)return{...de,include:[...de.include],exclude:[...de.exclude]};let e=nn(t,"native.snapshot");return{include:Sd(e.include,"native.snapshot.include",de.include),exclude:Sd(e.exclude,"native.snapshot.exclude",de.exclude),max_files:Ls(e.max_files,de.max_files,"native.snapshot.max_files"),max_total_bytes:Ls(e.max_total_bytes,de.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Ls(e.max_duration_ms,de.max_duration_ms,"native.snapshot.max_duration_ms")}}function hN(t){if(t===void 0)return;let e=nn(t,"native.pending_root_move"),i=e.id,n=e.from_artifact_root,r=e.to_artifact_root,a=e.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let s=nn(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Ft(n),toArtifactRoot:Ft(r),stage:a,...o?{cleanup:o}:{}}}function pN(t,e={}){let i=nn(t,"native"),n=i.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let r=i.clarification_mode??"sequential";if(r!=="sequential"&&r!=="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??Fs;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=hN(i.pending_root_move);return{artifact_root:Ft(n),language:Ed(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:dN(i.snapshot),...s?{pending_root_move:s}:{}}}function mN(t){let e=nn(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=e.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:kd(e.artifact_layout),language:Ed(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function vN(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function gN(t,e,i,n,r){let a=t.schema!==void 0;if(!(a||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!a)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=t.workflows??[t.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(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:n,...e?{native:e}:{},...i?{classic:i}:{}}}function Jr(t,e={}){let i=(0,Ds.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let n=i.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=n,a=vN(r.ambient_resume),o=r.native===void 0?void 0:pN(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=r.classic===void 0?void 0:mN(r.classic),c=gN(r,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function qs(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Ft(t),language:e,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:Fs,snapshot:{...de,include:[...de.include],exclude:[...de.exclude]}}}}import{createHash as yN}from"crypto";import{promises as Ur}from"fs";import St from"path";import{constants as Kr,promises as Bt}from"fs";var je=class extends Error{reason;constructor(e,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=e}};function Vs(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Rd(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function rn(t){return{dev:t.dev,ino:t.ino,birthtime:Vs(t)}}function Gr(t,e){let i=rn(t),n=rn(e);return se(i,n)?F(i,n):F(i,n)&&Vs(t)===Vs(e)&&Rd(t)===Rd(e)&&t.size===e.size}async function si(t,e,i={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let n=i.label??"file",r=i.bigint===!0,a=await Bt.lstat(t,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new je("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new je("too-large",`${n} exceeds ${e} bytes`);let o=await Bt.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:rn(a)});let s=process.platform==="win32"?Kr.O_RDONLY:Kr.O_RDONLY|Kr.O_NOFOLLOW|Kr.O_NONBLOCK,c;try{c=await Bt.open(t,s)}catch(l){throw l.code==="ELOOP"?new je("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:r}),Bt.lstat(t,{bigint:r}),Bt.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!Gr(a,l)||!Gr(a,u))throw new je("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:f,identity:rn(l)}),await i.hooks?.afterOpen?.();let d=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let E=e+1-p,{bytesRead:k}=await c.read(m,0,Math.min(m.length,E),null);if(k===0)break;if(p+=k,p>e)throw new je("too-large",`${n} exceeds ${e} bytes`);d.push(Buffer.from(m.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([c.stat({bigint:r}),Bt.lstat(t,{bigint:r}),Bt.realpath(t)]);if(!v.isFile()||v.isSymbolicLink()||w!==o||!Gr(a,h)||!Gr(a,v))throw new je("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:w,identity:rn(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:w}}finally{await c.close()}}function wN(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function zs(t,e){let i=St.relative(t,e);return i===""||!St.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${St.sep}`)}async function Cd(t,e){let i=St.resolve(t),n=await Ur.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Ur.realpath(i)}async function Pd(t,e,i,n){let r=t;for(let a=0;a<i.length;a++){r=St.join(r,i[a]);let o;try{o=await Ur.lstat(r)}catch(u){if(wN(u))return{exists:!1,kind:"missing"};throw u}let s=St.relative(t,r).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${n.label} ancestor ${s} must be a real directory`);if(c&&(n.expected==="file"&&!o.isFile()||n.expected==="directory"&&!o.isDirectory()||n.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let l=await Ur.realpath(r);if(!zs(e,l))throw new Error(`${n.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function an(t,e,i){let n=Bs(e,i.label),r=St.resolve(t),a=await Cd(r,i.label),o=n.split("/"),s=St.resolve(r,...o);if(!zs(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Pd(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function ci(t,e,i,n){let r=await an(t,e,{label:n.label,expected:"file"});if(!r.exists){let o=new Error(`${n.label} does not exist`);throw o.code="ENOENT",o}let a=await Cd(r.projectRoot,n.label);return si(r.target,i,{...n,verify:async(o,s)=>{if(!zs(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Pd(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var on=".comet/config.yaml";function NN(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Ws(t,e={}){return(await Yr(t,e)).document}async function bN(t){try{return(await ci(t,on,zr,{label:on})).bytes}catch(e){if(NN(e))return null;throw e}}function SN(t){return t?{exists:!0,sha256:yN("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Yr(t,e={}){let i=await bN(t);return{document:i?Jr(i.toString("utf8"),e):null,identity:SN(i)}}var jP=16*1024;import{promises as li}from"fs";import K from"path";import PN from"os";var Xr=".comet/config.yaml";async function Ks(t){try{return await li.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function AN(t){try{let e=await li.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function sn(t,e){let i=K.relative(t,e);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}async function cn(t){let e=[],i=t;for(;!await Ks(i);){let r=K.dirname(i);if(r===i)break;e.push(K.basename(i)),i=r}let n=await li.realpath(i);return K.resolve(n,...e.reverse())}async function Id(t){try{return(await li.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Qr(t){let e=K.resolve(t);try{(await li.stat(e)).isDirectory()||(e=K.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let i=e,n=K.resolve(PN.homedir());for(;;){if(!(e===n&&i!==n)){let o=K.join(e,...Xr.split("/")),s=e===i||await AN(o);if(await Ks(o)&&s)return e}if(await Ks(K.join(e,".git")))return e;let a=K.dirname(e);if(a===e)return i;e=a}}function Zr(t){return Ft(t)}async function xN(t,e){let i=Zr(e),n=K.resolve(t,...i.split("/")),r=await li.realpath(t),a=await cn(n);if(!sn(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function Gs(t,e){let i=Zr(e),n=await xN(t,i),r=K.join(n,"comet");if(await Id(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([cn(n),cn(r)]);if(!sn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:K.resolve(t),configFile:K.join(t,...Xr.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:K.join(r,"specs"),changesDir:K.join(r,"changes"),archiveDir:K.join(r,"archive"),runtimeDir:K.join(r,"runtime"),locksDir:K.join(r,"runtime","locks"),transactionsDir:K.join(r,"runtime","transactions")}}function ae(t,e){return sn(K.resolve(t),K.resolve(e))}async function q(t,e){let i=K.resolve(t),n=K.resolve(e);if(!sn(i,n))throw new Error(`Path is outside the Native root: ${e}`);if(await Id(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[r,a]=await Promise.all([cn(i),cn(n)]);if(!sn(r,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}var Us=de;var ea=Wr;function IN(t="docs",e="en"){return qs(t,e)}async function qt(t){let e=(await Ws(t))?.config??null;return e?.native?e:null}async function ln(t){let e=await qt(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function _d(t){let e=await Qr(t.startPath),i=await qt(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${Xr} 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 n=t.explicitArtifactRoot?Zr(t.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??IN(n??"docs"),a=await Gs(e,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as sb}from"fs";import cb from"path";import{AsyncLocalStorage as _N}from"async_hooks";import{randomUUID as $d}from"crypto";import{promises as ke}from"fs";import Hd from"os";import ce from"path";var Od=16*1024,Md=".coordinator",ON=5e3,jd=new _N,ta=new Map;function jN(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function $N(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let i=t;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: ${e}`);return i}function Ld(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function Ys(t,e){let i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},n={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return se(i,n)?F(i,n):F(i,n)&&t.size===e.size}function Xs(t,e){return Ys(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function et(t){let e,i;try{let n=await si(t,Od,{bigint:!0,label:"Native lock"});e=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof je?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Od} bytes: ${t}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:n}):new Error(`Native lock changed while reading: ${t}`,{cause:n}):n}return{file:t,owner:$N(JSON.parse(e.toString("utf8")),t),identity:Ld(i)}}async function HN(t){return(await et(t))?.owner??null}function Dd(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==Hd.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=qN(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function MN(t,e){try{await ke.lstat(e);return}catch(i){if(i.code!=="ENOENT")throw i}try{await ke.rename(t,e)}catch(i){if(i.code!=="ENOENT")throw i}}async function Qs(t,e){let i=await et(t.file);if(!i)return"missing";if(i.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Xs(i.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await ke.mkdir(e,{recursive:!0});let n=ce.join(e,`${ce.basename(t.file)}.${t.owner.id}.${$d()}.removed`);try{await ke.rename(t.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await et(n);if(!r||r.owner.id!==t.owner.id||!Ys(r.identity,t.identity))throw await MN(n,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await ke.rm(n,{force:!0}),"removed"}function Fd(t){return{id:$d(),pid:process.pid,hostname:Hd.hostname(),createdAt:new Date().toISOString(),operation:t}}async function Bd(t,e){let i;try{i=await ke.open(t,"wx")}catch(n){if(n.code==="EEXIST"){let r=await HN(t);throw new Error(`Native lock is already held: ${t}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(e,null,2)+`
|
|
144
|
-
`,"utf8"),await i.sync(),Ld(await i.stat({bigint:!0}))}finally{await i.close()}}async function LN(t,e){let i=await q(t.nativeRoot,t.locksDir);await ke.mkdir(i,{recursive:!0});let n=await q(t.nativeRoot,ce.join(i,Md));await ke.mkdir(n,{recursive:!0});let r=Fd(e),a=ce.join(n,`.${r.id}.tmp`),o=ce.join(n,`${r.id}.claim`);try{let s=await Bd(a,r);await ke.rename(a,o);let c=await et(o);if(!c||!Ys(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.nativeRoot,locksDir:i,owner:r,identity:c.identity}}finally{await ke.rm(a,{force:!0})}}async function DN(t){let e=ce.dirname(t.file),i=!1,n=ce.basename(t.file);for(let r of await ke.readdir(e,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=ce.join(e,r.name);if(ce.resolve(a)!==ce.resolve(t.file))try{let o=await et(a),s=Dd(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Qs(o,e);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function qd(t){let e=await et(t.file);if(e){if(e.owner.id!==t.owner.id||!Xs(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await Qs(e,ce.dirname(t.file))}}async function FN(t,e){let i=Date.now()+ON;for(;;){let n=await LN(t,e);if(!await DN(n))return n;if(await qd(n),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(r=>setTimeout(r,2+Math.floor(Math.random()*7)))}}async function BN(t){let e=ta.get(t)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=e.then(()=>n);return ta.set(t,r),await e,()=>{i(),ta.get(t)===r&&ta.delete(t)}}async function Vd(t,e,i){let n=ce.resolve(t.locksDir),r=jd.getStore();if(r?.has(n))return i();let a=await BN(n);try{let o=await FN(t,e),s=new Map(r??[]);return s.set(n,o),await jd.run(s,async()=>{try{return await i()}finally{await qd(o)}})}finally{a()}}async function un(t,e,i){return Vd(t,`acquire ${e}`,async()=>{let n=await q(t.nativeRoot,t.locksDir);await ke.mkdir(n,{recursive:!0});let r=await q(t.nativeRoot,ce.join(n,jN(e))),a=Fd(i),o=await Bd(r,a);return{file:r,nativeRoot:t.nativeRoot,locksDir:n,owner:a,identity:o}})}async function fn(t){await et(t.file)&&await Vd(t,`release ${ce.basename(t.file)}`,async()=>{let e=await et(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Xs(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let i=ce.join(t.locksDir,Md);await Qs(e,i)})}function qN(t){try{return process.kill(t,0),!0}catch(e){let i=e.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function zd(t){return Dd(await et(t))}import it from"path";import{TextDecoder as XN}from"util";import{createHash as VN}from"node:crypto";import{constants as ia,promises as $e}from"node:fs";import He from"node:path";import{TextDecoder as zN}from"node:util";function ra(t,e){let i=He.relative(t,e);return i===""||!He.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${He.sep}`)}function WN(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function JN(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function KN(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function na(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Zs(t,e){let i=await $e.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await $e.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function GN(t,e,i){let n=He.resolve(t),r=He.resolve(e);if(!ra(n,r))throw new Error(`${i} is outside its managed root`);let a=[await Zs(n,i)],o=n;for(let s of He.relative(n,r).split(He.sep).filter(Boolean)){await Vt(a,i),o=He.join(o,s);let c=await Zs(o,i);if(!ra(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Vt(a,i),a}async function Vt(t,e){for(let i of t){let n=await $e.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!JN(i,n)||await $e.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function UN(t,e,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-r,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>e)throw new Error(`${i} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function tt(t){let e=WN(t.maxBytes),i=He.resolve(t.file),n=await GN(t.root,He.dirname(i),t.label),r=await Promise.all((t.forbiddenRoots??[]).map(u=>Zs(He.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Vt(n,t.label);let a=await $e.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=KN(a),s=await $e.realpath(i);if(!ra(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(r.some(u=>ra(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?ia.O_RDONLY:ia.O_RDONLY|ia.O_NOFOLLOW|ia.O_NONBLOCK,l=await $e.open(i,c);try{let u=await l.stat();await t.hooks?.afterOpen?.();let[f,d]=await Promise.all([$e.lstat(i),$e.realpath(i)]);if(await Vt(n,t.label),await Vt(r,t.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!na(o,u)||!na(o,f))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let p=await UN(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),$e.lstat(i),$e.realpath(i)]);if(await Vt(n,t.label),await Vt(r,t.label),!h.isFile()||h.isSymbolicLink()||v!==s||!na(o,m)||!na(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:p,hash:VN("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Wd(t){let e=await tt(t),i;try{i=new zN("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t.label} is not valid UTF-8`,{cause:n})}return{...e,text:i}}var QN=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),ZN=new Set(["id","type","source","target","staged","backup"]),eb=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),tb=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Gd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var ib=256*1024,EA=1024*1024,RA=16*1024;var CA=64*1024*1024;var nb=new XN("utf-8",{fatal:!0});function oa(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function sa(t,e,i){let n=Object.keys(t).filter(r=>!e.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Ud(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function ec(t,e){if(typeof t!="string"||t.length===0||it.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function aa(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function Jd(t,e){if(ec(t,e),t.includes("\\")||t!==it.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function rb(t,e){let i=oa(t,`transaction operations[${e}]`);if(sa(i,ZN,`transaction operations[${e}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${e}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);ec(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&ec(i[n],`transaction operation ${i.id} ${n}`);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 Yd(t){let e=oa(t,"Native Archive transaction journal");if(sa(e,eb,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!Gd.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!Ud(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(aa(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=e.operations.map((s,c)=>{let l=oa(s,`Archive transaction operations[${c}]`);if(sa(l,tb,`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`);Jd(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Jd(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&aa(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(aa(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`);aa(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=i.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let r=`runtime/transactions/${e.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.change}$`,"u").test(a[0].target)||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(`${r}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${r}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:i}}function ab(t){let e=oa(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return Yd(e);if(sa(e,QN,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!Gd.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!it.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!it.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!Ud(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let i=e.operations.map(rb),n=i.map(r=>r.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:i}}function ob(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return it.join(t.transactionsDir,e)}function Xd(t,e){let i=ob(t,e);return{directory:i,journal:it.join(i,"transaction.json"),events:it.join(i,"events.jsonl"),staged:it.join(i,"staged"),backups:it.join(i,"backups")}}async function ic(t,e){let i=Xd(t,e);return await Promise.all(Object.values(i).map(n=>q(t.nativeRoot,n))),i}async function nc(t,e,i={}){let n=await ic(t,e),r=await tt({root:t.nativeRoot,file:n.journal,maxBytes:ib,label:`Native transaction journal ${e}`,hooks:i.hooks}),a=JSON.parse(nb.decode(r.bytes)),o=ab(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function lb(t,e){let i;try{i=await sb.readdir(t.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let r=await nc(t,n.name);if(r.id!==e&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function ub(t,e){let i=Date.now()+5e3,n=cb.join(t.locksDir,"root-move.lock");for(;;)try{return await un(t,"root-move",e)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await zd(n);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw r;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function kt(t,e,i,n){let r=await ub(t,e);try{if(await ln(t.projectRoot),await lb(t,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await fn(r)}}function Qd(t){return Number.isSafeInteger(t)&&t>=1}async function Zd(t){if(!Qd(t.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(t.next.revision!==t.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let e=await t.read();if(!Qd(e.revision))throw new Error("Native current revision must be a positive integer");let i=t.equals??((n,r)=>JSON.stringify(n)===JSON.stringify(r));if(e.revision===t.next.revision&&i(e,t.next))return e;if(e.revision!==t.expectedRevision)throw t.conflict(e.revision);return await t.write(t.next),t.next}import{createHash as fa}from"crypto";import{spawn as uh}from"node:child_process";import{promises as U}from"fs";import V from"path";import{createHash as fb}from"crypto";function G(t){return fb("sha256").update(t).digest("hex")}var ca={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},fh=1e3,db=8*1024*1024,hb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,pb=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),mb=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),vb=new Set(["schema","include","exclude","hash"]),gb=new Set(["provider","gitSelection","physicalSelection","projection"]),wb=new Set(["provider","selection"]),yb=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Nb=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),bb=new Set(["schema","status","before","after"]),Sb=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),kb=new Set(["path","hash","size","type","gitObjectId"]),Eb=new Set(["path","size","type","reason"]),Rb=new Set(["ref","hash","count"]),Cb=new Set(["change-created","legacy-migration","explicit"]),Pb=new Set(["file","directory","other"]),Ab=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),da=/^[a-f0-9]{64}$/u,dh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,xb=new Set(["EACCES","EPERM"]),di=64*1024,lc=64*1024,Tb=6e4,Ib=1e3,_b=2,hh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Ob={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function jb(t){let e=t.deadlineMs??Tb;if(!Number.isSafeInteger(e)||e<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+e,gitProcess:t.gitProcess??{command:"git"}}}function Me(t){return Math.max(0,t.deadlineAt-Date.now())}function _(t){return Me(t)>=1}function rc(t){let e=t===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:t});return Object.assign(e,{code:"GIT_SNAPSHOT_TIMEOUT"})}function dn(t){return t.code==="GIT_SNAPSHOT_TIMEOUT"}function $b(t){let e={...Ob,...t};if(!Number.isSafeInteger(e.maxNodes)||e.maxNodes<1||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<1||!Number.isSafeInteger(e.maxPathBytes)||e.maxPathBytes<1||e.maxPathBytes>e.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return e}async function Hb(t,e){if(e.terminateTree){await e.terminateTree(t);return}let i=t.pid;if(i===void 0){t.kill("SIGKILL");return}if(process.platform==="win32"){let n=process.env.SystemRoot??process.env.WINDIR,r=n&&V.win32.isAbsolute(n)?V.win32.resolve(n):"C:\\Windows",a=V.win32.join(r,"System32","taskkill.exe");if(!V.win32.isAbsolute(a))throw t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,f=(d,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(d))};try{l=uh(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>f(!1)),l.once("close",d=>f(d===0)),u=setTimeout(()=>f(!1,!0),Ib),u.unref()}catch{f(!1)}});for(let s=0;s<_b;s+=1)if(await o()){t.kill("SIGKILL");return}throw t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(n){if(n.code!=="ESRCH")throw n}t.kill("SIGKILL")}function fc(t,e,i,n){let r=Me(t);if(r<1)throw rc();let a=t.gitProcess,o=uh(a.command,[...a.argsPrefix??[],"-C",e,...i],{stdio:[n?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),f=setTimeout(()=>{c=!0,l=Hb(o,a).then(()=>({error:null}),p=>({error:p}))},r);f.unref();let d=u.then(async p=>{if(clearTimeout(f),c){let m=await l;throw m?.error?rc(m.error):rc()}return{code:p,spawnError:s}});return{child:o,completion:d}}function Mb(t){let e={...hh,...t};if(!Number.isSafeInteger(e.maxRecords)||e.maxRecords<1||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<1||!Number.isSafeInteger(e.maxRecordBytes)||e.maxRecordBytes<1||e.maxRecordBytes>e.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return e}async function la(t,e,i,n=lc){let{child:r,completion:a}=fc(t,e,i,!1),o=[],s=[],c=0,l=0,u=!1;r.stdout.on("data",p=>{let m=Math.max(0,n-l);m>0&&o.push(Buffer.from(p).subarray(0,m)),l+=p.byteLength,l>n&&(u=!0)}),r.stderr.on("data",p=>{if(c>=di)return;let m=di-c,h=Buffer.from(p).subarray(0,m);s.push(h),c+=h.byteLength});let{code:f,spawnError:d}=await a;if(f===0&&d===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${d?`: ${d.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function ac(t){return{hash:t.digest,recordCount:t.recordCount,storedRecordCount:t.records.length,stdoutBytes:t.stdoutBytes,overflow:t.overflow}}function oc(t,e,i,n){if(n.outputChunkBytes!==void 0&&(!Number.isSafeInteger(n.outputChunkBytes)||n.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((r,a)=>{let{child:o,completion:s}=fc(t,e,i,n.stdin!==void 0),c=[],l=fa("sha256"),u=[],f=0,d=0,p=0,m=0,h=Buffer.alloc(0),v=!1,w=!1,E=!1,k=N=>{let S=0;for(;S<N.byteLength;){let g=N.indexOf(0,S),b=g<0?N.byteLength:g,y=N.subarray(S,b);if(!v&&y.byteLength>0&&(h.byteLength+y.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,w=!0):h=Buffer.concat([h,y])),g<0)break;m+=1,h.byteLength===0&&!v&&(E=!0);let R=h.byteLength+1;!v&&m<=n.maxRecords&&p+R<=n.maxBytes?(c.push(h),p+=R):w=!0,h=Buffer.alloc(0),v=!1,S=g+1}};o.stdout.on("data",N=>{l.update(N),d+=N.byteLength,d>n.maxBytes&&(w=!0);let S=n.outputChunkBytes;if(S===void 0){k(N);return}for(let g=0;g<N.byteLength;g+=S)k(N.subarray(g,Math.min(N.byteLength,g+S)))}),o.stderr.on("data",N=>{if(f>=di)return;let S=di-f,g=Buffer.from(N).subarray(0,S);u.push(g),f+=g.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:S})=>{let g=n.acceptedExitCodes??[0];if(N!==null&&g.includes(N)&&S===null&&!E&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:w,recordCount:m,stdoutBytes:d});return}a(new Error(`git ${i.join(" ")} failed${S?`: ${S.message}`:E||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function eh(t){let e=t.toString("utf8");if(!Buffer.from(e,"utf8").equals(t))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return e}async function Lb(t,e,i){let{child:n,completion:r}=fc(t,e,i,!1),a=[],o=0,s=!1;n.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),n.stderr.on("data",u=>{if(o>=di)return;let f=di-o,d=Buffer.from(u).subarray(0,f);a.push(d),o+=d.byteLength});let{code:c,spawnError:l}=await r;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function ua(t){let e=t.endsWith("/")?t.slice(0,-1):t;return e.length===0||e.includes("\\")||V.posix.isAbsolute(e)||/^[A-Za-z]:/u.test(e)||V.posix.normalize(e)!==e||e===".."||e.startsWith("../")||e.includes("\0")?null:e}function Db(t,e){return t.map(i=>{let n=ua(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${e} path`);return n})}async function Fb(t){let e=V.resolve(t);for(;;){try{return await U.lstat(V.join(e,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=V.dirname(e);if(i===e)return!1;e=i}}async function ph(t,e,i,n={}){let r={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},a=await oc(t,e,["ls-files","--stage","-z"],r);await n.afterStageBefore?.();let o=await oc(t,e,["ls-files","--cached","--others","--exclude-standard","-z"],r);await n.afterCombined?.();let s=await oc(t,e,["ls-files","--stage","-z"],r);return{stagedBefore:a,combined:o,stagedAfter:s}}function mh(t){return{stageBefore:ac(t.stagedBefore),combined:ac(t.combined),stageAfter:ac(t.stagedAfter)}}async function Bb(t,e,i=hh,n={}){if(!await Fb(e))return null;let r;try{r=await la(t,e,["rev-parse","--is-inside-work-tree"])}catch(w){throw dn(w)?w:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:w})}if(r.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let a;try{a=await ph(t,e,i,n)}catch(w){throw dn(w)?w:new Error("Native Git snapshot provider failed after repository detection",{cause:w})}let{stagedBefore:o,combined:s,stagedAfter:c}=a,l=new Set,u=new Map,f=new Set,d=w=>{for(let E of w){let k=eh(E),N=k.indexOf(" ");if(N<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let S=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(k.slice(0,N))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let g=ua(k.slice(N+1));if(g===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");l.add(g),S.stage==="0"&&u.set(g,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(g)}};d(o.records),d(c.records);let p=s.records.map(eh),m=Db(p,"combined"),h=new Set(m.filter(w=>!l.has(w))),v=new Set(m.filter((w,E)=>!l.has(w)&&p[E].endsWith("/")));for(let w of f)v.delete(w);return{tracked:l,trackedObjectIds:u,untracked:h,gitlinks:f,nestedRepositories:v,omissions:[],overflow:null,evidence:null,initialFence:mh(a)}}function Rt(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}function th(t){return t.stageBefore.overflow||t.combined.overflow||t.stageAfter.overflow}function qb(t,e){return!Rt(t.stageBefore,t.stageAfter)||!Rt(t.stageAfter,e.stageBefore)||!Rt(t.combined,e.combined)||!Rt(e.stageBefore,e.stageAfter)}async function Vb(t,e,i,n,r){let a;try{a=await ph(t,e,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw dn(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=mh(a),c=th(o)||th(s),l=qb(o,s);c&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),n.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(n.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:G(`comet.native.git-selection-overflow.v2
|
|
145
|
-
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var
|
|
142
|
+
`,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Wr(e),n=li(i);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Wr(e),n=li(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Pd.Parser=Js});var _d=C(on=>{"use strict";var Ad=js(),nN=Yi(),an=Zi(),rN=Io(),aN=M(),oN=zs(),xd=Gs();function Td(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new oN.LineCounter||null,prettyErrors:e}}function sN(t,e={}){let{lineCounter:i,prettyErrors:n}=Td(e),r=new xd.Parser(i?.addNewLine),a=new Ad.Composer(e),o=Array.from(a.compose(r.parse(t)));if(n&&i)for(let s of o)s.errors.forEach(an.prettifyError(t,i)),s.warnings.forEach(an.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Id(t,e={}){let{lineCounter:i,prettyErrors:n}=Td(e),r=new xd.Parser(i?.addNewLine),a=new Ad.Composer(e),o=null;for(let s of a.compose(r.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new an.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(an.prettifyError(t,i)),o.warnings.forEach(an.prettifyError(t,i))),o}function cN(t,e,i){let n;typeof e=="function"?n=e:i===void 0&&e&&typeof e=="object"&&(i=e);let r=Id(t,i);if(!r)return null;if(r.warnings.forEach(a=>rN.warn(r.options.logLevel,a)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},i))}function lN(t,e,i){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:i===void 0&&e&&(i=e),typeof i=="string"&&(i=i.length),typeof i=="number"){let r=Math.round(i);i=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=i??e??{};if(!r)return}return aN.isDocument(t)&&!n?t.toString(i):new nN.Document(t,n,i).toString(i)}on.parse=cN;on.parseAllDocuments=sN;on.parseDocument=Id;on.stringify=lN});var Gr=C(V=>{"use strict";var uN=js(),fN=Yi(),dN=hs(),Ks=Zi(),hN=Oi(),kt=M(),pN=gt(),mN=ee(),vN=yt(),gN=Nt(),wN=qr(),yN=Vs(),NN=zs(),bN=Gs(),Jr=_d(),jd=Ti();V.Composer=uN.Composer;V.Document=fN.Document;V.Schema=dN.Schema;V.YAMLError=Ks.YAMLError;V.YAMLParseError=Ks.YAMLParseError;V.YAMLWarning=Ks.YAMLWarning;V.Alias=hN.Alias;V.isAlias=kt.isAlias;V.isCollection=kt.isCollection;V.isDocument=kt.isDocument;V.isMap=kt.isMap;V.isNode=kt.isNode;V.isPair=kt.isPair;V.isScalar=kt.isScalar;V.isSeq=kt.isSeq;V.Pair=pN.Pair;V.Scalar=mN.Scalar;V.YAMLMap=vN.YAMLMap;V.YAMLSeq=gN.YAMLSeq;V.CST=wN;V.Lexer=yN.Lexer;V.LineCounter=NN.LineCounter;V.Parser=bN.Parser;V.parse=Jr.parse;V.parseAllDocuments=Jr.parseAllDocuments;V.parseDocument=Jr.parseDocument;V.stringify=Jr.stringify;V.visit=jd.visit;V.visitAsync=jd.visitAsync});import{execFile as xR,spawn as Hl}from"node:child_process";import{createHash as TR}from"node:crypto";import{existsSync as Cm}from"node:fs";import Xe from"node:path";import{promisify as IR}from"node:util";import{spawn as Jm}from"node:child_process";import po from"node:path";var Gm=1e3,Km=2;async function Wl(t){let e=t.pid;if(e===void 0){t.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&po.win32.isAbsolute(i)?po.win32.resolve(i):"C:\\Windows",r=po.win32.join(n,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(f,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(f))};try{c=Jm(r,["/pid",String(e),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",f=>u(f===0)),l=setTimeout(()=>u(!1,!0),Gm)}catch{u(!1)}});for(let o=0;o<Km;o+=1)if(await a()){t.kill("SIGKILL");return}t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.stderr?.destroy();return}try{process.kill(-e,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}t.kill("SIGKILL")}var _a=ho(Gr(),1);import{promises as ep}from"fs";import at from"path";import{createHash as RN}from"node:crypto";import{promises as _e}from"node:fs";import Ee from"node:path";import{TextDecoder as CN}from"node:util";import Us from"path";var kN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),SN=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function EN(t){return t.toLowerCase().startsWith(".env")}function Je(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>EN(n))?"environment-file":i.some(n=>SN.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>kN.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Od(t,e){let i=Je(e);if(i)return i;let n=Us.resolve(t.projectRoot,...e.split("/")),r=Us.relative(t.projectRoot,t.nativeRoot).replaceAll("\\","/"),a=e.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===Us.resolve(t.configFile)?"native-runtime":null}function St(t){return t!==0&&t!==0n&&t!=="0"}function ue(t,e){return St(t.dev)&&St(e.dev)&&St(t.ino)&&St(e.ino)}function B(t,e){let i=St(t.dev)&&St(e.dev);if(i&&t.dev!==e.dev)return!1;let n=St(t.ino)&&St(e.ino);return n&&t.ino!==e.ino?!1:i&&n?!0:t.birthtime===e.birthtime}var Ur=1024*1024;function Ys(t,e){let i=Ee.relative(t,e);return i===""||!Ee.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ee.sep}`)}function PN(t){let e=Ee.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||Ee.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),n=Je(t);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${t}`);return t}function AN(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function xN(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Kr(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return ue(i,n)?B(i,n):B(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function $d(t){let e=await _e.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await _e.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function TN(t,e){let i=Ee.resolve(t),n=Ee.resolve(e);if(!Ys(i,n))throw new Error("Native artifact path is outside its root");let r=[await $d(i)],a=i;for(let o of Ee.relative(i,n).split(Ee.sep).filter(Boolean)){a=Ee.join(a,o);let s=await $d(a);if(!Ys(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Hd(t){for(let e of t){let i=await _e.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!xN(e,i)||await _e.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function Re(t){let e=PN(t.ref),i=AN(t.maxBytes??Ur),n=Ee.resolve(t.root,...e.split("/")),r=await TN(t.root,Ee.dirname(n));await t.hooks?.afterParentChainCaptured?.();let a=await _e.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await _e.realpath(n);if(!Ys(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await _e.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),_e.lstat(n),_e.realpath(n)]);if(await Hd(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Kr(a,c)||!Kr(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let f=[],d=0,p=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let E=i+1-d,b=await s.read(p,0,Math.min(p.length,E),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);f.push(Buffer.from(p.subarray(0,b.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),_e.lstat(n),_e.realpath(n)]);if(await Hd(r),!h.isFile()||h.isSymbolicLink()||v!==o||!Kr(c,m)||!Kr(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let S=Buffer.concat(f,d),N;try{N=new CN("utf-8",{fatal:!0}).decode(S)}catch(E){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:E})}return{ref:e,size:d,hash:RN("sha256").update(S).digest("hex"),text:N}}finally{await s.close()}}import{randomUUID as IN}from"crypto";import{promises as oe}from"fs";import je from"path";function Qs(t,e){let i=je.relative(t,e);return i===""||!je.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${je.sep}`)}function _N(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Xs(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return ue(i,n)?B(i,n):B(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Md(t){let e=await oe.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await oe.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function sn(t){for(let e of t){let i=await oe.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!_N(e,i)||await oe.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function jN(t,e){let i=je.resolve(t),n=je.resolve(e);if(!Qs(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let r=[await Md(i)],a=je.relative(i,n).split(je.sep).filter(Boolean),o=i;for(let s of a){await sn(r),o=je.join(o,s);try{await oe.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Md(o);if(!Qs(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await sn(r),r}async function ON(t){let e;try{e=await oe.open(t,"r"),await e.sync()}catch(i){let n=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw i}finally{await e?.close()}}async function $N(t,e,i={}){let n=je.dirname(t),r=i.containedRoot?await jN(i.containedRoot,n):null;r||await oe.mkdir(n,{recursive:!0});let a=je.join(n,`.${je.basename(t)}.${IN()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await oe.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([oe.lstat(a),oe.realpath(a)]);if(await sn(r),!c.isFile()||c.isSymbolicLink()||!Xs(s,c)||!Qs(r[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Xs(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?.(),r){await sn(r);let c=await oe.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Xs(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await oe.link(a,t),await oe.unlink(a)):await oe.rename(a,t),await ON(n)}catch(c){if(await o?.close(),!r)await oe.rm(a,{force:!0});else try{await sn(r),await oe.rm(a,{force:!0})}catch{}throw c}}async function et(t,e,i={}){await $N(t,e,i)}async function Oe(t,e,i={}){await et(t,JSON.stringify(e,null,2)+`
|
|
143
|
+
`,i)}var ec=ho(Gr(),1);import Yr from"path";var ln=64*1024,Xr=1024,Qr=64,tc=5,HN=[".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/**"],me={include:["**/*"],exclude:[...HN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function MN(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Yr.posix.isAbsolute(i)||Yr.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return n}function qt(t){let e=MN(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Fd(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function ic(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim().replaceAll("\\","/");if(n.length===0||Yr.posix.isAbsolute(n)||Yr.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function cn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Bd(t,e,i){let n=t??e;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function Zr(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Xr)throw new Error(`${e} exceeds ${Xr} characters`);let i=0;for(let n=0;n<t.length;n+=1)t[n]==="?"?i+=1:t[n]==="*"&&(i+=1,t[n+1]==="*"&&(n+=1));if(i>Qr)throw new Error(`${e} contains more than ${Qr} wildcard tokens`);return t}function Ld(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(n=>Zr(n,e)))].sort((n,r)=>n.localeCompare(r,"en"))}function Zs(t,e,i){let n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function LN(t){if(t===void 0)return{...me,include:[...me.include],exclude:[...me.exclude]};let e=cn(t,"native.snapshot");return{include:Ld(e.include,"native.snapshot.include",me.include),exclude:Ld(e.exclude,"native.snapshot.exclude",me.exclude),max_files:Zs(e.max_files,me.max_files,"native.snapshot.max_files"),max_total_bytes:Zs(e.max_total_bytes,me.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Zs(e.max_duration_ms,me.max_duration_ms,"native.snapshot.max_duration_ms")}}function FN(t){if(t===void 0)return;let e=cn(t,"native.pending_root_move"),i=e.id,n=e.from_artifact_root,r=e.to_artifact_root,a=e.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let s=cn(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:qt(n),toArtifactRoot:qt(r),stage:a,...o?{cleanup:o}:{}}}function BN(t,e={}){let i=cn(t,"native"),n=i.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let r=i.clarification_mode??"sequential";if(r!=="sequential"&&r!=="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??tc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=FN(i.pending_root_move);return{artifact_root:qt(n),language:Bd(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:LN(i.snapshot),...s?{pending_root_move:s}:{}}}function DN(t){let e=cn(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=e.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Fd(e.artifact_layout),language:Bd(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function qN(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function VN(t,e,i,n,r){let a=t.schema!==void 0;if(!(a||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!a)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=t.workflows??[t.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(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:n,...e?{native:e}:{},...i?{classic:i}:{}}}function un(t,e={}){let i=(0,ec.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let n=i.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=n,a=qN(r.ambient_resume),o=r.native===void 0?void 0:BN(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=r.classic===void 0?void 0:DN(r.classic),c=VN(r,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function ea(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:qt(t),language:e,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:tc,snapshot:{...me,include:[...me.include],exclude:[...me.exclude]}}}}import{createHash as zN}from"crypto";import{promises as na}from"fs";import Et from"path";import{constants as ta,promises as Vt}from"fs";var $e=class extends Error{reason;constructor(e,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=e}};function nc(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Dd(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function fn(t){return{dev:t.dev,ino:t.ino,birthtime:nc(t)}}function ia(t,e){let i=fn(t),n=fn(e);return ue(i,n)?B(i,n):B(i,n)&&nc(t)===nc(e)&&Dd(t)===Dd(e)&&t.size===e.size}async function ui(t,e,i={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let n=i.label??"file",r=i.bigint===!0,a=await Vt.lstat(t,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new $e("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new $e("too-large",`${n} exceeds ${e} bytes`);let o=await Vt.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:fn(a)});let s=process.platform==="win32"?ta.O_RDONLY:ta.O_RDONLY|ta.O_NOFOLLOW|ta.O_NONBLOCK,c;try{c=await Vt.open(t,s)}catch(l){throw l.code==="ELOOP"?new $e("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:r}),Vt.lstat(t,{bigint:r}),Vt.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!ia(a,l)||!ia(a,u))throw new $e("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:f,identity:fn(l)}),await i.hooks?.afterOpen?.();let d=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let N=e+1-p,{bytesRead:E}=await c.read(m,0,Math.min(m.length,N),null);if(E===0)break;if(p+=E,p>e)throw new $e("too-large",`${n} exceeds ${e} bytes`);d.push(Buffer.from(m.subarray(0,E)))}await i.hooks?.beforeFinalCheck?.();let[h,v,S]=await Promise.all([c.stat({bigint:r}),Vt.lstat(t,{bigint:r}),Vt.realpath(t)]);if(!v.isFile()||v.isSymbolicLink()||S!==o||!ia(a,h)||!ia(a,v))throw new $e("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:fn(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:S}}finally{await c.close()}}function WN(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function rc(t,e){let i=Et.relative(t,e);return i===""||!Et.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Et.sep}`)}async function qd(t,e){let i=Et.resolve(t),n=await na.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return na.realpath(i)}async function Vd(t,e,i,n){let r=t;for(let a=0;a<i.length;a++){r=Et.join(r,i[a]);let o;try{o=await na.lstat(r)}catch(u){if(WN(u))return{exists:!1,kind:"missing"};throw u}let s=Et.relative(t,r).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${n.label} ancestor ${s} must be a real directory`);if(c&&(n.expected==="file"&&!o.isFile()||n.expected==="directory"&&!o.isDirectory()||n.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let l=await na.realpath(r);if(!rc(e,l))throw new Error(`${n.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function dn(t,e,i){let n=ic(e,i.label),r=Et.resolve(t),a=await qd(r,i.label),o=n.split("/"),s=Et.resolve(r,...o);if(!rc(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Vd(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Wt(t,e,i,n){let r=await dn(t,e,{label:n.label,expected:"file"});if(!r.exists){let o=new Error(`${n.label} does not exist`);throw o.code="ENOENT",o}let a=await qd(r.projectRoot,n.label);return ui(r.target,i,{...n,verify:async(o,s)=>{if(!rc(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Vd(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var hn=".comet/config.yaml";function JN(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function ac(t,e={}){return(await ra(t,e)).document}async function GN(t){try{return(await Wt(t,hn,ln,{label:hn})).bytes}catch(e){if(JN(e))return null;throw e}}function KN(t){return t?{exists:!0,sha256:zN("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function ra(t,e={}){let i=await GN(t);return{document:i?un(i.toString("utf8"),e):null,identity:KN(i)}}var wA=16*1024;import{promises as fi}from"fs";import J from"path";import ZN from"os";var oa=".comet/config.yaml";async function cc(t){try{return await fi.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function eb(t){try{let e=await fi.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function pn(t,e){let i=J.relative(t,e);return i===""||!J.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${J.sep}`)}async function mn(t){let e=[],i=t;for(;!await cc(i);){let r=J.dirname(i);if(r===i)break;e.push(J.basename(i)),i=r}let n=await fi.realpath(i);return J.resolve(n,...e.reverse())}async function zd(t){try{return(await fi.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function sa(t){let e=J.resolve(t);try{(await fi.stat(e)).isDirectory()||(e=J.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let i=e,n=J.resolve(ZN.homedir());for(;;){if(!(e===n&&i!==n)){let o=J.join(e,...oa.split("/")),s=e===i||await eb(o);if(await cc(o)&&s)return e}if(await cc(J.join(e,".git")))return e;let a=J.dirname(e);if(a===e)return i;e=a}}function ca(t){return qt(t)}async function tb(t,e){let i=ca(e),n=J.resolve(t,...i.split("/")),r=await fi.realpath(t),a=await mn(n);if(!pn(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function lc(t,e){let i=ca(e),n=await tb(t,i),r=J.join(n,"comet");if(await zd(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([mn(n),mn(r)]);if(!pn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:J.resolve(t),configFile:J.join(t,...oa.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:J.join(r,"specs"),changesDir:J.join(r,"changes"),archiveDir:J.join(r,"archive"),runtimeDir:J.join(r,"runtime"),locksDir:J.join(r,"runtime","locks"),transactionsDir:J.join(r,"runtime","transactions")}}function se(t,e){return pn(J.resolve(t),J.resolve(e))}async function q(t,e){let i=J.resolve(t),n=J.resolve(e);if(!pn(i,n))throw new Error(`Path is outside the Native root: ${e}`);if(await zd(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[r,a]=await Promise.all([mn(i),mn(n)]);if(!pn(r,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}var uc=me;var la=Zr;function nb(t="docs",e="en"){return ea(t,e)}async function zt(t){let e=(await ac(t))?.config??null;return e?.native?e:null}async function vn(t){let e=await zt(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Jd(t){let e=await sa(t.startPath),i=await zt(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${oa} 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 n=t.explicitArtifactRoot?ca(t.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??nb(n??"docs"),a=await lc(e,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as jb}from"fs";import Ob from"path";import{AsyncLocalStorage as rb}from"async_hooks";import{randomUUID as Ud}from"crypto";import{promises as Ce}from"fs";import Yd from"os";import fe from"path";var Gd=16*1024,Xd=".coordinator",ab=5e3,Kd=new rb,ua=new Map;function ob(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function sb(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let i=t;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: ${e}`);return i}function Qd(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function fc(t,e){let i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},n={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return ue(i,n)?B(i,n):B(i,n)&&t.size===e.size}function dc(t,e){return fc(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function tt(t){let e,i;try{let n=await ui(t,Gd,{bigint:!0,label:"Native lock"});e=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof $e?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Gd} bytes: ${t}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:n}):new Error(`Native lock changed while reading: ${t}`,{cause:n}):n}return{file:t,owner:sb(JSON.parse(e.toString("utf8")),t),identity:Qd(i)}}async function cb(t){return(await tt(t))?.owner??null}function Zd(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==Yd.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=pb(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function lb(t,e){try{await Ce.lstat(e);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Ce.rename(t,e)}catch(i){if(i.code!=="ENOENT")throw i}}async function hc(t,e){let i=await tt(t.file);if(!i)return"missing";if(i.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!dc(i.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await Ce.mkdir(e,{recursive:!0});let n=fe.join(e,`${fe.basename(t.file)}.${t.owner.id}.${Ud()}.removed`);try{await Ce.rename(t.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await tt(n);if(!r||r.owner.id!==t.owner.id||!fc(r.identity,t.identity))throw await lb(n,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await Ce.rm(n,{force:!0}),"removed"}function eh(t){return{id:Ud(),pid:process.pid,hostname:Yd.hostname(),createdAt:new Date().toISOString(),operation:t}}async function th(t,e){let i;try{i=await Ce.open(t,"wx")}catch(n){if(n.code==="EEXIST"){let r=await cb(t);throw new Error(`Native lock is already held: ${t}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(e,null,2)+`
|
|
144
|
+
`,"utf8"),await i.sync(),Qd(await i.stat({bigint:!0}))}finally{await i.close()}}async function ub(t,e){let i=await q(t.nativeRoot,t.locksDir);await Ce.mkdir(i,{recursive:!0});let n=await q(t.nativeRoot,fe.join(i,Xd));await Ce.mkdir(n,{recursive:!0});let r=eh(e),a=fe.join(n,`.${r.id}.tmp`),o=fe.join(n,`${r.id}.claim`);try{let s=await th(a,r);await Ce.rename(a,o);let c=await tt(o);if(!c||!fc(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.nativeRoot,locksDir:i,owner:r,identity:c.identity}}finally{await Ce.rm(a,{force:!0})}}async function fb(t){let e=fe.dirname(t.file),i=!1,n=fe.basename(t.file);for(let r of await Ce.readdir(e,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=fe.join(e,r.name);if(fe.resolve(a)!==fe.resolve(t.file))try{let o=await tt(a),s=Zd(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await hc(o,e);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function ih(t){let e=await tt(t.file);if(e){if(e.owner.id!==t.owner.id||!dc(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await hc(e,fe.dirname(t.file))}}async function db(t,e){let i=Date.now()+ab;for(;;){let n=await ub(t,e);if(!await fb(n))return n;if(await ih(n),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(r=>setTimeout(r,2+Math.floor(Math.random()*7)))}}async function hb(t){let e=ua.get(t)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=e.then(()=>n);return ua.set(t,r),await e,()=>{i(),ua.get(t)===r&&ua.delete(t)}}async function nh(t,e,i){let n=fe.resolve(t.locksDir),r=Kd.getStore();if(r?.has(n))return i();let a=await hb(n);try{let o=await db(t,e),s=new Map(r??[]);return s.set(n,o),await Kd.run(s,async()=>{try{return await i()}finally{await ih(o)}})}finally{a()}}async function gn(t,e,i){return nh(t,`acquire ${e}`,async()=>{let n=await q(t.nativeRoot,t.locksDir);await Ce.mkdir(n,{recursive:!0});let r=await q(t.nativeRoot,fe.join(n,ob(e))),a=eh(i),o=await th(r,a);return{file:r,nativeRoot:t.nativeRoot,locksDir:n,owner:a,identity:o}})}async function wn(t){await tt(t.file)&&await nh(t,`release ${fe.basename(t.file)}`,async()=>{let e=await tt(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!dc(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let i=fe.join(t.locksDir,Xd);await hc(e,i)})}function pb(t){try{return process.kill(t,0),!0}catch(e){let i=e.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function rh(t){return Zd(await tt(t))}import nt from"path";import{TextDecoder as Sb}from"util";import{createHash as mb}from"node:crypto";import{constants as fa,promises as He}from"node:fs";import Me from"node:path";import{TextDecoder as vb}from"node:util";function ha(t,e){let i=Me.relative(t,e);return i===""||!Me.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Me.sep}`)}function gb(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function wb(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function yb(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function da(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function pc(t,e){let i=await He.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await He.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Nb(t,e,i){let n=Me.resolve(t),r=Me.resolve(e);if(!ha(n,r))throw new Error(`${i} is outside its managed root`);let a=[await pc(n,i)],o=n;for(let s of Me.relative(n,r).split(Me.sep).filter(Boolean)){await Jt(a,i),o=Me.join(o,s);let c=await pc(o,i);if(!ha(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Jt(a,i),a}async function Jt(t,e){for(let i of t){let n=await He.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!wb(i,n)||await He.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function bb(t,e,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-r,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>e)throw new Error(`${i} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function it(t){let e=gb(t.maxBytes),i=Me.resolve(t.file),n=await Nb(t.root,Me.dirname(i),t.label),r=await Promise.all((t.forbiddenRoots??[]).map(u=>pc(Me.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Jt(n,t.label);let a=await He.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=yb(a),s=await He.realpath(i);if(!ha(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(r.some(u=>ha(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?fa.O_RDONLY:fa.O_RDONLY|fa.O_NOFOLLOW|fa.O_NONBLOCK,l=await He.open(i,c);try{let u=await l.stat();await t.hooks?.afterOpen?.();let[f,d]=await Promise.all([He.lstat(i),He.realpath(i)]);if(await Jt(n,t.label),await Jt(r,t.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!da(o,u)||!da(o,f))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let p=await bb(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),He.lstat(i),He.realpath(i)]);if(await Jt(n,t.label),await Jt(r,t.label),!h.isFile()||h.isSymbolicLink()||v!==s||!da(o,m)||!da(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:p,hash:mb("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function ah(t){let e=await it(t),i;try{i=new vb("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t.label} is not valid UTF-8`,{cause:n})}return{...e,text:i}}var Eb=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Rb=new Set(["id","type","source","target","staged","backup"]),Cb=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Pb=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var ch=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Ab=256*1024,cx=1024*1024,lx=16*1024;var ux=64*1024*1024;var xb=new Sb("utf-8",{fatal:!0});function ma(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function va(t,e,i){let n=Object.keys(t).filter(r=>!e.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function lh(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function mc(t,e){if(typeof t!="string"||t.length===0||nt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function pa(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function oh(t,e){if(mc(t,e),t.includes("\\")||t!==nt.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function Tb(t,e){let i=ma(t,`transaction operations[${e}]`);if(va(i,Rb,`transaction operations[${e}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${e}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);mc(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&mc(i[n],`transaction operation ${i.id} ${n}`);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 uh(t){let e=ma(t,"Native Archive transaction journal");if(va(e,Cb,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!ch.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!lh(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(pa(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=e.operations.map((s,c)=>{let l=ma(s,`Archive transaction operations[${c}]`);if(va(l,Pb,`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`);oh(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&oh(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&pa(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(pa(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`);pa(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=i.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let r=`runtime/transactions/${e.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.change}$`,"u").test(a[0].target)||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(`${r}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${r}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:i}}function Ib(t){let e=ma(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return uh(e);if(va(e,Eb,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!ch.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!nt.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!nt.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!lh(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let i=e.operations.map(Tb),n=i.map(r=>r.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:i}}function _b(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return nt.join(t.transactionsDir,e)}function fh(t,e){let i=_b(t,e);return{directory:i,journal:nt.join(i,"transaction.json"),events:nt.join(i,"events.jsonl"),staged:nt.join(i,"staged"),backups:nt.join(i,"backups")}}async function gc(t,e){let i=fh(t,e);return await Promise.all(Object.values(i).map(n=>q(t.nativeRoot,n))),i}async function wc(t,e,i={}){let n=await gc(t,e),r=await it({root:t.nativeRoot,file:n.journal,maxBytes:Ab,label:`Native transaction journal ${e}`,hooks:i.hooks}),a=JSON.parse(xb.decode(r.bytes)),o=Ib(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function $b(t,e){let i;try{i=await jb.readdir(t.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let r=await wc(t,n.name);if(r.id!==e&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function Hb(t,e){let i=Date.now()+5e3,n=Ob.join(t.locksDir,"root-move.lock");for(;;)try{return await gn(t,"root-move",e)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await rh(n);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw r;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function rt(t,e,i,n){let r=await Hb(t,e);try{if(await vn(t.projectRoot),await $b(t,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await wn(r)}}function dh(t){return Number.isSafeInteger(t)&&t>=1}async function hh(t){if(!dh(t.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(t.next.revision!==t.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let e=await t.read();if(!dh(e.revision))throw new Error("Native current revision must be a positive integer");let i=t.equals??((n,r)=>JSON.stringify(n)===JSON.stringify(r));if(e.revision===t.next.revision&&i(e,t.next))return e;if(e.revision!==t.expectedRevision)throw t.conflict(e.revision);return await t.write(t.next),t.next}import{createHash as Na}from"crypto";import{spawn as Sh}from"node:child_process";import{promises as U}from"fs";import $ from"path";import{createHash as Mb}from"crypto";function G(t){return Mb("sha256").update(t).digest("hex")}var ga={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Eh=1e3,Lb=8*1024*1024,Fb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Bb=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),Db=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),qb=new Set(["schema","include","exclude","hash"]),Vb=new Set(["provider","gitSelection","physicalSelection","projection"]),Wb=new Set(["provider","selection"]),zb=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Jb=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),Gb=new Set(["schema","status","before","after"]),Kb=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Ub=new Set(["path","hash","size","type","gitObjectId"]),Yb=new Set(["path","size","type","reason"]),Xb=new Set(["ref","hash","count"]),Qb=new Set(["change-created","legacy-migration","explicit"]),Zb=new Set(["file","directory","other"]),ek=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),ba=/^[a-f0-9]{64}$/u,Rh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,tk=new Set(["EACCES","EPERM"]),vi=64*1024,Sc=64*1024,ik=6e4,nk=1e3,rk=2,Ch={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},ak={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function ok(t){let e=t.deadlineMs??ik;if(!Number.isSafeInteger(e)||e<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+e,gitProcess:t.gitProcess??{command:"git"}}}function Le(t){return Math.max(0,t.deadlineAt-Date.now())}function I(t){return Le(t)>=1}function yc(t){let e=t===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:t});return Object.assign(e,{code:"GIT_SNAPSHOT_TIMEOUT"})}function pi(t){return t.code==="GIT_SNAPSHOT_TIMEOUT"}function sk(t){let e={...ak,...t};if(!Number.isSafeInteger(e.maxNodes)||e.maxNodes<1||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<1||!Number.isSafeInteger(e.maxPathBytes)||e.maxPathBytes<1||e.maxPathBytes>e.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return e}async function ck(t,e){if(e.terminateTree){await e.terminateTree(t);return}let i=t.pid;if(i===void 0){t.kill("SIGKILL");return}if(process.platform==="win32"){let n=process.env.SystemRoot??process.env.WINDIR,r=n&&$.win32.isAbsolute(n)?$.win32.resolve(n):"C:\\Windows",a=$.win32.join(r,"System32","taskkill.exe");if(!$.win32.isAbsolute(a))throw t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,f=(d,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(d))};try{l=Sh(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>f(!1)),l.once("close",d=>f(d===0)),u=setTimeout(()=>f(!1,!0),nk),u.unref()}catch{f(!1)}});for(let s=0;s<rk;s+=1)if(await o()){t.kill("SIGKILL");return}throw t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(n){if(n.code!=="ESRCH")throw n}t.kill("SIGKILL")}function Cc(t,e,i,n){let r=Le(t);if(r<1)throw yc();let a=t.gitProcess,o=Sh(a.command,[...a.argsPrefix??[],"-C",e,...i],{stdio:[n?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),f=setTimeout(()=>{c=!0,l=ck(o,a).then(()=>({error:null}),p=>({error:p}))},r);f.unref();let d=u.then(async p=>{if(clearTimeout(f),c){let m=await l;throw m?.error?yc(m.error):yc()}return{code:p,spawnError:s}});return{child:o,completion:d}}function lk(t){let e={...Ch,...t};if(!Number.isSafeInteger(e.maxRecords)||e.maxRecords<1||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<1||!Number.isSafeInteger(e.maxRecordBytes)||e.maxRecordBytes<1||e.maxRecordBytes>e.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return e}async function ya(t,e,i,n=Sc){let{child:r,completion:a}=Cc(t,e,i,!1),o=[],s=[],c=0,l=0,u=!1;r.stdout.on("data",p=>{let m=Math.max(0,n-l);m>0&&o.push(Buffer.from(p).subarray(0,m)),l+=p.byteLength,l>n&&(u=!0)}),r.stderr.on("data",p=>{if(c>=vi)return;let m=vi-c,h=Buffer.from(p).subarray(0,m);s.push(h),c+=h.byteLength});let{code:f,spawnError:d}=await a;if(f===0&&d===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${d?`: ${d.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Nc(t){return{hash:t.digest,recordCount:t.recordCount,storedRecordCount:t.records.length,stdoutBytes:t.stdoutBytes,overflow:t.overflow}}function wa(t,e,i,n){if(n.outputChunkBytes!==void 0&&(!Number.isSafeInteger(n.outputChunkBytes)||n.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((r,a)=>{let{child:o,completion:s}=Cc(t,e,i,n.stdin!==void 0),c=[],l=Na("sha256"),u=[],f=0,d=0,p=0,m=0,h=Buffer.alloc(0),v=!1,S=!1,N=!1,E=b=>{let k=0;for(;k<b.byteLength;){let g=b.indexOf(0,k),y=g<0?b.byteLength:g,w=b.subarray(k,y);if(!v&&w.byteLength>0&&(h.byteLength+w.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,S=!0):h=Buffer.concat([h,w])),g<0)break;m+=1,h.byteLength===0&&!v&&(N=!0);let R=h.byteLength+1;!v&&m<=n.maxRecords&&p+R<=n.maxBytes?(c.push(h),p+=R):S=!0,h=Buffer.alloc(0),v=!1,k=g+1}};o.stdout.on("data",b=>{l.update(b),d+=b.byteLength,d>n.maxBytes&&(S=!0);let k=n.outputChunkBytes;if(k===void 0){E(b);return}for(let g=0;g<b.byteLength;g+=k)E(b.subarray(g,Math.min(b.byteLength,g+k)))}),o.stderr.on("data",b=>{if(f>=vi)return;let k=vi-f,g=Buffer.from(b).subarray(0,k);u.push(g),f+=g.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:b,spawnError:k})=>{let g=n.acceptedExitCodes??[0];if(b!==null&&g.includes(b)&&k===null&&!N&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:S,recordCount:m,stdoutBytes:d});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:N||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function Ec(t){let e=t.toString("utf8");if(!Buffer.from(e,"utf8").equals(t))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return e}async function uk(t,e,i){let{child:n,completion:r}=Cc(t,e,i,!1),a=[],o=0,s=!1;n.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),n.stderr.on("data",u=>{if(o>=vi)return;let f=vi-o,d=Buffer.from(u).subarray(0,f);a.push(d),o+=d.byteLength});let{code:c,spawnError:l}=await r;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function mi(t){let e=t.endsWith("/")?t.slice(0,-1):t;return e.length===0||e.includes("\\")||$.posix.isAbsolute(e)||/^[A-Za-z]:/u.test(e)||$.posix.normalize(e)!==e||e===".."||e.startsWith("../")||e.includes("\0")?null:e}function fk(t,e){return t.map(i=>{let n=mi(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${e} path`);return n})}async function dk(t){let e=$.resolve(t);for(;;){try{return await U.lstat($.join(e,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=$.dirname(e);if(i===e)return!1;e=i}}async function Ph(t,e,i,n={}){let r=$.resolve(e.projectRoot),a=$.join(r,".comet","current-change.json"),s=["--",".",...[e.nativeRoot,e.configFile,a].map(d=>{let p=$.relative(r,$.resolve(d)).replaceAll("\\","/"),m=mi(p);if(m===null)throw new Error("Native Git snapshot exclusion escaped the project root");return m}).flatMap(d=>[`:(exclude)${d}`,`:(exclude)${d}/**`])],c={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},l=await wa(t,r,["ls-files","--stage","-z",...s],c);await n.afterStageBefore?.();let u=await wa(t,r,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await n.afterCombined?.();let f=await wa(t,r,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:f}}function Ah(t){return{stageBefore:Nc(t.stagedBefore),combined:Nc(t.combined),stageAfter:Nc(t.stagedAfter)}}async function hk(t,e,i=Ch,n={}){let r=$.resolve(e.projectRoot);if(!await dk(r))return null;let a;try{a=await ya(t,r,["rev-parse","--is-inside-work-tree"])}catch(N){throw pi(N)?N:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:N})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await Ph(t,e,i,n)}catch(N){throw pi(N)?N:new Error("Native Git snapshot provider failed after repository detection",{cause:N})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,f=new Map,d=new Set,p=N=>{for(let E of N){let b=Ec(E),k=b.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let g=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(b.slice(0,k))?.groups;if(!g)throw new Error("Native Git snapshot provider returned a malformed staged header");let y=mi(b.slice(k+1));if(y===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(y),g.stage==="0"&&f.set(y,g.objectId),g.mode==="160000"&&g.stage==="0"&&d.add(y)}};p(s.records),p(l.records);let m=c.records.map(Ec),h=fk(m,"combined"),v=new Set(h.filter(N=>!u.has(N))),S=new Set(h.filter((N,E)=>!u.has(N)&&m[E].endsWith("/")));for(let N of d)S.delete(N);return{tracked:u,trackedObjectIds:f,untracked:v,gitlinks:d,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:Ah(o)}}function Ct(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}function ph(t){return t.stageBefore.overflow||t.combined.overflow||t.stageAfter.overflow}function pk(t,e){return!Ct(t.stageBefore,t.stageAfter)||!Ct(t.stageAfter,e.stageBefore)||!Ct(t.combined,e.combined)||!Ct(e.stageBefore,e.stageAfter)}async function mk(t,e,i,n,r){let a;try{a=await Ph(t,e,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw pi(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=Ah(a),c=ph(o)||ph(s),l=pk(o,s);c&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),n.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(n.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:G(`comet.native.git-selection-overflow.v2
|
|
145
|
+
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var vk=(1n<<256n)-1n;function gk(t){return t.isFile()?"file":t.isDirectory()?"directory":t.isSymbolicLink()?"symlink":"other"}async function mh(t){let e=$.resolve(t.paths.projectRoot),i=$.resolve(t.paths.nativeRoot),n=$.resolve(t.paths.configFile),r=$.join(e,".comet","current-change.json"),a=[],o=[],s=Buffer.alloc(32),c=0n,l=0,u=0,f=0,d=!1,p=!1,m=!1,h=()=>Le(t.execution)>=1?!0:(d=!0,m=!0,!1),v=E=>{let b=Buffer.from(`${E.type}\0${E.path}`,"utf8"),k=Na("sha256").update("comet.native.physical-selection-record.v1\0").update(b).digest();for(let g=0;g<s.length;g+=1)s[g]^=k[g];if(c=c+BigInt(`0x${k.toString("hex")}`)&vk,u+=1,f+=b.byteLength,Buffer.byteLength(E.path,"utf8")>t.limits.maxPathBytes||f>t.limits.maxBytes){d=!0,m=!0;return}a.push(E)},S=async E=>{if(m||!h())return;let b;try{b=await U.opendir(E)}catch(R){if(!h())return;if(!ie(R)&&!te(R)||E===e&&ie(R))throw R;p||=te(R),d||=ie(R),m=!0;return}if(!h()){try{await b.close()}catch(R){if(R.code!=="ERR_DIR_CLOSED")throw R}return}let k=!1,g;try{for(;!m&&h();){let R;try{R=await b.read()}catch(z){if(!h())break;if(!ie(z)&&!te(z)||E===e&&ie(z))throw z;p||=te(z),d||=ie(z),m=!0;break}if(!h()||R===null)break;if(l+=1,l>t.limits.maxNodes){d=!0,m=!0;break}let _=$.join(E,R.name),D=bk(e,_);if(_===n||_===r||Pt(i,_)||t.denylist.some(z=>Pt(z,_))||Je(D)!==null)continue;if(!h())break;let H;try{H=await U.lstat(_)}catch(z){if(!h())break;if(!ie(z)&&!te(z))throw z;if(p=!0,v({path:D,type:"other"}),o.push({path:D,size:null,type:"file",reason:ie(z)?"unreadable":"changed-during-read"}),await t.hooks?.afterNode?.(D),m||!h())break;continue}if(!h())break;let F=gk(H);if(F==="directory"){if(Rk(t.policy,D))continue;if(!h())break;let z;try{z=await U.realpath(_)}catch(qe){if(!h())break;if(!ie(qe)&&!te(qe))throw qe;if(p=!0,v({path:D,type:F}),o.push({path:D,size:null,type:"directory",reason:ie(qe)?"unreadable":"changed-during-read"}),await t.hooks?.afterNode?.(D),m||!h())break;continue}if(!h())break;if(!se(t.physicalProjectRoot,z)||Pt(t.physicalNativeRoot,z))continue;if(v({path:D,type:F}),await t.hooks?.afterNode?.(D),!h()||(await S(_),m))break;continue}if(v({path:D,type:F}),await t.hooks?.afterNode?.(D),!h()||m)break}}catch(R){k=!0,g=R}let y;try{await b.close()}catch(R){y=R}let w=h();if(k)throw g;if(w&&y!==void 0&&y.code!=="ERR_DIR_CLOSED")throw y};await S(e),h(),d?(a.length=0,u=0,f=0):(a.sort((E,b)=>E.path.localeCompare(b.path,"en")),o.sort((E,b)=>E.path.localeCompare(b.path,"en")));let N=d?G(`comet.native.physical-selection-incomplete.v1
|
|
146
146
|
${JSON.stringify({maxNodes:t.limits.maxNodes,maxBytes:t.limits.maxBytes,maxPathBytes:t.limits.maxPathBytes})}`):G(`comet.native.physical-selection.v1
|
|
147
|
-
${JSON.stringify({visitedNodeCount:l,recordCount:u,encodedBytes:f,xor:s.toString("hex"),sum:c.toString(16).padStart(64,"0")})}`);return{records:a,omissions:o,evidence:{hash:
|
|
148
|
-
`)}function
|
|
149
|
-
${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function
|
|
147
|
+
${JSON.stringify({visitedNodeCount:l,recordCount:u,encodedBytes:f,xor:s.toString("hex"),sum:c.toString(16).padStart(64,"0")})}`);return{records:a,omissions:o,evidence:{hash:N,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:f,overflow:d,unstable:p}}}function xh(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function wk(t,e){let i=t.overflow||e.overflow,n=t.unstable||e.unstable||!xh(t,e),r=[];return i&&r.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),n&&r.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:r,evidence:i||n?{schema:"comet.native.physical-selection.v1",status:i&&n?"overflow-and-changed":i?"overflow":"changed",before:t,after:e}:null}}function yk(t){return[...new Set([...t.tracked,...t.untracked])].sort((e,i)=>e.localeCompare(i,"en"))}async function vh(t,e){let n=(await ya(t,e,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Rh.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return G(`gitlink:${n}`)}async function gh(t,e){let i=await vh(t,e),n=await uk(t,e,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await vh(t,e);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function Nk(t,e){if(Je(e)!==null)return!1;let i=$.resolve(t.projectRoot,...e.split("/"));return!Pt($.resolve(t.nativeRoot),i)}function bk(t,e){return $.relative(t,e).split($.sep).join("/")}function kk(t,e){return e.map(i=>$.resolve(t,...i.split(/[\\/]/u)))}function Pt(t,e){let i=$.resolve(t),n=$.resolve(e);return n===i||se(i,n)}function ie(t){return tk.has(t.code??"")}function te(t){return t.code==="ENOENT"}function Th(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
148
|
+
`)}function Sk(t,e){return G(`comet.native.snapshot-policy.v1
|
|
149
|
+
${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function bc(t,e,i){let n=new Set(e),r=[...e];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=t[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),r.push(a+1))}return n}function Ek(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function wh(t){let e=la(t,"Native snapshot pattern"),i=[];for(let n=0;n<e.length;n+=1){let r=e[n];r==="*"&&e[n+1]==="*"?(n+=1,e[n+1]==="/"?(n+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):r==="*"?i.push({kind:"star"}):r==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:r})}return(n,r)=>{let a=r?Ek(r):void 0;if(a&&!a())return!1;let o=bc(i,new Set([0]),a);if(o===null)return!1;for(let s of n){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=bc(i,c,a),o===null||o.size===0)return!1}return bc(i,o,a)?.has(i.length)??!1}}function Ih(t){if(t===void 0)return;let e=[...new Set(t.include.map(r=>la(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(t.exclude.map(r=>la(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let n=Sk(e,i);if("hash"in t&&t.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:i,hash:n},includeMatchers:e.map(wh),excludeMatchers:i.map(wh),excludedDirectoryPrefixes:i.flatMap(r=>{if(!r.endsWith("/**"))return[];let a=r.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((r,a)=>r.localeCompare(a,"en"))}}function Rk(t,e){return t?.excludedDirectoryPrefixes.includes(e)??!1}function yh(t,e,i){if(!t)return!0;let n=()=>I(i),r=!1;for(let a of t.includeMatchers){if(!n())return!1;if(a(e,n)){r=!0;break}}if(!r)return!1;for(let a of t.excludeMatchers)if(!n()||a(e,n))return!1;return!0}function kc(t,e,i){let n=JSON.stringify(i);return G(`${t}
|
|
150
150
|
${Buffer.byteLength(e)}:${e}
|
|
151
|
-
${Buffer.byteLength(n)}:${n}`)}function uc(t){return t.reason==="git-enumeration-limit"||t.reason==="git-selection-changed"||t.reason==="physical-enumeration-limit"||t.reason==="physical-selection-changed"}function sh(t){for(let e=t.length-1;e>=0;e-=1){let i=t[e];if(!uc(i))return t.splice(e,1),i}return null}function Et(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?F(i,n):F(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function eS(t,e,i,n){if(!_(n))return{status:"budget-exhausted"};let r;try{r=await U.open(t,"r")}catch(c){if(!_(n))return{status:"budget-exhausted"};throw c}if(!_(n))return await r.close(),{status:"budget-exhausted"};let a=fa("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,e+1)),s=0;try{if(!_(n))return{status:"budget-exhausted"};let c=await r.stat();if(!_(n))return{status:"budget-exhausted"};if(!c.isFile()||!Et(i,c))return{status:"changed"};for(;;){if(!_(n))return{status:"budget-exhausted"};let l=e+1-s;if(l<1)return{status:"changed"};let u=await r.read(o,0,Math.min(o.length,l),null);if(!_(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!_(n))return{status:"budget-exhausted"};let f=await r.stat();return _(n)?!f.isFile()||!Et(c,f)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:f}:{status:"budget-exhausted"}}if(s+u.bytesRead>e)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await r.close()}}function Ee(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Re(t,e,i){let n=Object.keys(t).find(r=>!e.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function fi(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Je(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function yh(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let i=V.posix.normalize(t);if(i!==t||V.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function tS(t,e){let i=Ee(t,`Native snapshot entry ${e}`);Re(i,kb,`Native snapshot entry ${e}`);let n=yh(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!da.test(i.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let r={path:n,hash:i.hash,size:Je(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!dh.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function iS(t,e){let i=Ee(t,`Native snapshot omission ${e}`);if(Re(i,Eb,`Native snapshot omission ${e}`),!Pb.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!Ab.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:yh(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:Je(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function nS(t){let e=Ee(t,"Native snapshot omission overflow");if(Re(e,Rb,"Native snapshot omission overflow"),typeof e.hash!="string"||!da.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:e.hash,count:fi(e.count,"Native snapshot omission overflow count")}}function ui(t,e){let i=Ee(t,e);if(Re(i,Nb,e),typeof i.hash!="string"||!da.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let n=Je(i.recordCount,`${e} recordCount`),r=Je(i.storedRecordCount,`${e} storedRecordCount`),a=Je(i.stdoutBytes,`${e} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function ch(t){let e=Ee(t,"Native Git selection evidence");if(Re(e,yb,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=ui(e.stageBefore,"Native Git selection stageBefore"),n=ui(e.combined,"Native Git selection combined"),r=ui(e.stageAfter,"Native Git selection stageAfter"),a=ui(e.finalStageBefore,"Native Git selection finalStageBefore"),o=ui(e.finalCombined,"Native Git selection finalCombined"),s=ui(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(f=>f.overflow),l=!Rt(i,r)||!Rt(r,a)||!Rt(n,o)||!Rt(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function lh(t,e){let i=Ee(t,e);if(Re(i,Sb,e),typeof i.hash!="string"||!da.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${e} flags are invalid`);let n=Je(i.visitedNodeCount,`${e} visitedNodeCount`),r=Je(i.recordCount,`${e} recordCount`),a=Je(i.storedRecordCount,`${e} storedRecordCount`),o=Je(i.encodedBytes,`${e} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function rS(t){let e=Ee(t,"Native physical selection evidence");if(Re(e,bb,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=lh(e.before,"Native physical selection before"),n=lh(e.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!vh(i,n);if(!r&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=r&&a?"overflow-and-changed":r?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:n}}function hn(t){let e=Ee(t,"Native content snapshot manifest");if(Re(e,pb,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Cb.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let g=Ee(e.capture,"Native content snapshot capture");if(Re(g,gb,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let b=g.gitSelection===void 0?void 0:ch(g.gitSelection),y=g.physicalSelection===void 0?void 0:rS(g.physicalSelection),R=null;if(g.projection!==void 0){let O=Ee(g.projection,"Native content snapshot projection");if(Re(O,wb,"Native content snapshot projection"),O.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");R={provider:"git",...O.selection===void 0?{}:{selection:ch(O.selection)}}}if(g.provider==="git"){if(y||R)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...b?{gitSelection:b}:{}}}else{if(b)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(y&&R)throw new Error("Native physical-tree capture cannot combine selection and projection");i=R?{provider:"physical-tree",projection:R}:{provider:"physical-tree",...y?{physicalSelection:y}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=Ee(e.limits,"Native content snapshot limits");Re(n,mb,"Native content snapshot limits");let r={maxFiles:fi(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:fi(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:fi(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:fi(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:fi(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let g=Ee(e.policy,"Native snapshot policy");if(Re(g,vb,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=wh({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(tS),s=e.omitted.map(iS),c=Je(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:nS(e.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>r.maxFileBytes)||o.reduce((g,b)=>g+b.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>fh||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let f=s.filter(g=>g.reason==="git-enumeration-limit"),d=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...f,...d])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(f.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(f.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(g=>g.reason==="physical-enumeration-limit"),w=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...v,...w])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||w.length>1)throw new Error("Native physical selection omissions must not be duplicated");let E=i?.physicalSelection,k=E?.status==="overflow"||E?.status==="overflow-and-changed",N=E?.status==="changed"||E?.status==="overflow-and-changed";if(k!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(w.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let S={schema:"comet.native.content-snapshot.v1",origin:e.origin,...i?{capture:i}:{},createdAt:e.createdAt,complete:e.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(gh(S)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return S}function aS(t,e){if(!hb.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=V.join(t.changesDir,e);if(!ae(t.changesDir,i))throw new Error("Native change path escaped");return V.join(i,"runtime","baseline-manifest.json")}async function Nh(t,e={}){let i={maxFiles:e.limits?.maxFiles??ca.maxFiles,maxFileBytes:e.limits?.maxFileBytes??ca.maxFileBytes,maxTotalBytes:e.limits?.maxTotalBytes??ca.maxTotalBytes,maxManifestBytes:e.limits?.maxManifestBytes??ca.maxManifestBytes,...e.limits?.maxDurationMs===void 0?{}:{maxDurationMs:e.limits.maxDurationMs}},n=wh(e.policy),r=jb({...e,deadlineMs:e.deadlineMs??i.maxDurationMs}),a=Mb(e.gitSelectionLimits),o=$b(e.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=V.resolve(t.projectRoot),c=await U.realpath(s),l=V.resolve(t.nativeRoot),u=await U.realpath(l),f=V.resolve(t.configFile),d=V.join(s,".comet","current-change.json"),p=Yb(s,e.denylist??[]),m=[],h=[],v=new Map,w=new Map,E=0,k=0,N=G("comet.native.snapshot-omission-overflow.v1"),S=0,g=!1,b=null,y=P=>{k+=1,N=cc(N,"omission",P)},R=P=>{if(E+=1,h.length<fh){h.push(P);return}if(uc(P)){let A=sh(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(A),h.push(P);return}y(P)},O=P=>{E+=P.count,k+=P.count,N=cc(N,"git-selection",{source:"git-selection",...P})},B=P=>{k+=1,N=cc(N,"manifest-entry",{reason:"manifest-size",entry:P})},H=async(P,A)=>{m.push(P),S+=P.size,v.set(P.path,A),g||(g=!0,await e.gitSelectionHooks?.afterFirstEntryCaptured?.(P.path))},D=(P,A)=>{let T=m.findIndex(X=>X.path===P);if(T<0)return;let[$]=m.splice(T,1);S-=$.size,v.delete(P),R(A)},J=async(P,A,T,$)=>{if(!T.isFile()||T.isSymbolicLink()||!_(r))return;let X;try{X=await U.realpath(P)}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;R({path:A,size:T.size,type:"file",reason:Z(I)?"changed-during-read":"unreadable"});return}if(!_(r)||!ae(c,X)||Ct(u,X))return;if(m.length>=i.maxFiles){R({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){R({path:A,size:T.size,type:"file",reason:"file-size"});return}if(S+T.size>i.maxTotalBytes){R({path:A,size:T.size,type:"file",reason:"total-size"});return}let L,j,x;try{if(L=await eS(X,T.size,T,r),L.status==="budget-exhausted"||!_(r))return;if(L.status==="changed"){R({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!_(r)||(x=await U.realpath(P),!_(r)))return;j=await U.lstat(P)}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;R({path:A,size:T.size,type:"file",reason:Z(I)?"changed-during-read":"unreadable"});return}if(_(r)){if(L.bytes!==T.size||x!==X||!Et(T,L.finalStat)||!Et(L.finalStat,j)||!j.isFile()||j.isSymbolicLink()||j.size!==T.size||j.mtimeMs!==T.mtimeMs||j.ctimeMs!==T.ctimeMs){R({path:A,size:j.isFile()?j.size:null,type:j.isFile()?"file":"other",reason:"changed-during-read"});return}_(r)&&await H({path:A,hash:L.hash,size:j.size,type:"file",...$===void 0?{}:{gitObjectId:$}},{kind:"file",target:P,realTarget:X,stat:j})}},Be=async(P,A,T)=>{if(!_(r))return;let $,X,L;try{if($=await U.readlink(P,{encoding:"buffer"}),!_(r)||(L=await U.lstat(P),!_(r)))return;X=await U.readlink(P,{encoding:"buffer"})}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;R({path:A,size:null,type:"other",reason:Z(I)?"changed-during-read":"unreadable"});return}if(!_(r))return;if(!L.isSymbolicLink()||!Et(T,L)||L.mtimeMs!==T.mtimeMs||L.ctimeMs!==T.ctimeMs||!$.equals(X)){R({path:A,size:null,type:"other",reason:"changed-during-read"});return}let j=$.byteLength;if(m.length>=i.maxFiles){R({path:A,size:j,type:"other",reason:"file-count"});return}if(j>i.maxFileBytes){R({path:A,size:j,type:"other",reason:"file-size"});return}if(S+j>i.maxTotalBytes){R({path:A,size:j,type:"other",reason:"total-size"});return}let x=fa("sha256").update("symlink\0").update($).digest("hex");_(r)&&await H({path:A,hash:x,size:j,type:"file"},{kind:"symlink",target:P,rawTarget:$,stat:L})},qe=async()=>{for(let[P,A]of[...v]){if(!_(r))return;if(A.kind==="file"){let j,x;try{if(j=await U.realpath(A.target),!_(r))return;x=await U.lstat(A.target)}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;D(P,{path:P,size:null,type:"file",reason:ee(I)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(j!==A.realTarget||!x.isFile()||x.isSymbolicLink()||!Et(A.stat,x)||x.size!==A.stat.size||x.mtimeMs!==A.stat.mtimeMs||x.ctimeMs!==A.stat.ctimeMs)&&D(P,{path:P,size:x.isFile()?x.size:null,type:x.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let j,x;try{if(j=await U.lstat(A.target),!_(r))return;x=await U.readlink(A.target,{encoding:"buffer"})}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;D(P,{path:P,size:null,type:"other",reason:ee(I)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(!j.isSymbolicLink()||!Et(A.stat,j)||j.mtimeMs!==A.stat.mtimeMs||j.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(x))&&D(P,{path:P,size:null,type:"other",reason:"changed-during-read"});continue}let T,$;try{if(T=await U.realpath(A.target),!_(r))return;$=await U.lstat(A.target)}catch{if(!_(r))return;D(P,{path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;if(!(T===A.realTarget&&$.isDirectory()&&!$.isSymbolicLink()&&Et(A.stat,$)&&ae(c,T)&&!Ct(u,T))){D(P,{path:P,size:null,type:"directory",reason:"gitlink-changed"});continue}let L;try{if(!_(r))return;L=await rh(r,T)}catch(j){if(dn(j))throw j;D(P,{path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;L.dirty?D(P,{path:P,size:null,type:"directory",reason:"gitlink-dirty"}):L.hash!==A.hash&&D(P,{path:P,size:null,type:"directory",reason:"gitlink-changed"})}for(let[P,A]of w){if(!_(r))return;try{let T=await U.lstat(A);if(!_(r))return;R({path:P,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!_(r))return;if(Z(T))continue;if(!ee(T))throw T;R({path:P,size:null,type:"file",reason:"unreadable"})}}},me=await Bb(r,s,a,e.gitSelectionHooks);if(me===null){let P=await ih({execution:r,paths:t,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:e.physicalSelectionHooks});await e.physicalSelectionHooks?.afterInitialSelection?.();for(let $ of P.records){if($.type!=="file"&&$.type!=="symlink"||v.has($.path))continue;if(Me(r)<1)break;if(!oh(n,$.path,r))continue;if(Me(r)<1)break;let X=V.resolve(s,...$.path.split("/")),L;try{L=await U.lstat(X)}catch(j){if(!_(r))break;if(!ee(j)&&!Z(j))throw j;R({path:$.path,size:null,type:"file",reason:Z(j)?"changed-during-read":"unreadable"});continue}if(Me(r)<1)break;if($.type==="symlink"&&L.isSymbolicLink()){if(await Be(X,$.path,L),Me(r)<1)break;continue}if($.type!=="file"||!L.isFile()||L.isSymbolicLink()){R({path:$.path,size:L.isFile()?L.size:null,type:L.isDirectory()?"directory":L.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await J(X,$.path,L),Me(r)<1)break}Me(r)>=1&&await qe();let A=await ih({execution:r,paths:t,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),T=Jb(P.evidence,A.evidence);b=T.evidence;for(let $ of[...P.omissions,...A.omissions,...T.omissions])h.some(X=>X.path===$.path&&X.reason===$.reason)||R($)}else{await e.gitSelectionHooks?.afterInitialSelection?.();let P=e.incrementalBaseline,A=new Map,T=!1;if(P){let x=hn(P);for(let I of x.entries)I.gitObjectId!==void 0&&A.set(I.path,I);T=A.size>0}let $=new Set,X=!0;try{let x=await la(r,s,["ls-files","--modified","-z"],lc);for(let I of x.toString("utf8").split("\0")){let ie=ua(I);ie!==null&&$.add(ie)}}catch{T=!1,X=!1,A.clear()}let L=new Set,j=new Set;for(let x of Kb(me)){if(v.has(x)||!Gb(t,x))continue;if(Me(r)<1)break;if(!oh(n,x,r))continue;if(Me(r)<1)break;let I=V.resolve(s,...x.split("/"));if(I===f||I===d||p.some(ge=>Ct(ge,I)))continue;if(me.gitlinks.has(x)){if(m.length>=i.maxFiles){R({path:x,size:0,type:"file",reason:"file-count"});continue}let ge,Dn;try{[ge,Dn]=await Promise.all([U.realpath(I),U.lstat(I)])}catch{R({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Dn.isSymbolicLink()||!Dn.isDirectory()||!ae(c,ge)||Ct(u,ge)){R({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Ut=await rh(r,ge);if(Ut.dirty){R({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await H({path:x,hash:Ut.hash,size:0,type:"file"},{kind:"gitlink",target:I,realTarget:ge,stat:Dn,hash:Ut.hash})}catch(Ut){if(dn(Ut))throw Ut;R({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ie;try{ie=await U.lstat(I)}catch(ge){if(Z(ge)&&me.tracked.has(x)){w.set(x,I);continue}if(!ee(ge)&&!Z(ge))throw ge;R({path:x,size:null,type:"file",reason:Z(ge)?"changed-during-read":"unreadable"});continue}if(ie.isSymbolicLink()){await Be(I,x,ie);continue}if(!ie.isFile()){me.nestedRepositories.has(x)||R({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let Pe=me.trackedObjectIds.get(x),ve=Pe?A.get(x):void 0;if(T&&ve?.gitObjectId!==void 0&&ve.gitObjectId===Pe&&!$.has(x)){if(m.length>=i.maxFiles){R({path:x,size:ve.size,type:"file",reason:"file-count"});continue}if(ve.size>i.maxFileBytes){R({path:x,size:ve.size,type:"file",reason:"file-size"});continue}if(S+ve.size>i.maxTotalBytes){R({path:x,size:ve.size,type:"file",reason:"total-size"});continue}m.push({...ve}),S+=ve.size,L.add(x);continue}let Rl=X&&!$.has(x)?Pe:void 0;await J(I,x,ie,Rl),Rl!==void 0&&j.add(x)}if(await qe(),await e.gitSelectionHooks?.afterContentRevalidation?.(),await Vb(r,s,a,me,e.gitSelectionHooks?.outputChunkBytes),L.size>0||T&&j.size>0){let x=await la(r,s,["ls-files","--modified","-z"],lc),I=new Set;for(let ie of x.toString("utf8").split("\0")){let Pe=ua(ie);Pe!==null&&I.add(Pe)}for(let ie of L){if(!I.has(ie))continue;let Pe=m.find(ve=>ve.path===ie);D(ie,{path:ie,size:Pe?.size??null,type:"file",reason:"changed-during-read"})}for(let ie of j){if(!I.has(ie))continue;let Pe=m.find(ve=>ve.path===ie);Pe&&delete Pe.gitObjectId}}for(let x of me.omissions)R(x);me.overflow&&O(me.overflow)}m.sort((P,A)=>P.path.localeCompare(A.path,"en")),h.sort((P,A)=>P.path.localeCompare(A.path,"en"));let hm=me===null?{provider:"physical-tree",...b?{physicalSelection:b}:{}}:{provider:"git",...me.evidence?{gitSelection:me.evidence}:{}},El=()=>({schema:"comet.native.content-snapshot.v1",origin:e.origin??"explicit",capture:hm,createdAt:(e.now??new Date).toISOString(),complete:E===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:E,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:k}}:{}}),Ya=El();for(;gh(Ya)>i.maxManifestBytes;){if(h.filter(A=>!uc(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let $=sh(h);if($===null)break;y($)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))E+=1,B(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Ya=El()}return Ya}async function dc(t,e,i={}){let r=(await qt(t.projectRoot))?.native.snapshot??Us;return Nh(t,{...i,policy:e.policy,incrementalBaseline:e,limits:{maxFiles:r.max_files,maxFileBytes:r.max_total_bytes,maxTotalBytes:r.max_total_bytes,maxDurationMs:r.max_duration_ms},deadlineMs:r.max_duration_ms})}async function bh(t,e){let i=aS(t,e);await q(t.nativeRoot,i);try{let n=await Wd({root:t.nativeRoot,file:i,maxBytes:db,label:"Native baseline snapshot manifest"});return hn(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as SS}from"crypto";import wc from"path";var Ke=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{constants as pa,promises as le}from"node:fs";import ye from"node:path";import{TextDecoder as vS}from"node:util";import dS from"path";var Sh=(t,e)=>{let i=t[e];return i==null?null:String(i)};function mn(t,e){let i=t[e];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return i}function pn(t,e){let i=mn(t,e);if(dS.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return i}function hS(t){let e=t.run_retries??"{}",i;try{i=typeof e=="string"?JSON.parse(e):e}catch(n){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:n})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let n of Object.values(i))if(!Number.isInteger(n)||Number(n)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function kh(t){if(!t.run_id)return null;let e=mn(t,"run_id"),i=mn(t,"skill"),n=mn(t,"skill_version"),r=mn(t,"skill_hash"),a=pn(t,"pending_ref"),o=pn(t,"trajectory_ref"),s=pn(t,"context_ref"),c=pn(t,"artifacts_ref"),l=pn(t,"checkpoint_ref"),u=Number(t.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:i,skillVersion:n,skillHash:r,orchestration:t.orchestration,currentStep:Sh(t,"current_step"),iteration:u,pending:Sh(t,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:hS(t)}}var Fx=256*1024;var pS=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function mS(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)},i=kh(e);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function ha(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid Run state: stored value must be an object");let e=t,i=Object.keys(e).find(n=>!pS.has(n));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(e.currentStep!==null&&(typeof e.currentStep!="string"||e.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(e.pending!==null&&(typeof e.pending!="string"||e.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!e.retries||typeof e.retries!="object"||Array.isArray(e.retries))throw new Error("Invalid Run state: retries must be an object");return mS(e)}var we={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function gn(t,e){let i=ye.relative(t,e);return i===""||!ye.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ye.sep}`)}function Rh(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function vn(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}function gS(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function hi(t,e,i){let n=Ke[e];if(i!==void 0&&i!==n)throw new Error(`Native Run ${e} ref must be ${n}`);let r=ye.resolve(t),a=ye.resolve(r,...n.split("/"));if(!gn(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Eh(t){let e=await le.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${t}`);return{path:t,realPath:await le.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function hc(t,e){let i=ye.resolve(t),n=ye.resolve(e);if(!gn(i,n))throw new Error("Native Run path is outside its change");let r=[await Eh(i)],a=i;for(let o of ye.relative(i,n).split(ye.sep).filter(Boolean)){a=ye.join(a,o);let s;try{s=await Eh(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!gn(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function ma(t){for(let e of t){let i=await le.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!gS(e,i)||await le.realpath(e.path)!==e.realPath)throw new Error(`Native Run parent changed during I/O: ${e.path}`)}}async function wS(t,e,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-r,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>e)throw new Error(`${i} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function wn(t,e,i,n,r){let a=await hc(t,ye.dirname(e));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await le.lstat(e)}catch(f){if(f.code==="ENOENT")return null;throw f}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${n} must be a regular file`);if(o.size>i)throw new Error(`${n} exceeds ${i} bytes`);let s=Rh(o),c=await le.realpath(e);if(!gn(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?pa.O_RDONLY:pa.O_RDONLY|pa.O_NOFOLLOW|pa.O_NONBLOCK,u;try{u=await le.open(e,l)}catch(f){throw new Error(`${n} changed while opening`,{cause:f})}try{let[f,d,p]=await Promise.all([u.stat(),le.lstat(e),le.realpath(e)]);if(await ma(a),!f.isFile()||!d.isFile()||d.isSymbolicLink()||p!==c||!vn(s,f)||!vn(s,d))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await wS(u,i,n);await r?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([u.stat(),le.lstat(e),le.realpath(e)]);if(await ma(a),!v.isFile()||v.isSymbolicLink()||w!==c||!vn(s,h)||!vn(s,v))throw new Error(`${n} changed while reading`);let E;try{E=new vS("utf-8",{fatal:!0}).decode(m)}catch(k){throw new Error(`${n} is not valid UTF-8`,{cause:k})}return{text:E,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function yS(t,e,i){let n=await hc(t,ye.dirname(e));if(!n)return{exists:!1};let r;try{r=await le.lstat(e)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!r.isFile()||r.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await le.realpath(e);if(!gn(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await ma(n),{exists:!0,identity:Rh(r),realPath:a}}async function NS(t,e,i,n){let r=await hc(t,ye.dirname(e));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await le.lstat(e)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${n} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!vn(i.identity,a)||await le.realpath(e)!==i.realPath)throw new Error(`${n} changed before commit`);await ma(r)}async function pc(t){if(Buffer.byteLength(t.content,"utf8")>t.maxBytes)throw new Error(`${t.label} exceeds ${t.maxBytes} bytes`);let i=t.expected??await yS(t.changeDir,t.file,t.label);if(i.exists&&i.identity.size>t.maxBytes)throw new Error(`${t.label} exceeds ${t.maxBytes} bytes`);await Ze(t.file,t.content,{containedRoot:t.changeDir,beforeCommit:async()=>{await t.hooks?.beforeCommit?.(),await NS(t.changeDir,t.file,i,t.label)}});let n=await wn(t.changeDir,t.file,t.maxBytes,t.label);if(!n||n.text!==t.content)throw new Error(`${t.label} commit could not be verified`)}function bS(t,e){try{return JSON.parse(t)}catch(i){throw new Error(`${e} contains invalid JSON`,{cause:i})}}function Ch(t){return`${JSON.stringify(t,null,2)}
|
|
152
|
-
`}function
|
|
153
|
-
`;if(Buffer.byteLength(a,"utf8")>
|
|
154
|
-
`)])}catch(f){if(!
|
|
155
|
-
`);function En(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function jh(t,e,i){let n=Object.keys(t).filter(r=>!e.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function kc(t){if(!Oh.test(t))throw new Error(`Invalid Native change name: ${t}`)}function MS(t){if(!Oh.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function $h(t,e){if(t.length===0||nt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function LS(t,e){let i=En(t,`spec_changes[${e}]`);if(jh(i,_S,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(MS(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let n=i.source,r=i.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof n=="string"&&$h(n,`Spec source for ${i.capability}`),i.operation==="create"){if(!n)throw new Error(`Create spec ${i.capability} requires source`);if(r!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!n)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof r!="string"||!Sc.test(r))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof r!="string"||!Sc.test(r))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof n=="string"?{source:n}:{},base_hash:r}}function DS(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function Ec(t,e){if(jh(t,e,At),typeof t.name!="string")throw new Error("Native change name is required");if(kc(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!OS.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!jS.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(LS),n=i.map(r=>r.capability).filter((r,a,o)=>o.indexOf(r)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof t.verification_result!="string"||!$S.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&$h(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!DS(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Rn(t){let e=En(t,At);if(e.schema!==Wt)throw new Error(`Expected ${Wt}`);return{schema:Wt,...Ec(e,TS)}}function kn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Nc(t,e,i){if(t===null)return null;let n=typeof t=="string"?HS.exec(t):null;if(!n||n[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return t}function FS(t){if(t==null)return null;if(typeof t!="string"||!Sc.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function BS(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Cn(t){let e=En(t,At);if(e.schema!==zt)throw new Error(`Expected ${zt}`);if(kn(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${zt} minimum_runtime_version must be 2`);return{schema:zt,minimum_runtime_version:2,revision:kn(e.revision,"Native v2 revision"),...Ec(e,_h)}}function rt(t){let e=En(t,At);if(e.schema!==Pt){if(e.schema===Wt||e.schema===zt){let o=e.schema===Wt?Rn(e):Cn(e);throw new bn(o.name,o.schema)}throw new Jt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=kn(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Jt(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=kn(e.revision,"Native revision"),r=Ec(e,IS),a=FS(e.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Pt,minimum_runtime_version:3,revision:n,verification_protocol:BS(e.verification_protocol),...r,approved_contract_hash:a,implementation_scope:Nc(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Nc(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Nc(e.partial_allowance,"Native partial_allowance","allowances")}}function qS(t){let e=En(t,At);if(e.schema===Wt){let r=Rn(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Pt}`}}if(e.schema===zt){let r=Cn(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Pt}`}}if(e.schema!==Pt){let r=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new Jt(typeof e.schema=="string"?e.schema:"(missing)",r).message}}let i=kn(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Jt(e.schema,i).message};let n=rt(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function bc(t){let e=rt(t);return{schema:e.schema,minimum_runtime_version:e.minimum_runtime_version,revision:e.revision,verification_protocol:e.verification_protocol,name:e.name,language:e.language,phase:e.phase,brief:e.brief,approval:e.approval,approved_contract_hash:e.approved_contract_hash??null,spec_changes:e.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:e.verification_result,verification_report:e.verification_report,implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Y(t,e){kc(e);let i=nt.join(t.changesDir,e);if(!ae(t.changesDir,i))throw new Error("Native change path escaped");return i}async function Pn(t,e){let i=nt.join(Y(t,e),"runtime","schema-migration.json");await q(t.nativeRoot,i);try{return await Th.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Hh(t,e){let i=nt.join(Y(t,e),"runtime","checkpoint-journal.json");await q(t.nativeRoot,i);try{return await Th.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var VS=256*1024;async function Mh(t,e=nt.dirname(t)){let i=nt.relative(e,t).split(nt.sep).join("/"),n=await Ie({root:e,ref:i,maxBytes:VS}),r=(0,wa.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${r.errors[0].message}`);return r.toJS()}async function zS(t,e){let i=nt.join(Y(t,e),At);await q(t.nativeRoot,i);let n=qS(await Mh(i,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Pn(t,e)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(n.status==="current"&&n.state&&await WS(t,n.state),n)}async function WS(t,e){if(await bh(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function Ne(t,e){let i=await zS(t,e);if(i.status==="migration-required")throw new bn(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Jt(i.schema,i.minimumRuntimeVersion);return i.state}async function JS(t,e,i){let n={...e,schema:Pt,minimum_runtime_version:3,revision:i+1},r=await Zd({expectedRevision:i,next:n,read:async()=>{let a=rt(await Mh(t));if(a.name!==e.name)throw new Error(`Native change file/name mismatch: ${e.name}`);return a},write:a=>Ze(t,(0,wa.stringify)(bc(a))),equals:(a,o)=>JSON.stringify(bc(a))===JSON.stringify(bc(o)),conflict:a=>new Sn(e.name,i,a)});return Object.assign(e,r),r}async function ya(t,e,i,n){if(await ln(t.projectRoot),await Pn(t,e.name))throw new bn(e.name,e.schema);if(!n?.allowPendingCheckpointRecovery&&await Hh(t,e.name))throw new Error(`Native progress checkpoint recovery is required for ${e.name} before another state write`);if((await Ne(t,e.name)).verification_protocol!==e.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await va(t,e.name);let a=nt.join(Y(t,e.name),At);return await q(t.nativeRoot,a),JS(a,e,i)}import{promises as aE}from"fs";import An from"path";var KS=/\b(Bearer|Basic)\s+[^\s"']+/giu,GS=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,US=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,YS=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,XS=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,QS=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,ZS=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function Ce(t){return t.replace(KS,"$1 [REDACTED]").replace(GS,"[REDACTED PRIVATE KEY]").replace(US,"$1[REDACTED]@").replace(YS,"[REDACTED TOKEN]").replace(XS,'$1"[REDACTED]"').replace(QS,"$1$2$1$3$4[REDACTED]$4").replace(ZS,"$1$2[REDACTED]")}var Na={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},gi=/^[a-f0-9]{64}$/u;function ba(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Sa(t,e,i){let n=new Set(e),r=Object.keys(t).filter(o=>!n.has(o)),a=e.filter(o=>!(o in t));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function xt(t,e,i=2e3){if(typeof t!="string"||t.length===0||t.length>i)throw new Error(`${e} must be a non-empty string of at most ${i} characters`);return t}function Lh(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Rc(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function ek(t){let e=t.trim().replaceAll("\\","/");if(e.length===0||An.isAbsolute(e)||/^(?:[A-Za-z]:|~|\/)/u.test(e)||e.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${t}`);let i=An.posix.normalize(e);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${t}`);return i}function tk(t,e){return An.join(Y(t,e),"runtime","checkpoints","progress.json")}function Cc(t,e){return An.join(Y(t,e),"runtime","checkpoint-journal.json")}function Dh(t,e,i){if(!gi.test(i))throw new Error("Native checkpoint manifest hash is invalid");return An.join(Y(t,e),"runtime","checkpoints","manifests",`${i}.json`)}function ik(t){if(!gi.test(t))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${t}.json`}async function Fh(t,e,i){let n=await tt({root:t,file:e,maxBytes:Na.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function nk(t,e){let i=ba(t,`checkpoint manifest artifact ${e}`);Sa(i,["path","hash","size"],`checkpoint manifest artifact ${e}`);let n=ek(xt(i.path,`checkpoint artifact ${e} path`,4096)),r=We(n);if(r)throw new Error(`checkpoint artifact ${e} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!gi.test(i.hash))throw new Error(`checkpoint artifact ${e} hash is invalid`);return{path:n,hash:i.hash,size:Rc(i.size,`checkpoint artifact ${e} size`)}}function ka(t,e){let i=ba(t,"Native checkpoint manifest");if(Sa(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==e)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>Na.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(nk),r=[...n].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(n)!==JSON.stringify(r))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(n.map(o=>o.path)).size!==n.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Rc(i.totalBytes,"checkpoint manifest totalBytes");if(n.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Na.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:e,artifacts:n,totalBytes:a}}function Pc(t){return G(JSON.stringify(ka(t,t.change)))}function Bh(t,e){let i=ba(t,"Native progress checkpoint");if(Sa(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==e)throw new Error("Native checkpoint change mismatch");let n=i.phase;if(n!=="shape"&&n!=="build"&&n!=="verify"&&n!=="archive")throw new Error("Native checkpoint phase is invalid");let r=Lh(i.previousRevision,"Native checkpoint previousRevision"),a=Lh(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=xt(i.manifestHash,"Native checkpoint manifestHash",64);if(!gi.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=ik(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=xt(i.inputHash,"Native checkpoint inputHash",64);if(!gi.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=xt(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Rc(i.artifactCount,"Native checkpoint artifactCount");if(u>Na.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let f=xt(i.summary,"Native checkpoint summary"),d=xt(i.nextAction,"Native checkpoint nextAction");if(Ce(f)!==f||Ce(d)!==d)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:xt(i.id,"Native checkpoint id",128),change:e,phase:n,previousRevision:r,stateRevision:a,summary:f,nextAction:d,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function rk(t,e){let i=ba(t,"Native checkpoint journal");if(Sa(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==e)throw new Error("Native checkpoint journal change mismatch");let n=rt(i.previousState),r=rt(i.nextState),a=Bh(i.checkpoint,e),o=ka(i.manifest,e),s=xt(i.inputHash,"Native checkpoint journal inputHash",64),c=G(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!gi.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(n.name!==e||r.name!==e||r.revision!==n.revision+1||a.previousRevision!==n.revision||a.stateRevision!==r.revision||a.phase!==r.phase||a.manifestHash!==Pc(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:e,inputHash:s,createdAt:a.createdAt,previousState:n,nextState:r,checkpoint:a,manifest:o}}async function qh(t,e,i){let n=Dh(t,e,i);await q(t.nativeRoot,n);let r=await Fh(t.nativeRoot,n,"Native checkpoint manifest"),a=ka(r,e);if(Ac(t,a),Pc(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Vh(t,e){let i=Cc(t,e);await q(t.nativeRoot,i);try{let n=rk(await Fh(t.nativeRoot,i,"Native checkpoint journal"),e);return Ac(t,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function zh(t,e,i,n){let r=ka(i,e);Ac(t,r);let a=Pc(r),o=Dh(t,e,a);await q(t.nativeRoot,o);try{let s=await qh(t,e,a);if(JSON.stringify(s)!==JSON.stringify(r))throw new Error("Native checkpoint manifest hash collision")}catch(s){if(s.code!=="ENOENT")throw s}return await Oe(o,r,{containedRoot:t.nativeRoot,beforeCommit:n?.beforeCommit}),a}function Ac(t,e){for(let i of e.artifacts){let n=wd(t,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function Wh(t,e){let i=Bh(e,e.change),n=await qh(t,i.change,i.manifestHash),r=G(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:n.artifacts}));if(i.inputHash!==r||i.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=tk(t,e.change);await q(t.nativeRoot,a),await Oe(a,i,{containedRoot:t.nativeRoot})}import{promises as Vk}from"fs";import zk from"path";import{isDeepStrictEqual as Yc}from"util";import{createHash as ak}from"crypto";function Le(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function ok(t,e){e.has(t)&&Le("cyclic structures are not supported"),e.add(t);try{let i=Object.keys(t);for(let n=0;n<t.length;n+=1)Object.prototype.hasOwnProperty.call(t,n)||Le("sparse arrays are not supported");return(i.length!==t.length||i.some((n,r)=>n!==String(r)))&&Le("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&Le("symbol properties are not supported"),`[${t.map(n=>xc(n,e)).join(",")}]`}finally{e.delete(t)}}function sk(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&Le("only plain objects are supported"),e.has(t)&&Le("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&Le("symbol properties are not supported"),e.add(t);try{let n=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&Le("accessor properties are not supported"),`${JSON.stringify(o)}:${xc(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function xc(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||Le("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?ok(t,e):sk(t,e);case"bigint":case"function":case"symbol":case"undefined":return Le(`${typeof t} values are not supported`)}return Le("unsupported value type")}function Ea(t){return xc(t,new Set)}function W(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return ak("sha256").update(`${t}
|
|
156
|
-
${
|
|
157
|
-
|
|
158
|
-
${
|
|
159
|
-
|
|
160
|
-
`);let i=0;np(t.baseline,t.current,r=>{if(i>=t.detailedChangeCount){Tt(e,"change",r);let a=0;for(let o of t.declaredArtifacts)Aa(o,r.path)&&(a+=1,Tt(e,"change-attribution",o));Tt(e,"change-end",{attributionCount:a}),a===0&&Tt(e,"unattributed-change",{after:r.after,before:r.before,changeKind:r.kind,path:r.path})}i+=1});let n=0;for(let[r,a]of[["baseline",t.baseline],["current",t.current]])for(let o of a.omitted)n>=t.detailedOmissionCount&&Tt(e,"snapshot-omission",{source:r,...o}),n+=1;return e.digest("hex")}function op(t,e,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=Ck(t,e,r,i.gitChangedPaths),s=W(xn,t),c=W(xn,e),l=[];for(let[g,b]of[["baseline",t],["current",e]])for(let y of b.omitted){if(l.length>=mk)break;l.push(at({kind:"snapshot-omission",source:g,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${g} snapshot omitted ${y.path}: ${y.reason}`))}let u=t.omitted.length+e.omitted.length,f=[...Uh("baseline",t),...Uh("current",e),...o.totalChanges===0&&a===null?[at({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],d=()=>{if(i.gitChangedPaths===void 0)return;let g=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(b=>g.has(b)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(b=>!g.has(b))}},p=g=>{let b=o.candidates.slice(0,g.detailedChangeCount),y=b.filter(qe=>qe.attributedTo.length===0),R=o.totalChanges-b.length,O=o.totalUnattributed-y.length,B=u-g.detailedOmissionCount,H=O+B,D=[...y.map(qe=>at({kind:"unattributed-change",source:"implementation-scope",path:qe.path,evidence:{after:qe.after,before:qe.before,changeKind:qe.kind}},`Changed path is not covered by a declared artifact: ${qe.path}`)),...l.slice(0,g.detailedOmissionCount),...f,...R>0||H>0?[ap(g.overflowHash,{changes:R,unattributed:O,unresolved:H})]:[]],J=Ek(D),Be=g.includeGitAdvisory?d():void 0;return{schema:Ic,contractHash:n,baselineProjectionRef:_c(s),baselineProjectionHash:s,currentProjectionRef:_c(c),currentProjectionHash:c,complete:J.length===0,declaredArtifacts:r,changes:b,unattributed:y,unresolvedScopes:J,noCodeReason:a,...Be?{gitAdvisory:Be}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let g=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:w});if(Tn({...g,scopeHash:w})<=Gt)break;if(v){v=!1;continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let k=o.totalChanges>m||u>h?Ak({baseline:t,current:e,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):w,N=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:k}),S={...N,scopeHash:W(tp,N)};if(Tn(S)>Gt)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return S}function Hc(t){let e=Oc(t.baseline),i=Oc(t.current),n=rp(t);return{authority:n,baseline:e,current:i,scope:op(e,i,n)}}var xk=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function ot(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function st(t,e,i,n){let r=new Set([...e,...i]),a=Object.keys(t).filter(s=>!r.has(s)),o=e.filter(s=>!(s in t));if(a.length>0)throw new Error(`${n} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${n} is missing field(s): ${o.join(", ")}`)}function Kt(t,e){if(typeof t!="string"||!$c.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function Yh(t,e,i){let n=_c(e);if(t!==n)throw new Error(`${i} ref/hash mismatch`);return n}function Ca(t,e){let i=ot(t,"Native snapshot projection");if(st(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==ep)throw new Error("Native snapshot projection schema is invalid");let n=hn({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),r=Oc(n);if(W(xn,i)!==W(xn,r))throw new Error("Native snapshot projection is not canonical");let a=W(xn,r);if(e!==void 0&&Kt(e,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function Mc(t,e){let i=ot(t,`Declared artifact ${e}`);if(st(i,["path","kind"],[],`Declared artifact ${e}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${e} kind is invalid`);return{path:It(i.path,`Declared artifact ${e} path`),kind:i.kind}}function Xh(t,e){if(t===null)return null;let i=ot(t,e);return st(i,["hash","size"],[],e),{hash:Kt(i.hash,`${e} hash`),size:wi(i.size,`${e} size`)}}function Qh(t,e){let i=ot(t,`Implementation change ${e}`);if(st(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${e}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${e} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${e} attributedTo must be an array`);let n=i.attributedTo.map(Mc),r=Pa(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${e} attribution must be sorted and unique`);let a=Xh(i.before,`Implementation change ${e} before`),o=Xh(i.after,`Implementation change ${e} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${e} before/after state is invalid`);return{path:It(i.path,`Implementation change ${e} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function Tk(t,e){let i=ot(t,`Unresolved scope ${e}`);st(i,["id","kind","source","path","reason"],[],`Unresolved scope ${e}`);let n=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!n.has(i.kind))throw new Error(`Unresolved scope ${e} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${e} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${e} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${e} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${e} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?ip(i.path,`Unresolved scope ${e} path`):It(i.path,`Unresolved scope ${e} path`),reason:i.reason}}function Ra(t,e){if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error(`${e} must be an array of paths`);let i=t.map((r,a)=>It(r,`${e} ${a}`)),n=[...new Set(i)].sort(oe);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${e} must be sorted and unique`);return i}function xa(t){let e=ot(t,"Native implementation scope"),i=[...xk].filter(b=>b!=="gitAdvisory");if(st(e,i,["gitAdvisory"],"Native implementation scope"),e.schema!==Ic)throw new Error("Native implementation scope schema is invalid");let n=Kt(e.contractHash,"Implementation scope contractHash"),r=Kt(e.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Yh(e.baselineProjectionRef,r,"Implementation scope baseline projection"),o=Kt(e.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Yh(e.currentProjectionRef,o,"Implementation scope current projection");if(typeof e.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(e.declaredArtifacts)||!Array.isArray(e.changes)||!Array.isArray(e.unattributed)||!Array.isArray(e.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=e.declaredArtifacts.map(Mc);if(JSON.stringify(c)!==JSON.stringify(Pa(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=e.changes.map(Qh),u=[...l].sort((b,y)=>oe(b.path,y.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(b=>b.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let f=new Set(c.map(b=>`${b.kind}:${b.path}`));if(l.some(b=>b.attributedTo.some(y=>!f.has(`${y.kind}:${y.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(b=>JSON.stringify(b.attributedTo)!==JSON.stringify(c.filter(y=>Aa(y,b.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=e.unattributed.map(Qh),p=l.filter(b=>b.attributedTo.length===0);if(JSON.stringify(d)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=e.unresolvedScopes.map(Tk),h=m.filter(b=>b.kind==="scope-detail-overflow");if(h.length>1)throw new Error("Implementation scope has multiple detail overflow records");let v=h[0]===void 0?null:Pk(h[0]);if(v&&(v.changes+v.unresolved===0||v.unattributed>v.changes||v.unattributed>v.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let w=e.noCodeReason,E=[...p.map(b=>at({kind:"unattributed-change",source:"implementation-scope",path:b.path,evidence:{after:b.after,before:b.before,changeKind:b.kind}},`Changed path is not covered by a declared artifact: ${b.path}`)),...l.length+(v?.changes??0)===0&&w===null?[at({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:r,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=m.filter(b=>b.kind==="unattributed-change"||b.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(jc))||new Set(m.map(b=>b.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(E.sort(jc))||e.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(e.noCodeReason!==null&&(typeof e.noCodeReason!="string"||e.noCodeReason.length===0||e.noCodeReason.trim()!==e.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let N;if(e.gitAdvisory!==void 0){let b=ot(e.gitAdvisory,"Implementation scope Git advisory");if(st(b,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),b.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let y=Ra(b.changedPaths,"Git changed paths"),R=Ra(b.pathsPresentInSnapshotChanges,"Git present paths"),O=Ra(b.pathsAbsentFromSnapshotChanges,"Git absent paths"),B=[...R,...O].sort(oe),H=new Set(l.map(D=>D.path));if(JSON.stringify(B)!==JSON.stringify(y)||(v?.changes??0)===0&&R.some(D=>!H.has(D))||O.some(D=>H.has(D)))throw new Error("Implementation scope Git advisory partition is invalid");N={advisoryOnly:!0,changedPaths:y,pathsPresentInSnapshotChanges:R,pathsAbsentFromSnapshotChanges:O}}let S={schema:Ic,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:e.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:m,noCodeReason:w,...N?{gitAdvisory:N}:{}},g=Kt(e.scopeHash,"Implementation scope scopeHash");if(W(tp,S)!==g)throw new Error("Implementation scope content hash mismatch");return{...S,scopeHash:g}}function Ik(t){let e=ot(t,"Native implementation scope authority");if(st(e,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths"],"Native implementation scope authority"),!Array.isArray(e.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=e.declaredArtifacts.map(Mc);if(JSON.stringify(i)!==JSON.stringify(Pa(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(e.noCodeReason!==null&&(typeof e.noCodeReason!="string"||e.noCodeReason.length===0||e.noCodeReason.trim()!==e.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let n;e.gitChangedPaths!==void 0&&(n=Ra(e.gitChangedPaths,"Native implementation scope authority Git paths"));let r=rp({contractHash:e.contractHash,declaredArtifacts:i,noCodeReason:e.noCodeReason,...n===void 0?{}:{gitChangedPaths:n}});if(r.contractHash!==e.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return r}function Ta(t){let e=ot(t,"Native implementation scope bundle");st(e,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=Ik(e.authority),n=Ca(e.baseline),r=Ca(e.current),a=xa(e.scope),o=op(n,r,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:n,current:r,scope:o}}function sp(t){let e=xa(t.scope);return Ta({authority:{contractHash:e.contractHash,declaredArtifacts:e.declaredArtifacts,noCodeReason:e.noCodeReason,...e.gitAdvisory?{gitChangedPaths:e.gitAdvisory.changedPaths}:{}},baseline:t.baseline,current:t.current,scope:e})}var up=/^[a-f0-9]{64}$/u;var _k="comet.native.acceptance-trace.v2",Ok="comet.native.partial-allowance.v1",jk="comet.native.verification-evidence.v2";function ct(t,e){if(!up.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function fp(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native evidence source revision must be a positive integer");return t}function dp(t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native evidence change name: ${t}`);return t}function Lc(t,e,i=2e3){let n=Ce(t).trim();if(n.length===0||n.length>i)throw new Error(`${e} must be between 1 and ${i} characters`);return n}function In(t,e){let i=cp.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||cp.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||i!==t||i==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized relative ref`);return t}function $k(t,e,i){let n=In(t,e);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=We(n),a=n.toLowerCase(),o=i?In(i,"Native root ref").toLowerCase():null;if(r||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${e} is excluded as sensitive (${r??"native-runtime"}): ${n}`);return n}function Dc(t){let e=In(t,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(e))throw new Error("Verification receipt ref must identify a typed v3 receipt");return e}function yi(t,e){return t<e?-1:t>e?1:0}function Ia(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function _a(t,e,i){let n=new Set(e),r=Object.keys(t).filter(o=>!n.has(o)),a=e.filter(o=>!(o in t));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function hp(t,e){if(typeof t!="string")throw new Error(`${e} is invalid`);let i=new Date(t);if(Number.isNaN(i.valueOf())||i.toISOString()!==t)throw new Error(`${e} is invalid`);return t}function lp(t,e,i){if(typeof t!="string")throw new Error(`Native ${e} evidence ref is invalid`);let n=`runtime/evidence/${e}/${i}.json`;if(t!==n)throw new Error(`Native ${e} evidence ref/hash mismatch`);return t}function Hk(t){let e=Ia(t,"Native acceptance trace");if(_a(e,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),e.schema!=="comet.native.acceptance-trace.v2"||typeof e.nativeRootRef!="string"||typeof e.criteriaHash!="string"||!up.test(e.criteriaHash)||!Number.isSafeInteger(e.total)||!Number.isSafeInteger(e.evidenced)||!Number.isSafeInteger(e.skipped)||!Array.isArray(e.entries))throw new Error("Native acceptance trace is invalid");let i=In(e.nativeRootRef,"Native root ref"),n=e.entries.map((o,s)=>{let c=Ia(o,`Native acceptance trace entry ${s}`);if(_a(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(f=>typeof f!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(f=>Dc(f)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(yi))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:In(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Lc(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>yi(o.acceptanceId,s.acceptanceId)))||new Set(n.map(o=>o.acceptanceId)).size!==n.length||e.total!==n.length||e.evidenced!==n.filter(o=>o.evidenceRefs.length>0).length||e.skipped!==n.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let r={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:e.criteriaHash,total:e.total,evidenced:e.evidenced,skipped:e.skipped,entries:n},a=ct(e.traceHash,"Native acceptance trace hash");if(W(_k,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function pp(t){let e=Ia(t,"Native partial allowance");if(_a(e,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),e.schema!=="comet.native.partial-allowance.v1"||typeof e.change!="string"||typeof e.scopeHash!="string"||!Array.isArray(e.scopeIds)||e.scopeIds.length===0||e.scopeIds.some(r=>typeof r!="string"||!/^scope:[a-f0-9]{64}$/u.test(r))||JSON.stringify(e.scopeIds)!==JSON.stringify([...new Set(e.scopeIds)].sort(yi))||typeof e.reason!="string"||typeof e.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:dp(e.change),scopeHash:ct(e.scopeHash,"Native partial allowance scopeHash"),scopeIds:e.scopeIds,reason:Lc(e.reason,"Partial allowance reason"),confirmedSummary:Lc(e.confirmedSummary,"Partial allowance confirmation"),sourceRevision:fp(e.sourceRevision),confirmedAt:hp(e.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==e.reason||i.confirmedSummary!==e.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let n=ct(e.allowanceHash,"Native partial allowance hash");if(W(Ok,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function Fc(t){let e=Ia(t,"Native verification evidence");if(_a(e,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),e.schema!=="comet.native.verification-evidence.v2"||typeof e.change!="string"||e.result!=="pass"&&e.result!=="fail"||e.freshness!=="complete"&&e.freshness!=="partial"||typeof e.implementationScopeHash!="string"||typeof e.reportRef!="string"||!Array.isArray(e.requiredReceiptRefs)||!Array.isArray(e.receiptRefs))throw new Error("Native verification evidence is invalid");let i=ct(e.implementationScopeHash,"Native verification implementation scope hash"),n=Hk(e.acceptanceTrace),r=ct(e.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(n.criteriaHash!==r)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=e.partialAllowanceRef!==null||e.partialAllowanceHash!==null;if(e.partialAllowanceRef===null!=(e.partialAllowanceHash===null)||e.freshness==="complete"&&a||e.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=e.partialAllowanceHash===null?null:ct(e.partialAllowanceHash,"Native verification allowance hash"),s=e.receiptRefs.map(d=>Dc(d));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(yi)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(d=>d.evidenceRefs))].sort(yi);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=e.requiredReceiptRefs.map(d=>Dc(d));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(yi)))throw new Error("Native required receipt refs must be canonical");if(e.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:dp(e.change),sourceRevision:fp(e.sourceRevision),result:e.result,freshness:e.freshness,contractHash:ct(e.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:lp(e.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:$k(e.reportRef,"Native verification report ref"),reportHash:ct(e.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:lp(e.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:hp(e.createdAt,"Native verification timestamp")},f=ct(e.envelopeHash,"Native verification envelope hash");if(W(jk,u)!==f)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:f}}function Bc(t,e){if(typeof t!="string"||t.trim().length===0||t.length>4096)throw new Error(`${e} must be between 1 and 4096 characters`)}var Mk=/^[a-f0-9]{64}$/u;var mp=["disposition","overrideSummaryHash","signatureHash"],Lk=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"];function Vc(t,e){return t<e?-1:t>e?1:0}function Dk(t,e,i){let n=Object.keys(t).sort(Vc);if(n.length!==e.length||n.some((r,a)=>r!==e[a]))throw new Error(`${i} fields are invalid`)}function Fk(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new Error(`${e} must be a plain object`);return t}function qc(t,e){if(typeof t!="string"||!Mk.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function Bk(t){if(!Array.isArray(t)||t.length>Tc.maxFailedAcceptanceIds||t.some(e=>typeof e!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(e)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(t)].sort(Vc)}function vp(t){let e=Fk(t,"Native repair trajectory projection"),i=Object.keys(e).sort(Vc),n=i.length===mp.length&&i.every((l,u)=>l===mp[u]);n||Dk(e,Lk,"Native repair trajectory projection");let r=qc(e.signatureHash,"Native repair trajectory signature hash");if(e.disposition!=="continue"&&e.disposition!=="warn"&&e.disposition!=="manual-stop"&&e.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=e.overrideSummaryHash===null?null:qc(e.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&e.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(n)return{signatureHash:r,disposition:e.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=qc(e.contractHash,"Native repair trajectory contract hash"),s=Bk(e.failedAcceptanceIds),c=Jh(e.failedCheckIds);if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:r,disposition:e.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:e.maxVerifyFailures}}var Ni={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:[]},zc=G("comet-native-runtime:v3:semantic-repair-budget"),qk=[{skillVersion:"2",skillHash:G("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:G("comet-native-runtime:v1")}];function gp(t){return t.skillVersion===Ni.definition.metadata.version&&t.skillHash===zc||qk.some(e=>e.skillVersion===t.skillVersion&&e.skillHash===t.skillHash)}async function Oa(t){let i={sequence:(await pi(t.changeDir,t.run.trajectoryRef)).length+1,timestamp:(t.now??new Date).toISOString(),type:t.type,runId:t.run.runId,data:t.data};return await Ah(t.changeDir,t.run.trajectoryRef,i),i}async function Wc(t){let e={runId:t.run.runId,stateVersion:t.run.iteration,trajectoryOffset:t.trajectoryOffset,contextHash:null,artifactsHash:G(t.evidenceHash),createdAt:(t.now??new Date).toISOString()};return await xh(t.changeDir,t.run.checkpointRef,e),e}function wp(t){return G(JSON.stringify({summary:t.summary,confirmed:t.confirmed??!1,artifacts:[...t.artifacts??[]].sort(),noCodeReason:t.noCodeReason??null,verificationResult:t.verificationResult??null,verificationReport:t.verificationReport??null,allowPartialScopeHash:t.allowPartialScopeHash??null,partialReason:t.partialReason??null,repairOverrideSignature:t.repairOverrideSignature??null,repairOverrideSummary:t.repairOverrideSummary??null}))}var Cp=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],Wk=new Set(Cp),Pp=new Set([...Cp,"minimum_runtime_version","revision"]),Jk=new Set([...Pp,"operation"]),Kk=512*1024,Kc=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Gk=new Set([...Kc,"implementationScopeHash","repairScopeHash","repairStagnation"]),Gc=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Xc(t,e){return zk.join(Y(t,e),"runtime","transition.json")}function Uk(t){return`transition-${t}`}async function Yk(t,e,i){let n=Uk(e);return un(t,n,i)}async function $a(t,e,i,n){let r=await Yk(t,e,i);try{return await n()}finally{await fn(r)}}function Ha(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native transition journal must be an object");return t}function Qc(t,e){let i=Object.keys(t).find(n=>!e.has(n));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function ja(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ge(t,e){return Yc(t,e)}function Uc(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native transition journal event data is invalid");let i=t,n=Object.keys(i),r=n.find(u=>!Gk.has(u)),a=[...Kc].find(u=>!Object.hasOwn(i,u)),o=Kc.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0);if(r||a||n.length!==o)throw new Error(`Native transition journal event data keys are invalid${r?`: ${r}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==e)throw new Error("Native transition journal event evidence hash mismatch");if(Bc(i.summary,"Native transition journal event summary"),Ce(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Bc(i.noCodeReason,"Native transition journal event no-code reason"),Ce(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?vp(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:e,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function Xk(t,e){if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,n=Object.keys(i),r=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(n.length===r.size&&n.every(a=>r.has(a))&&i.reason==="spec-rebase")return Uc({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},e)}return Uc(t,e)}function Zc(t,e,i=!1){if(t.change!==e)throw new Error("Native transition journal change mismatch");if(typeof t.id!="string"||t.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof t.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(t.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native transition journal timestamp is invalid");let n=i?Xk(t.eventData,t.evidenceHash):Uc(t.eventData,t.evidenceHash),r=mc(t.nextRun),a=t.previousRun===null?null:mc(t.previousRun);return{id:t.id,evidenceHash:t.evidenceHash,createdAt:t.createdAt,previousRun:a,nextRun:r,eventData:n}}function yp(t,e,i=!1){if(t.skill!==Ni.definition.metadata.name||(i?!gp(t):t.skillVersion!==Ni.definition.metadata.version||t.skillHash!==zc)||t.orchestration!==Ni.definition.orchestration.mode||t.pendingRef!==Ke.pendingRef||t.trajectoryRef!==Ke.trajectoryRef||t.contextRef!==Ke.contextRef||t.artifactsRef!==Ke.artifactsRef||t.checkpointRef!==Ke.checkpointRef)throw new Error(`Native transition journal ${e} metadata or storage refs are invalid`)}function Np(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,retries:t.retries}}function bp(t,e){if(t.status!=="running")throw new Error(`Native transition journal ${e} status must be running`);if(t.pending!==null)throw new Error(`Native transition journal ${e} pending action must be null`)}function el(t,e,i,n=!1){let{previousRun:r,nextRun:a}=i;if(yp(a,"next Run",n||r!==null),bp(a,"next Run"),a.runId!==e.run_id||a.currentStep!==e.phase)throw new Error("Native transition journal next Run does not match the next change state");if(r===null){if(t.run_id!==null||t.phase!=="shape"||a.iteration!==1||Object.keys(a.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(yp(r,"previous Run",!0),bp(r,"previous Run"),t.run_id!==r.runId||r.currentStep!==t.phase||e.run_id!==r.runId)throw new Error("Native transition journal previous Run does not match the change state");if(a.iteration!==r.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!Yc(Np(r),Np(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function Qk(t,e,i){return G(JSON.stringify({operation:"spec-rebase",change:t,summary:e,specChanges:i}))}function Ap(t,e,i){return t.phase!=="shape"&&e.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Sp(t){return"implementation_scope"in t?{implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance}:null}function tl(t,e,i,n,r=!1){let a=i.eventData,o=Sp(t),s=Sp(e);if(a.previousPhase!==t.phase||a.nextPhase!==e.phase)throw new Error("Native transition journal event phases do not match its states");if(t.archived||e.archived)throw new Error("Native transition journal cannot mutate an archived change");if(n==="evidence-retreat"){let c=t.name===e.name&&t.language===e.language&&t.brief===e.brief&&t.approval===e.approval&&("approved_contract_hash"in t?"approved_contract_hash"in e&&t.approved_contract_hash===e.approved_contract_hash:!("approved_contract_hash"in e))&&t.created_at===e.created_at&&t.run_id===e.run_id&&Yc(t.spec_changes,e.spec_changes),l=wp({summary:a.summary});if(!(t.phase==="archive"&&t.verification_result==="pass"||t.phase==="verify"&&t.verification_result==="pending")||e.phase!=="build"||e.verification_result!=="pending"||e.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(n==="spec-rebase"){let c=Qk(t.name,a.summary,e.spec_changes),l=G(`spec-rebase:${t.name}:${a.summary}`);if(t.phase==="shape"||e.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||e.verification_report!==null||!r&&i.evidenceHash!==c||r&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in e&&(e.implementation_scope!==null||e.verification_evidence!==null||e.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(t.phase==="shape"){if(e.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||e.verification_result!=="pending"||t.verification_report!==null||e.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(t.phase==="build"){if(e.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||e.verification_result!=="pending"||e.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(t.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||e.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!==a.verificationResult||e.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function Zk(t,e){let i=Ha(t);if(Qc(i,Jk),i.schema!==mi)throw new Error(`Expected Native transition schema ${mi}`);let n=ja(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(n>3)throw new Error(`Native transition requires runtime protocol ${n}; current protocol is ${3}`);if(n!==3)throw new Error(`Native transition ${mi} minimum_runtime_version must be ${3}`);let r=ja(i.revision,"Native transition revision");if(r!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat")throw new Error("Native transition journal operation is invalid");let a=Zc(i,e),o=rt(i.previousState),s=rt(i.nextState);if(o.name!==e||s.name!==e)throw new Error("Native transition journal state mismatch");if(tl(o,s,a,i.operation),el(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:mi,minimum_runtime_version:3,revision:r,operation:i.operation,id:a.id,change:e,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function eE(t,e){let i=Ha(t);if(Qc(i,Wk),i.schema!==Nn)throw new Error(`Expected Native transition schema ${Nn}`);let n=Zc(i,e,!0),r=Rn(i.previousState),a=Rn(i.nextState);if(r.name!==e||a.name!==e)throw new Error("Native transition journal state mismatch");return tl(r,a,n,Ap(r,a,n.eventData),!0),el(r,a,n,!0),{schema:Nn,id:n.id,change:e,evidenceHash:n.evidenceHash,createdAt:n.createdAt,previousState:r,nextState:a,previousRun:n.previousRun,nextRun:n.nextRun,eventData:n.eventData}}function tE(t,e){let i=Ha(t);if(Qc(i,Pp),i.schema!==vi)throw new Error(`Expected Native transition schema ${vi}`);if(ja(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${vi} minimum_runtime_version must be 2`);let r=ja(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Zc(i,e,!0),o=Cn(i.previousState),s=Cn(i.nextState);if(o.name!==e||s.name!==e)throw new Error("Native v2 transition journal state mismatch");if(tl(o,s,a,Ap(o,s,a.eventData),!0),el(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:vi,minimum_runtime_version:2,revision:r,id:a.id,change:e,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function iE(t,e){let i=Ha(t);if(i.schema===mi)return{status:"current",journal:Zk(i,e)};if(i.schema===Nn)return{status:"migration-required",journal:eE(i,e)};if(i.schema===vi)return{status:"migration-required",journal:tE(i,e)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function nE(t,e){let i=Xc(t,e);await q(t.nativeRoot,i);try{let n=await tt({root:t.nativeRoot,file:i,maxBytes:Kk,label:`Native transition journal ${e}`});return iE(JSON.parse(n.bytes.toString("utf8")),e)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Jc(t,e){let i=await nE(t,e);if(!i)return null;if(i.status==="migration-required")throw new Gc(e);return i.journal}function kp(t,e){if(Ge(t,e.nextRun))return"next";if(e.previousRun===null){if(t===null)return"previous"}else if(Ge(t,e.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${e.change}; recovery journal was preserved`)}function Ep(t,e){if(Ge(t,e.nextState))return"next";if(Ge(t,e.previousState))return"previous";throw new Error(`Native transition change content changed for ${e.change}; recovery journal was preserved`)}function rE(t){let{journal:e}=t;return xp({sequence:t.sequence,timestamp:e.createdAt,type:t.type,runId:e.nextRun.runId,data:t.type==="run_started"?{runtime:"comet-native",phase:e.previousState.phase,transitionId:e.id}:{...e.eventData,transitionId:e.id}})}function xp(t){return{sequence:t.sequence,timestamp:t.timestamp,type:t.type,runId:t.runId,data:t.data}}function Rp(t,e){let i=t.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===e.id),n=i.filter(({event:a})=>a.type==="run_started"),r=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==n.length+r.length||n.length>(e.previousRun===null?1:0)||r.length>1||e.previousRun===null&&r.length===1&&(n.length!==1||n[0].index>=r[0].index))throw new Error(`Native trajectory transition id collision for ${e.change}; recovery journal was preserved`);for(let a of[...n,...r]){let o=rE({sequence:a.index+1,journal:e,type:a.event.type});if(!Ge(xp(a.event),o))throw new Error(`Native trajectory event changed for transition ${e.id}; recovery journal was preserved`)}return{started:n[0]?.event??null,transitioned:r[0]?.event??null}}async function il(t,e,i){if(await Pn(t,e))throw new Error(`Native schema migration is incomplete for ${e}; run doctor --repair`);await va(t,e);let n=await Jc(t,e);if(!n)return null;let r=Y(t,e),a=Rp(await pi(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([yn(r),Ne(t,e)]),c=kp(o,n),l=Ep(s,n);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${n.change}; recovery journal was preserved`);if(c==="previous"&&(await vc(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!Ge(await yn(r),n.nextRun))throw new Error(`Native transition Run content changed while continuing ${n.change}; recovery journal was preserved`);if(l==="previous"){let v=await ya(t,n.nextState,n.previousState.revision);if(!Ge(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!Ge(await Ne(t,e),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await Jc(t,e);if(!u||!Ge(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let f=Rp(await pi(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(f.started||await Oa({changeDir:r,run:n.nextRun,type:"run_started",data:{runtime:"comet-native",phase:n.previousState.phase,transitionId:n.id},now:new Date(n.createdAt)}));let d=f.transitioned;d||(d=await Oa({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await Wc({changeDir:r,run:n.nextRun,trajectoryOffset:d.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([yn(r),Ne(t,e)]);kp(p,{...n,previousRun:n.nextRun}),Ep(m,{...n,previousState:n.nextState});let h=await Jc(t,e);if(!h||!Ge(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await Vk.rm(Xc(t,e),{force:!0}),n.nextState}async function Tp(t,e,i){let n=await Vh(t,e);if(!n)return null;if(await zh(t,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await ya(t,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await Wh(t,n.checkpoint),await i?.afterProgressWritten?.(n),await aE.rm(Cc(t,e),{force:!0}),n}async function nl(t,e){await il(t,e),await Tp(t,e)}var Ma="scoped-text-safety",oE=1,sE=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var cE="comet.native.checker-policy.v1";var i_=W(cE,{policy:Ma,version:oE,limits:sE,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var lE=["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"],n_=new Set(lE);var f_=512*1024;import Dp from"node:path";import Ip from"node:path";var uE="comet.native.acceptance.v1",fE=/^acceptance-[a-f0-9]{64}$/u,dE=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),hE=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u;var m_=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),On=Object.freeze({maxCriteria:1024}),_n="<!-- comet-native:acceptance-evidence:start -->",bi="<!-- comet-native:acceptance-evidence:end -->";function ol(t){let e=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(t);return e?{level:e[1].length,text:e[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function rl(t,e){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(t);if(!i)return e;let n=i[1][0];return e===null?{marker:n,length:i[1].length}:n===e.marker&&i[1].length>=e.length&&i[2].trim().length===0?null:e}function _p(t){return t.includes("-->")||t.includes("--!>")}function*Si(t){let e=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=t.replace(/\r\n?/gu,`
|
|
151
|
+
${Buffer.byteLength(n)}:${n}`)}function Rc(t){return t.reason==="git-enumeration-limit"||t.reason==="git-selection-changed"||t.reason==="physical-enumeration-limit"||t.reason==="physical-selection-changed"}function Nh(t){for(let e=t.length-1;e>=0;e-=1){let i=t[e];if(!Rc(i))return t.splice(e,1),i}return null}function Rt(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return ue(i,n)?B(i,n):B(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Ck(t,e,i,n){if(!I(n))return{status:"budget-exhausted"};let r;try{r=await U.open(t,"r")}catch(c){if(!I(n))return{status:"budget-exhausted"};throw c}if(!I(n))return await r.close(),{status:"budget-exhausted"};let a=Na("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,e+1)),s=0;try{if(!I(n))return{status:"budget-exhausted"};let c=await r.stat();if(!I(n))return{status:"budget-exhausted"};if(!c.isFile()||!Rt(i,c))return{status:"changed"};for(;;){if(!I(n))return{status:"budget-exhausted"};let l=e+1-s;if(l<1)return{status:"changed"};let u=await r.read(o,0,Math.min(o.length,l),null);if(!I(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!I(n))return{status:"budget-exhausted"};let f=await r.stat();return I(n)?!f.isFile()||!Rt(c,f)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:f}:{status:"budget-exhausted"}}if(s+u.bytesRead>e)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await r.close()}}function Pe(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Ae(t,e,i){let n=Object.keys(t).find(r=>!e.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function hi(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ge(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function _h(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let i=$.posix.normalize(t);if(i!==t||$.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function Pk(t,e){let i=Pe(t,`Native snapshot entry ${e}`);Ae(i,Ub,`Native snapshot entry ${e}`);let n=_h(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!ba.test(i.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let r={path:n,hash:i.hash,size:Ge(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Rh.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function Ak(t,e){let i=Pe(t,`Native snapshot omission ${e}`);if(Ae(i,Yb,`Native snapshot omission ${e}`),!Zb.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!ek.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:_h(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:Ge(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function xk(t){let e=Pe(t,"Native snapshot omission overflow");if(Ae(e,Xb,"Native snapshot omission overflow"),typeof e.hash!="string"||!ba.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:e.hash,count:hi(e.count,"Native snapshot omission overflow count")}}function di(t,e){let i=Pe(t,e);if(Ae(i,Jb,e),typeof i.hash!="string"||!ba.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let n=Ge(i.recordCount,`${e} recordCount`),r=Ge(i.storedRecordCount,`${e} storedRecordCount`),a=Ge(i.stdoutBytes,`${e} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function bh(t){let e=Pe(t,"Native Git selection evidence");if(Ae(e,zb,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=di(e.stageBefore,"Native Git selection stageBefore"),n=di(e.combined,"Native Git selection combined"),r=di(e.stageAfter,"Native Git selection stageAfter"),a=di(e.finalStageBefore,"Native Git selection finalStageBefore"),o=di(e.finalCombined,"Native Git selection finalCombined"),s=di(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(f=>f.overflow),l=!Ct(i,r)||!Ct(r,a)||!Ct(n,o)||!Ct(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function kh(t,e){let i=Pe(t,e);if(Ae(i,Kb,e),typeof i.hash!="string"||!ba.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${e} flags are invalid`);let n=Ge(i.visitedNodeCount,`${e} visitedNodeCount`),r=Ge(i.recordCount,`${e} recordCount`),a=Ge(i.storedRecordCount,`${e} storedRecordCount`),o=Ge(i.encodedBytes,`${e} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function Tk(t){let e=Pe(t,"Native physical selection evidence");if(Ae(e,Gb,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=kh(e.before,"Native physical selection before"),n=kh(e.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!xh(i,n);if(!r&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=r&&a?"overflow-and-changed":r?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:n}}function yn(t){let e=Pe(t,"Native content snapshot manifest");if(Ae(e,Bb,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Qb.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let g=Pe(e.capture,"Native content snapshot capture");if(Ae(g,Vb,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let y=g.gitSelection===void 0?void 0:bh(g.gitSelection),w=g.physicalSelection===void 0?void 0:Tk(g.physicalSelection),R=null;if(g.projection!==void 0){let _=Pe(g.projection,"Native content snapshot projection");if(Ae(_,Wb,"Native content snapshot projection"),_.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");R={provider:"git",..._.selection===void 0?{}:{selection:bh(_.selection)}}}if(g.provider==="git"){if(w||R)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...y?{gitSelection:y}:{}}}else{if(y)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(w&&R)throw new Error("Native physical-tree capture cannot combine selection and projection");i=R?{provider:"physical-tree",projection:R}:{provider:"physical-tree",...w?{physicalSelection:w}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=Pe(e.limits,"Native content snapshot limits");Ae(n,Db,"Native content snapshot limits");let r={maxFiles:hi(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:hi(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:hi(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:hi(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:hi(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let g=Pe(e.policy,"Native snapshot policy");if(Ae(g,qb,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Ih({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(Pk),s=e.omitted.map(Ak),c=Ge(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:xk(e.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>r.maxFileBytes)||o.reduce((g,y)=>g+y.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Eh||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let f=s.filter(g=>g.reason==="git-enumeration-limit"),d=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...f,...d])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(f.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(f.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(g=>g.reason==="physical-enumeration-limit"),S=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...v,...S])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=i?.physicalSelection,E=N?.status==="overflow"||N?.status==="overflow-and-changed",b=N?.status==="changed"||N?.status==="overflow-and-changed";if(E!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(b!==(S.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:e.origin,...i?{capture:i}:{},createdAt:e.createdAt,complete:e.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Th(k)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}function Ik(t,e){if(!Fb.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=$.join(t.changesDir,e);if(!se(t.changesDir,i))throw new Error("Native change path escaped");return $.join(i,"runtime","baseline-manifest.json")}async function jh(t,e={}){let i={maxFiles:e.limits?.maxFiles??ga.maxFiles,maxFileBytes:e.limits?.maxFileBytes??ga.maxFileBytes,maxTotalBytes:e.limits?.maxTotalBytes??ga.maxTotalBytes,maxManifestBytes:e.limits?.maxManifestBytes??ga.maxManifestBytes,...e.limits?.maxDurationMs===void 0?{}:{maxDurationMs:e.limits.maxDurationMs}},n=Ih(e.policy),r=ok({...e,deadlineMs:e.deadlineMs??i.maxDurationMs}),a=lk(e.gitSelectionLimits),o=sk(e.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=$.resolve(t.projectRoot),c=await U.realpath(s),l=$.resolve(t.nativeRoot),u=await U.realpath(l),f=$.resolve(t.configFile),d=$.join(s,".comet","current-change.json"),p=kk(s,e.denylist??[]),m=[],h=[],v=new Map,S=new Map,N=0,E=0,b=G("comet.native.snapshot-omission-overflow.v1"),k=0,g=!1,y=null,w=x=>{E+=1,b=kc(b,"omission",x)},R=x=>{if(N+=1,h.length<Eh){h.push(x);return}if(Rc(x)){let A=Nh(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),h.push(x);return}w(x)},_=x=>{N+=x.count,E+=x.count,b=kc(b,"git-selection",{source:"git-selection",...x})},D=x=>{E+=1,b=kc(b,"manifest-entry",{reason:"manifest-size",entry:x})},H=async(x,A)=>{m.push(x),k+=x.size,v.set(x.path,A),g||(g=!0,await e.gitSelectionHooks?.afterFirstEntryCaptured?.(x.path))},F=(x,A)=>{let T=m.findIndex(K=>K.path===x);if(T<0)return;let[O]=m.splice(T,1);k-=O.size,v.delete(x),R(A)},z=async(x,A,T,O)=>{if(!T.isFile()||T.isSymbolicLink()||!I(r))return;let K;try{K=await U.realpath(x)}catch(P){if(!I(r))return;if(!ie(P)&&!te(P))throw P;R({path:A,size:T.size,type:"file",reason:te(P)?"changed-during-read":"unreadable"});return}if(!I(r)||!se(c,K)||Pt(u,K))return;if(m.length>=i.maxFiles){R({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){R({path:A,size:T.size,type:"file",reason:"file-size"});return}if(k+T.size>i.maxTotalBytes){R({path:A,size:T.size,type:"file",reason:"total-size"});return}let L,j,X;try{if(L=await Ck(K,T.size,T,r),L.status==="budget-exhausted"||!I(r))return;if(L.status==="changed"){R({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!I(r)||(X=await U.realpath(x),!I(r)))return;j=await U.lstat(x)}catch(P){if(!I(r))return;if(!ie(P)&&!te(P))throw P;R({path:A,size:T.size,type:"file",reason:te(P)?"changed-during-read":"unreadable"});return}if(I(r)){if(L.bytes!==T.size||X!==K||!Rt(T,L.finalStat)||!Rt(L.finalStat,j)||!j.isFile()||j.isSymbolicLink()||j.size!==T.size||j.mtimeMs!==T.mtimeMs||j.ctimeMs!==T.ctimeMs){R({path:A,size:j.isFile()?j.size:null,type:j.isFile()?"file":"other",reason:"changed-during-read"});return}I(r)&&await H({path:A,hash:L.hash,size:j.size,type:"file",...O===void 0?{}:{gitObjectId:O}},{kind:"file",target:x,realTarget:K,stat:j})}},qe=async(x,A,T)=>{if(!I(r))return;let O,K,L;try{if(O=await U.readlink(x,{encoding:"buffer"}),!I(r)||(L=await U.lstat(x),!I(r)))return;K=await U.readlink(x,{encoding:"buffer"})}catch(P){if(!I(r))return;if(!ie(P)&&!te(P))throw P;R({path:A,size:null,type:"other",reason:te(P)?"changed-during-read":"unreadable"});return}if(!I(r))return;if(!L.isSymbolicLink()||!Rt(T,L)||L.mtimeMs!==T.mtimeMs||L.ctimeMs!==T.ctimeMs||!O.equals(K)){R({path:A,size:null,type:"other",reason:"changed-during-read"});return}let j=O.byteLength;if(m.length>=i.maxFiles){R({path:A,size:j,type:"other",reason:"file-count"});return}if(j>i.maxFileBytes){R({path:A,size:j,type:"other",reason:"file-size"});return}if(k+j>i.maxTotalBytes){R({path:A,size:j,type:"other",reason:"total-size"});return}let X=Na("sha256").update("symlink\0").update(O).digest("hex");I(r)&&await H({path:A,hash:X,size:j,type:"file"},{kind:"symlink",target:x,rawTarget:O,stat:L})},Ve=async()=>{for(let[x,A]of[...v]){if(!I(r))return;if(A.kind==="file"){let j,X;try{if(j=await U.realpath(A.target),!I(r))return;X=await U.lstat(A.target)}catch(P){if(!I(r))return;if(!ie(P)&&!te(P))throw P;F(x,{path:x,size:null,type:"file",reason:ie(P)?"unreadable":"changed-during-read"});continue}if(!I(r))return;(j!==A.realTarget||!X.isFile()||X.isSymbolicLink()||!Rt(A.stat,X)||X.size!==A.stat.size||X.mtimeMs!==A.stat.mtimeMs||X.ctimeMs!==A.stat.ctimeMs)&&F(x,{path:x,size:X.isFile()?X.size:null,type:X.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let j,X;try{if(j=await U.lstat(A.target),!I(r))return;X=await U.readlink(A.target,{encoding:"buffer"})}catch(P){if(!I(r))return;if(!ie(P)&&!te(P))throw P;F(x,{path:x,size:null,type:"other",reason:ie(P)?"unreadable":"changed-during-read"});continue}if(!I(r))return;(!j.isSymbolicLink()||!Rt(A.stat,j)||j.mtimeMs!==A.stat.mtimeMs||j.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(X))&&F(x,{path:x,size:null,type:"other",reason:"changed-during-read"});continue}let T,O;try{if(T=await U.realpath(A.target),!I(r))return;O=await U.lstat(A.target)}catch{if(!I(r))return;F(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!I(r))return;if(!(T===A.realTarget&&O.isDirectory()&&!O.isSymbolicLink()&&Rt(A.stat,O)&&se(c,T)&&!Pt(u,T))){F(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"});continue}let L;try{if(!I(r))return;L=await gh(r,T)}catch(j){if(pi(j))throw j;F(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!I(r))return;L.dirty?F(x,{path:x,size:null,type:"directory",reason:"gitlink-dirty"}):L.hash!==A.hash&&F(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"})}for(let[x,A]of S){if(!I(r))return;try{let T=await U.lstat(A);if(!I(r))return;R({path:x,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!I(r))return;if(te(T))continue;if(!ie(T))throw T;R({path:x,size:null,type:"file",reason:"unreadable"})}}},we=await hk(r,t,a,e.gitSelectionHooks);if(we===null){let x=await mh({execution:r,paths:t,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:e.physicalSelectionHooks});await e.physicalSelectionHooks?.afterInitialSelection?.();for(let O of x.records){if(O.type!=="file"&&O.type!=="symlink"||v.has(O.path))continue;if(Le(r)<1)break;if(!yh(n,O.path,r))continue;if(Le(r)<1)break;let K=$.resolve(s,...O.path.split("/")),L;try{L=await U.lstat(K)}catch(j){if(!I(r))break;if(!ie(j)&&!te(j))throw j;R({path:O.path,size:null,type:"file",reason:te(j)?"changed-during-read":"unreadable"});continue}if(Le(r)<1)break;if(O.type==="symlink"&&L.isSymbolicLink()){if(await qe(K,O.path,L),Le(r)<1)break;continue}if(O.type!=="file"||!L.isFile()||L.isSymbolicLink()){R({path:O.path,size:L.isFile()?L.size:null,type:L.isDirectory()?"directory":L.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await z(K,O.path,L),Le(r)<1)break}Le(r)>=1&&await Ve();let A=await mh({execution:r,paths:t,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),T=wk(x.evidence,A.evidence);y=T.evidence;for(let O of[...x.omissions,...A.omissions,...T.omissions])h.some(K=>K.path===O.path&&K.reason===O.reason)||R(O)}else{await e.gitSelectionHooks?.afterInitialSelection?.();let x=e.incrementalBaseline,A=new Map,T=!1;if(x){let P=yn(x);for(let Q of P.entries)Q.gitObjectId!==void 0&&A.set(Q.path,Q);T=A.size>0}let O=new Set,K=!0;try{let P=await wa(r,s,["ls-files","-v","-z"],{...a,...e.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:e.gitSelectionHooks.outputChunkBytes}});if(P.overflow)T=!1,K=!1,A.clear();else for(let Q of P.records){let Z=Ec(Q),le=Z.indexOf(" "),ae=le<0?null:mi(Z.slice(le+1));if(le!==1||ae===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");Z[0]!=="H"&&O.add(ae)}}catch(P){if(pi(P))throw P;T=!1,K=!1,A.clear()}let L=new Set;try{let P=await ya(r,s,["ls-files","--modified","-z"],Sc);for(let Q of P.toString("utf8").split("\0")){let Z=mi(Q);Z!==null&&L.add(Z)}}catch{T=!1,K=!1,A.clear()}let j=new Set,X=new Set;for(let P of yk(we)){if(v.has(P)||!Nk(t,P))continue;if(Le(r)<1)break;if(!yh(n,P,r))continue;if(Le(r)<1)break;let Q=$.resolve(s,...P.split("/"));if(Q===f||Q===d||p.some(ye=>Pt(ye,Q)))continue;if(we.gitlinks.has(P)){if(m.length>=i.maxFiles){R({path:P,size:0,type:"file",reason:"file-count"});continue}let ye,Gn;try{[ye,Gn]=await Promise.all([U.realpath(Q),U.lstat(Q)])}catch{R({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Gn.isSymbolicLink()||!Gn.isDirectory()||!se(c,ye)||Pt(u,ye)){R({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Qt=await gh(r,ye);if(Qt.dirty){R({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await H({path:P,hash:Qt.hash,size:0,type:"file"},{kind:"gitlink",target:Q,realTarget:ye,stat:Gn,hash:Qt.hash})}catch(Qt){if(pi(Qt))throw Qt;R({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let Z;try{Z=await U.lstat(Q)}catch(ye){if(te(ye)&&we.tracked.has(P)){S.set(P,Q);continue}if(!ie(ye)&&!te(ye))throw ye;R({path:P,size:null,type:"file",reason:te(ye)?"changed-during-read":"unreadable"});continue}if(Z.isSymbolicLink()){await qe(Q,P,Z);continue}if(!Z.isFile()){we.nestedRepositories.has(P)||R({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let le=we.trackedObjectIds.get(P),ae=le?A.get(P):void 0;if(T&&ae?.gitObjectId!==void 0&&ae.gitObjectId===le&&!O.has(P)&&!L.has(P)){if(m.length>=i.maxFiles){R({path:P,size:ae.size,type:"file",reason:"file-count"});continue}if(ae.size>i.maxFileBytes){R({path:P,size:ae.size,type:"file",reason:"file-size"});continue}if(k+ae.size>i.maxTotalBytes){R({path:P,size:ae.size,type:"file",reason:"total-size"});continue}m.push({...ae}),k+=ae.size,j.add(P);continue}let ql=K&&!O.has(P)&&!L.has(P)?le:void 0;await z(Q,P,Z,ql),ql!==void 0&&X.add(P)}if(await Ve(),await e.gitSelectionHooks?.afterContentRevalidation?.(),await mk(r,t,a,we,e.gitSelectionHooks?.outputChunkBytes),j.size>0||T&&X.size>0){let P=await ya(r,s,["ls-files","--modified","-z"],Sc),Q=new Set;for(let Z of P.toString("utf8").split("\0")){let le=mi(Z);le!==null&&Q.add(le)}for(let Z of j){if(!Q.has(Z))continue;let le=m.find(ae=>ae.path===Z);F(Z,{path:Z,size:le?.size??null,type:"file",reason:"changed-during-read"})}for(let Z of X){if(!Q.has(Z))continue;let le=m.find(ae=>ae.path===Z);le&&delete le.gitObjectId}}for(let P of we.omissions)R(P);we.overflow&&_(we.overflow)}m.sort((x,A)=>x.path.localeCompare(A.path,"en")),h.sort((x,A)=>x.path.localeCompare(A.path,"en"));let Fm=we===null?{provider:"physical-tree",...y?{physicalSelection:y}:{}}:{provider:"git",...we.evidence?{gitSelection:we.evidence}:{}},Dl=()=>({schema:"comet.native.content-snapshot.v1",origin:e.origin??"explicit",capture:Fm,createdAt:(e.now??new Date).toISOString(),complete:N===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:N,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:E}}:{}}),fo=Dl();for(;Th(fo)>i.maxManifestBytes;){if(h.filter(A=>!Rc(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let O=Nh(h);if(O===null)break;w(O)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))N+=1,D(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");fo=Dl()}return fo}async function Pc(t,e,i={}){let r=(await zt(t.projectRoot))?.native.snapshot??uc;return jh(t,{...i,policy:e.policy,incrementalBaseline:e,limits:{maxFiles:r.max_files,maxFileBytes:r.max_total_bytes,maxTotalBytes:r.max_total_bytes,maxDurationMs:r.max_duration_ms},deadlineMs:r.max_duration_ms})}async function Oh(t,e){let i=Ik(t,e);await q(t.nativeRoot,i);try{let n=await ah({root:t.nativeRoot,file:i,maxBytes:Lb,label:"Native baseline snapshot manifest"});return yn(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as Uk}from"crypto";import jc from"path";var Ke=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{constants as Sa,promises as de}from"node:fs";import be from"node:path";import{TextDecoder as Vk}from"node:util";import Fk from"path";var Mk=ho(Gr(),1);var $h=(t,e)=>{let i=t[e];return i==null?null:String(i)};function bn(t,e){let i=t[e];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return i}function Nn(t,e){let i=bn(t,e);if(Fk.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return i}function Bk(t){let e=t.run_retries??"{}",i;try{i=typeof e=="string"?JSON.parse(e):e}catch(n){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:n})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let n of Object.values(i))if(!Number.isInteger(n)||Number(n)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Hh(t){if(!t.run_id)return null;let e=bn(t,"run_id"),i=bn(t,"skill"),n=bn(t,"skill_version"),r=bn(t,"skill_hash"),a=Nn(t,"pending_ref"),o=Nn(t,"trajectory_ref"),s=Nn(t,"context_ref"),c=Nn(t,"artifacts_ref"),l=Nn(t,"checkpoint_ref"),u=Number(t.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:i,skillVersion:n,skillHash:r,orchestration:t.orchestration,currentStep:$h(t,"current_step"),iteration:u,pending:$h(t,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:Bk(t)}}var $T=256*1024;var Dk=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function qk(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)},i=Hh(e);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function ka(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid Run state: stored value must be an object");let e=t,i=Object.keys(e).find(n=>!Dk.has(n));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(e.currentStep!==null&&(typeof e.currentStep!="string"||e.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(e.pending!==null&&(typeof e.pending!="string"||e.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!e.retries||typeof e.retries!="object"||Array.isArray(e.retries))throw new Error("Invalid Run state: retries must be an object");return qk(e)}var Ne={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Sn(t,e){let i=be.relative(t,e);return i===""||!be.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${be.sep}`)}function Lh(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function kn(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}function Wk(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function gi(t,e,i){let n=Ke[e];if(i!==void 0&&i!==n)throw new Error(`Native Run ${e} ref must be ${n}`);let r=be.resolve(t),a=be.resolve(r,...n.split("/"));if(!Sn(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Mh(t){let e=await de.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${t}`);return{path:t,realPath:await de.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Ac(t,e){let i=be.resolve(t),n=be.resolve(e);if(!Sn(i,n))throw new Error("Native Run path is outside its change");let r=[await Mh(i)],a=i;for(let o of be.relative(i,n).split(be.sep).filter(Boolean)){a=be.join(a,o);let s;try{s=await Mh(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Sn(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function Ea(t){for(let e of t){let i=await de.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Wk(e,i)||await de.realpath(e.path)!==e.realPath)throw new Error(`Native Run parent changed during I/O: ${e.path}`)}}async function zk(t,e,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-r,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>e)throw new Error(`${i} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function En(t,e,i,n,r){let a=await Ac(t,be.dirname(e));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await de.lstat(e)}catch(f){if(f.code==="ENOENT")return null;throw f}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${n} must be a regular file`);if(o.size>i)throw new Error(`${n} exceeds ${i} bytes`);let s=Lh(o),c=await de.realpath(e);if(!Sn(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?Sa.O_RDONLY:Sa.O_RDONLY|Sa.O_NOFOLLOW|Sa.O_NONBLOCK,u;try{u=await de.open(e,l)}catch(f){throw new Error(`${n} changed while opening`,{cause:f})}try{let[f,d,p]=await Promise.all([u.stat(),de.lstat(e),de.realpath(e)]);if(await Ea(a),!f.isFile()||!d.isFile()||d.isSymbolicLink()||p!==c||!kn(s,f)||!kn(s,d))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await zk(u,i,n);await r?.beforeFinalCheck?.();let[h,v,S]=await Promise.all([u.stat(),de.lstat(e),de.realpath(e)]);if(await Ea(a),!v.isFile()||v.isSymbolicLink()||S!==c||!kn(s,h)||!kn(s,v))throw new Error(`${n} changed while reading`);let N;try{N=new Vk("utf-8",{fatal:!0}).decode(m)}catch(E){throw new Error(`${n} is not valid UTF-8`,{cause:E})}return{text:N,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function Jk(t,e,i){let n=await Ac(t,be.dirname(e));if(!n)return{exists:!1};let r;try{r=await de.lstat(e)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!r.isFile()||r.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await de.realpath(e);if(!Sn(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Ea(n),{exists:!0,identity:Lh(r),realPath:a}}async function Gk(t,e,i,n){let r=await Ac(t,be.dirname(e));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await de.lstat(e)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${n} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!kn(i.identity,a)||await de.realpath(e)!==i.realPath)throw new Error(`${n} changed before commit`);await Ea(r)}async function xc(t){if(Buffer.byteLength(t.content,"utf8")>t.maxBytes)throw new Error(`${t.label} exceeds ${t.maxBytes} bytes`);let i=t.expected??await Jk(t.changeDir,t.file,t.label);if(i.exists&&i.identity.size>t.maxBytes)throw new Error(`${t.label} exceeds ${t.maxBytes} bytes`);await et(t.file,t.content,{containedRoot:t.changeDir,beforeCommit:async()=>{await t.hooks?.beforeCommit?.(),await Gk(t.changeDir,t.file,i,t.label)}});let n=await En(t.changeDir,t.file,t.maxBytes,t.label);if(!n||n.text!==t.content)throw new Error(`${t.label} commit could not be verified`)}function Kk(t,e){try{return JSON.parse(t)}catch(i){throw new Error(`${e} contains invalid JSON`,{cause:i})}}function Fh(t){return`${JSON.stringify(t,null,2)}
|
|
152
|
+
`}function Tc(t){return ka(t)}async function Rn(t,e){let i=gi(t,"stateRef"),n=await En(t,i,Ne.runStateBytes,"Native Run state",e);return n?ka(Kk(n.text,"Native Run state")):null}async function Ic(t,e,i){let n=ka(e);await xc({changeDir:t,file:gi(t,"stateRef"),content:Fh(n),maxBytes:Ne.runStateBytes,label:"Native Run state",hooks:i})}async function wi(t,e,i){let n=gi(t,"trajectoryRef",e),r=await En(t,n,Ne.trajectoryBytes,"Native Run trajectory",i);if(!r)return[];let a=r.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Ne.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ne.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function Bh(t,e,i){return(await En(t,gi(t,"trajectoryRef",e),Ne.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Dh(t,e,i,n){let r=gi(t,"trajectoryRef",e),a=`${JSON.stringify(i)}
|
|
153
|
+
`;if(Buffer.byteLength(a,"utf8")>Ne.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Ne.trajectoryEventBytes} bytes`);let o=await En(t,r,Ne.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Ne.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ne.trajectoryEvents} events`);await xc({changeDir:t,file:r,content:`${o?.text??""}${a}`,maxBytes:Ne.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function qh(t,e,i,n){await xc({changeDir:t,file:gi(t,"checkpointRef",e),content:Fh(i),maxBytes:Ne.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var Yk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Oc=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function _c(t){return Uk("sha256").update(t).digest("hex")}function Xk(t,e){if(!Yk.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=jc.join(t.changesDir,e);if(!se(t.changesDir,i))throw new Error("Native change path escaped");return jc.join(i,"runtime","trajectory.jsonl")}function Qk(t){let e=t.split(/\n/u),i=0;for(let n=0;n<e.length;n+=1){let r=e[n].endsWith("\r")?e[n].slice(0,-1):e[n];if(r.length!==0){i=n+1;try{JSON.parse(r)}catch(a){return{status:"invalid",line:n+1,message:a.message}}}}return{status:"valid",count:i}}function Zk(t,e){if(/Unexpected end|Unterminated string/iu.test(t.message))return!0;let i=/position (\d+)/iu.exec(t.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,e.length-1)}function eS(t,e){let i=e.lastIndexOf(10),n=e.subarray(0,i+1),r=Qk(n.toString("utf8"));if(r.status==="invalid")return{status:"invalid",file:t,line:r.line,message:r.message};if(i===e.length-1)return{status:"clean",file:t};let a=e.subarray(i+1),o=a.toString("utf8"),s=r.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([e,Buffer.from(`
|
|
154
|
+
`)])}catch(f){if(!Zk(f,o))return{status:"invalid",file:t,line:s,message:f.message};c="incomplete-json",l=n}return{inspection:{status:"repairable",file:t,reason:c,line:s,originalHash:_c(e),targetHash:_c(l),tailHash:_c(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function tS(t,e){let i=Xk(t,e);await q(t.nativeRoot,i);let n=jc.join(t.changesDir,e),r=await Bh(n,Ke.trajectoryRef);return r===null?{status:"clean",file:i}:eS(i,Buffer.from(r))}async function iS(t,e){let i=await tS(t,e);return"inspection"in i?i.inspection:i}async function Ra(t,e){let i=await iS(t,e);if(i.status!=="clean")throw new Oc(i)}import{createHash as aS}from"node:crypto";import{promises as Pa}from"node:fs";import At from"node:path";import{execFileSync as nS}from"child_process";import Ca from"path";function $c(t,e){return nS("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function rS(t,e){let i=Ca.normalize(t),n=Ca.normalize(e);return process.platform==="win32"?i.toLowerCase()===n.toLowerCase():i===n}function Vh(t){try{let e=Ca.resolve($c(t,["rev-parse","--show-toplevel"])),n=$c(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),r=n?Ca.resolve(n.slice(9)):e,a=null;try{a=$c(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!rS(e,r),currentWorktreeRoot:e,primaryWorktreeRoot:r,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}var Cn=/^[a-f0-9]{64}$/u,oS=16*1024,Hc=process.platform;function Gh(t,e){let i=At.relative(t,e);return At.isAbsolute(i)||i===".."||i.startsWith(`..${At.sep}`)?null:i.replaceAll("\\","/")||"."}function Kh(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function Uh(t,e){if(t.length===0||Kh(t)||t.includes("\\")||At.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let i=At.posix.normalize(t);if(i!==t||i===".."||i.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return i}function Mc(t,e){return aS("sha256").update(`${t}
|
|
155
|
+
${e}`).digest("hex")}async function Wh(t,e){let i=await Pa.realpath(e),n=await Pa.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Hc==="win32"?At.normalize(i).toLowerCase():i;return Mc(t,`${r}
|
|
156
|
+
${n.dev}
|
|
157
|
+
${n.ino}
|
|
158
|
+
${n.birthtimeMs}`)}async function zh(t,e){let i=await Pa.realpath(e),n=await Pa.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Hc==="win32"?At.normalize(i).toLowerCase():i;return Mc(t,r)}function sS(t){if(typeof t!="string")throw new Error("Native workspace capturedAt is invalid");let e=new Date(t);if(!Number.isFinite(e.getTime())||e.toISOString()!==t)throw new Error("Native workspace capturedAt is invalid");return t}function Jh(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||Kh(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function Yh(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Jh(t.changeBranch,"Native workspace change branch"),Jh(t.targetBranch,"Native workspace target branch"),(t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function Aa(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace identity must be an object");let e=t,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","isolation","changeBranch","targetBranch","finish"]),n=Object.keys(e).filter(o=>!i.has(o));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(e.schema!=="comet.native.workspace.v2"&&e.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(e.capturedRevision)||e.capturedRevision<1||typeof e.nativeRootRef!="string"||!Cn.test(String(e.projectRootId))||!Cn.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");sS(e.capturedAt),Uh(e.nativeRootRef,"Native workspace root ref");let r=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(r!==a)throw new Error("Native workspace path identities must be provided together");if(r&&!Cn.test(String(e.projectRootPathId))||a&&!Cn.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!Cn.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.schema==="comet.native.workspace.v2"){if(e.isolation!==void 0||e.changeBranch!==void 0||e.targetBranch!==void 0||e.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof e.isolation!="string"||e.changeBranch===void 0||e.targetBranch===void 0||e.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(Yh(e),e.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(e.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function cS(t,e){return At.join(t.changesDir,e,"runtime","workspace.json")}function lS(t,e){let i=Gh(t.nativeRoot,cS(t,e));if(!i||i===".")throw new Error("Native workspace file escaped its root");return Uh(i,"Native workspace file ref")}async function uS(t,e){try{let i=await Re({root:t.nativeRoot,ref:lS(t,e),maxBytes:oS});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function fS(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=Gh(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let[i,n,r,a]=await Promise.all([Wh("comet.native.workspace-project-root.v2",t.paths.projectRoot),Wh("comet.native.workspace-native-root.v2",t.paths.nativeRoot),zh("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),zh("comet.native.workspace-native-root-path.v2",t.paths.nativeRoot)]),o=(t.now??new Date).toISOString();if(t.finish&&!t.binding)throw new Error("Native workspace finish requires a workspace binding");t.binding&&Yh(t.binding);let s={capturedAt:o,capturedRevision:t.revision,nativeRootRef:e,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...t.sessionId?{sessionHash:Mc("comet.native.workspace-session.v2",`${i}
|
|
159
|
+
${n}
|
|
160
|
+
${t.sessionId}`)}:{}},c=t.binding?{schema:"comet.native.workspace.v3",...s,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...s};return Aa(c),c}async function xa(t,e){let i=await uS(t,e);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Aa(i),i)}async function Xh(t){Aa(t.identity);let e=await fS({paths:t.paths,name:"workspace-advisory",revision:t.identity.capturedRevision}),i=[],n=[];return e.nativeRootRef!==t.identity.nativeRootRef&&i.push("native-root-ref"),t.identity.projectRootPathId&&t.identity.nativeRootPathId?(e.projectRootPathId!==t.identity.projectRootPathId&&i.push("project-root-path"),e.nativeRootPathId!==t.identity.nativeRootPathId&&i.push("native-root-path")):(e.projectRootId!==t.identity.projectRootId&&i.push("project-root-legacy-identity"),e.nativeRootId!==t.identity.nativeRootId&&i.push("native-root-legacy-identity")),Hc==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):i.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:i}}async function Qh(t){if(Aa(t.identity),t.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Xh(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Vh(t.paths.projectRoot);return t.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==t.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${t.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:t.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function Zh(t,e){let i=await xa(t,e);if(i===null)return null;let n=await Qh({paths:t,identity:i});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return i}var xt="comet.native.v3",Gt="comet.native.v2",Kt="comet.native.v1",yi="comet.native.transition.v3",Ni="comet.native.transition.v2",Pn="comet.native.transition.v1";var tp=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],dS=new Set(tp),ip=new Set([...tp,"minimum_runtime_version","revision"]),hS=new Set([...ip,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),pS=new Set(["capability","operation","source","base_hash"]),mS=new Set(["shape","build","verify","archive"]),vS=new Set(["implicit","confirmed"]),gS=new Set(["pending","pass","fail"]),Tt="comet-state.yaml",Bc=/^[a-f0-9]{64}$/u,np=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,wS=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,An=class extends Error{constructor(i,n){super(`Native change ${i} uses ${n}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Ut=class extends Error{constructor(i,n){super(i!==xt||n===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},xn=class extends Error{constructor(i,n,r){super(`Native change ${i} revision conflict: expected ${n}, actual ${r}`);this.change=i;this.expectedRevision=n;this.actualRevision=r;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Ta=class extends Error{constructor(i,n){super(`Native working directory already contains active change${n.length===1?"":"s"} ${n.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=n;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Ia=class extends Error{constructor(i,n,r,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${n} omitted entr${n===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=n;this.omittedByReason=r;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"},HI=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
161
|
+
`);function In(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function rp(t,e,i){let n=Object.keys(t).filter(r=>!e.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Dc(t){if(!np.test(t))throw new Error(`Invalid Native change name: ${t}`)}function yS(t){if(!np.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function ap(t,e){if(t.length===0||at.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function NS(t,e){let i=In(t,`spec_changes[${e}]`);if(rp(i,pS,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(yS(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let n=i.source,r=i.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof n=="string"&&ap(n,`Spec source for ${i.capability}`),i.operation==="create"){if(!n)throw new Error(`Create spec ${i.capability} requires source`);if(r!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!n)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof r!="string"||!Bc.test(r))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof r!="string"||!Bc.test(r))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof n=="string"?{source:n}:{},base_hash:r}}function bS(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function qc(t,e){if(rp(t,e,Tt),typeof t.name!="string")throw new Error("Native change name is required");if(Dc(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!mS.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!vS.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(NS),n=i.map(r=>r.capability).filter((r,a,o)=>o.indexOf(r)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof t.verification_result!="string"||!gS.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&ap(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!bS(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function _n(t){let e=In(t,Tt);if(e.schema!==Kt)throw new Error(`Expected ${Kt}`);return{schema:Kt,...qc(e,dS)}}function Tn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Lc(t,e,i){if(t===null)return null;let n=typeof t=="string"?wS.exec(t):null;if(!n||n[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return t}function kS(t){if(t==null)return null;if(typeof t!="string"||!Bc.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function SS(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function jn(t){let e=In(t,Tt);if(e.schema!==Gt)throw new Error(`Expected ${Gt}`);if(Tn(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Gt} minimum_runtime_version must be 2`);return{schema:Gt,minimum_runtime_version:2,revision:Tn(e.revision,"Native v2 revision"),...qc(e,ip)}}function ot(t){let e=In(t,Tt);if(e.schema!==xt){if(e.schema===Kt||e.schema===Gt){let o=e.schema===Kt?_n(e):jn(e);throw new An(o.name,o.schema)}throw new Ut(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Tn(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Ut(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=Tn(e.revision,"Native revision"),r=qc(e,hS),a=kS(e.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:xt,minimum_runtime_version:3,revision:n,verification_protocol:SS(e.verification_protocol),...r,approved_contract_hash:a,implementation_scope:Lc(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Lc(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Lc(e.partial_allowance,"Native partial_allowance","allowances")}}function ES(t){let e=In(t,Tt);if(e.schema===Kt){let r=_n(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${xt}`}}if(e.schema===Gt){let r=jn(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${xt}`}}if(e.schema!==xt){let r=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new Ut(typeof e.schema=="string"?e.schema:"(missing)",r).message}}let i=Tn(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Ut(e.schema,i).message};let n=ot(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function Fc(t){let e=ot(t);return{schema:e.schema,minimum_runtime_version:e.minimum_runtime_version,revision:e.revision,verification_protocol:e.verification_protocol,name:e.name,language:e.language,phase:e.phase,brief:e.brief,approval:e.approval,approved_contract_hash:e.approved_contract_hash??null,spec_changes:e.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:e.verification_result,verification_report:e.verification_report,implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Y(t,e){Dc(e);let i=at.join(t.changesDir,e);if(!se(t.changesDir,i))throw new Error("Native change path escaped");return i}async function On(t,e){let i=at.join(Y(t,e),"runtime","schema-migration.json");await q(t.nativeRoot,i);try{return await ep.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function op(t,e){let i=at.join(Y(t,e),"runtime","checkpoint-journal.json");await q(t.nativeRoot,i);try{return await ep.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var RS=256*1024;async function sp(t,e=at.dirname(t)){let i=at.relative(e,t).split(at.sep).join("/"),n=await Re({root:e,ref:i,maxBytes:RS}),r=(0,_a.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${r.errors[0].message}`);return r.toJS()}async function CS(t,e){let i=at.join(Y(t,e),Tt);await q(t.nativeRoot,i);let n=ES(await sp(i,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await On(t,e)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(n.status==="current"&&n.state&&await PS(t,n.state),n)}async function PS(t,e){if(await Oh(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function ke(t,e){let i=await CS(t,e);if(i.status==="migration-required")throw new An(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Ut(i.schema,i.minimumRuntimeVersion);return await Zh(t,e),i.state}async function AS(t,e,i){let n={...e,schema:xt,minimum_runtime_version:3,revision:i+1},r=await hh({expectedRevision:i,next:n,read:async()=>{let a=ot(await sp(t));if(a.name!==e.name)throw new Error(`Native change file/name mismatch: ${e.name}`);return a},write:a=>et(t,(0,_a.stringify)(Fc(a))),equals:(a,o)=>JSON.stringify(Fc(a))===JSON.stringify(Fc(o)),conflict:a=>new xn(e.name,i,a)});return Object.assign(e,r),r}async function ja(t,e,i,n){if(await vn(t.projectRoot),await On(t,e.name))throw new An(e.name,e.schema);if(!n?.allowPendingCheckpointRecovery&&await op(t,e.name))throw new Error(`Native progress checkpoint recovery is required for ${e.name} before another state write`);if((await ke(t,e.name)).verification_protocol!==e.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Ra(t,e.name);let a=at.join(Y(t,e.name),Tt);return await q(t.nativeRoot,a),AS(a,e,i)}import{promises as DE}from"fs";import $n from"path";var xS=/\b(Bearer|Basic)\s+[^\s"']+/giu,TS=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,IS=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,_S=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,jS=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,OS=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,$S=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function xe(t){return t.replace(xS,"$1 [REDACTED]").replace(TS,"[REDACTED PRIVATE KEY]").replace(IS,"$1[REDACTED]@").replace(_S,"[REDACTED TOKEN]").replace(jS,'$1"[REDACTED]"').replace(OS,"$1$2$1$3$4[REDACTED]$4").replace($S,"$1$2[REDACTED]")}var Oa={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},bi=/^[a-f0-9]{64}$/u;function $a(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Ha(t,e,i){let n=new Set(e),r=Object.keys(t).filter(o=>!n.has(o)),a=e.filter(o=>!(o in t));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function It(t,e,i=2e3){if(typeof t!="string"||t.length===0||t.length>i)throw new Error(`${e} must be a non-empty string of at most ${i} characters`);return t}function cp(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Vc(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function HS(t){let e=t.trim().replaceAll("\\","/");if(e.length===0||$n.isAbsolute(e)||/^(?:[A-Za-z]:|~|\/)/u.test(e)||e.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${t}`);let i=$n.posix.normalize(e);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${t}`);return i}function MS(t,e){return $n.join(Y(t,e),"runtime","checkpoints","progress.json")}function Wc(t,e){return $n.join(Y(t,e),"runtime","checkpoint-journal.json")}function lp(t,e,i){if(!bi.test(i))throw new Error("Native checkpoint manifest hash is invalid");return $n.join(Y(t,e),"runtime","checkpoints","manifests",`${i}.json`)}function LS(t){if(!bi.test(t))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${t}.json`}async function up(t,e,i){let n=await it({root:t,file:e,maxBytes:Oa.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function FS(t,e){let i=$a(t,`checkpoint manifest artifact ${e}`);Ha(i,["path","hash","size"],`checkpoint manifest artifact ${e}`);let n=HS(It(i.path,`checkpoint artifact ${e} path`,4096)),r=Je(n);if(r)throw new Error(`checkpoint artifact ${e} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!bi.test(i.hash))throw new Error(`checkpoint artifact ${e} hash is invalid`);return{path:n,hash:i.hash,size:Vc(i.size,`checkpoint artifact ${e} size`)}}function Ma(t,e){let i=$a(t,"Native checkpoint manifest");if(Ha(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==e)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>Oa.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(FS),r=[...n].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(n)!==JSON.stringify(r))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(n.map(o=>o.path)).size!==n.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Vc(i.totalBytes,"checkpoint manifest totalBytes");if(n.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Oa.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:e,artifacts:n,totalBytes:a}}function zc(t){return G(JSON.stringify(Ma(t,t.change)))}function fp(t,e){let i=$a(t,"Native progress checkpoint");if(Ha(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==e)throw new Error("Native checkpoint change mismatch");let n=i.phase;if(n!=="shape"&&n!=="build"&&n!=="verify"&&n!=="archive")throw new Error("Native checkpoint phase is invalid");let r=cp(i.previousRevision,"Native checkpoint previousRevision"),a=cp(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=It(i.manifestHash,"Native checkpoint manifestHash",64);if(!bi.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=LS(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=It(i.inputHash,"Native checkpoint inputHash",64);if(!bi.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=It(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Vc(i.artifactCount,"Native checkpoint artifactCount");if(u>Oa.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let f=It(i.summary,"Native checkpoint summary"),d=It(i.nextAction,"Native checkpoint nextAction");if(xe(f)!==f||xe(d)!==d)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:It(i.id,"Native checkpoint id",128),change:e,phase:n,previousRevision:r,stateRevision:a,summary:f,nextAction:d,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function BS(t,e){let i=$a(t,"Native checkpoint journal");if(Ha(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==e)throw new Error("Native checkpoint journal change mismatch");let n=ot(i.previousState),r=ot(i.nextState),a=fp(i.checkpoint,e),o=Ma(i.manifest,e),s=It(i.inputHash,"Native checkpoint journal inputHash",64),c=G(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!bi.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(n.name!==e||r.name!==e||r.revision!==n.revision+1||a.previousRevision!==n.revision||a.stateRevision!==r.revision||a.phase!==r.phase||a.manifestHash!==zc(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:e,inputHash:s,createdAt:a.createdAt,previousState:n,nextState:r,checkpoint:a,manifest:o}}async function dp(t,e,i){let n=lp(t,e,i);await q(t.nativeRoot,n);let r=await up(t.nativeRoot,n,"Native checkpoint manifest"),a=Ma(r,e);if(Jc(t,a),zc(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function hp(t,e){let i=Wc(t,e);await q(t.nativeRoot,i);try{let n=BS(await up(t.nativeRoot,i,"Native checkpoint journal"),e);return Jc(t,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function pp(t,e,i,n){let r=Ma(i,e);Jc(t,r);let a=zc(r),o=lp(t,e,a);await q(t.nativeRoot,o);try{let s=await dp(t,e,a);if(JSON.stringify(s)!==JSON.stringify(r))throw new Error("Native checkpoint manifest hash collision")}catch(s){if(s.code!=="ENOENT")throw s}return await Oe(o,r,{containedRoot:t.nativeRoot,beforeCommit:n?.beforeCommit}),a}function Jc(t,e){for(let i of e.artifacts){let n=Od(t,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function mp(t,e){let i=fp(e,e.change),n=await dp(t,i.change,i.manifestHash),r=G(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:n.artifacts}));if(i.inputHash!==r||i.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=MS(t,e.change);await q(t.nativeRoot,a),await Oe(a,i,{containedRoot:t.nativeRoot})}import{promises as RE}from"fs";import CE from"path";import{isDeepStrictEqual as pl}from"util";import{createHash as DS}from"crypto";function Fe(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function qS(t,e){e.has(t)&&Fe("cyclic structures are not supported"),e.add(t);try{let i=Object.keys(t);for(let n=0;n<t.length;n+=1)Object.prototype.hasOwnProperty.call(t,n)||Fe("sparse arrays are not supported");return(i.length!==t.length||i.some((n,r)=>n!==String(r)))&&Fe("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&Fe("symbol properties are not supported"),`[${t.map(n=>Gc(n,e)).join(",")}]`}finally{e.delete(t)}}function VS(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&Fe("only plain objects are supported"),e.has(t)&&Fe("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&Fe("symbol properties are not supported"),e.add(t);try{let n=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&Fe("accessor properties are not supported"),`${JSON.stringify(o)}:${Gc(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Gc(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||Fe("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?qS(t,e):VS(t,e);case"bigint":case"function":case"symbol":case"undefined":return Fe(`${typeof t} values are not supported`)}return Fe("unsupported value type")}function La(t){return Gc(t,new Set)}function W(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return DS("sha256").update(`${t}
|
|
162
|
+
${La(e)}`).digest("hex")}var Kc={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var WS=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function zS(t,e){return t<e?-1:t>e?1:0}function JS(t,e,i,n){if(!Array.isArray(t)||t.length>i||!n&&t.length===0)throw new Error(`${e} exceeds its count boundary`);let r=t.map(a=>{if(typeof a!="string"||!WS.test(a))throw new Error(`${e} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(zS)}function vp(t=[]){return JS(t,"Native repair failed check IDs",Kc.maxFailedCheckIds,!0)}import _p from"node:path";import{createHash as Sp}from"node:crypto";import gp from"path";var Uc="comet.native.implementation-scope.v2",Ep="comet.native.content-snapshot-projection.v1",Hn="comet.native.content-snapshot-projection.v1",Rp="comet.native.implementation-scope.v2",GS="comet.native.unresolved-scope-id.v1",KS="comet.native.scope-detail-overflow.v1",US="comet.native.snapshot-projection-overflow.v2",Zc=/^[a-f0-9]{64}$/u,Xt=1024*1024,YS=128,XS=128;function ce(t,e){return t<e?-1:t>e?1:0}function Yc(t){if(!Zc.test(t))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${t}.json`}function QS(t,e){return t===e?0:t===null?-1:e===null?1:ce(t,e)}function jt(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.endsWith("/")||/^[a-zA-Z]:/u.test(t))throw new Error(`${e} must be a normalized project-relative path`);let i=gp.posix.normalize(t);if(i!==t||i==="."||i===".."||i.startsWith("../")||gp.posix.isAbsolute(i))throw new Error(`${e} must stay inside the project root`);return t}function Cp(t,e){return t==="."?t:jt(t,e)}function ki(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative safe integer`);return t}function ZS(t,e){if(t.type!=="file")throw new Error(`${e} must describe a file`);if(typeof t.hash!="string"||t.hash.length===0)throw new Error(`${e} hash must be non-empty`);return{path:jt(t.path,`${e} path`),hash:t.hash,size:ki(t.size,`${e} size`),type:"file"}}function eE(t,e){return{path:Cp(t.path,`${e} path`),size:t.size===null?null:ki(t.size,`${e} size`),type:t.type,reason:t.reason}}function tE(t,e){return ce(t.path,e.path)||ce(t.hash,e.hash)||t.size-e.size}function iE(t,e){return ce(t.path,e.path)||ce(t.reason,e.reason)||ce(t.type,e.type)||(t.size??-1)-(e.size??-1)}function Mn(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
163
|
+
`,"utf8")}function _t(t,e,i){let n=`${e}
|
|
164
|
+
${La(i)}`;t.update(`${Buffer.byteLength(n,"utf8")}:`),t.update(n)}function nE(t){if(Mn(t)<=Xt)return t;let e=[...t.entries],i=[...t.omitted],n=t.omittedCount,r=t.omissionOverflow?.count??0,a=Sp("sha256");a.update(`${US}
|
|
165
|
+
`),t.omissionOverflow&&_t(a,"existing-overflow",t.omissionOverflow);let o=(d,p)=>{p||(n+=1),r+=1,_t(a,"omission",d)},s=d=>{n+=1,r+=1,_t(a,"entry",d)},c=()=>{for(let d=i.length-1;d>=0;d-=1){let p=i[d];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(d,1),p}return null},l=()=>({...t,complete:n===0,entries:e,omitted:i,omittedCount:n,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:r}}),u=l();for(;Mn(u)>Xt;){if(i.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(i.length/4));for(let m=0;m<p;m+=1){let h=c();if(h===null)break;o(h,!0)}}else if(e.length>0){let p=Math.max(1,Math.ceil(e.length/4));for(let m of e.splice(-p))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let f=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${f}`,hash:f,count:r}}}function Xc(t){let e=yn(t),i=e.entries.map((r,a)=>ZS(r,`Snapshot entry ${a}`));if(i.sort(tE),new Set(i.map(r=>r.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let n=e.omitted.map((r,a)=>eE(r,`Snapshot omission ${a}`));return n.sort(iE),nE({schema:Ep,origin:e.origin,...e.capture?{capture:e.capture}:{},complete:e.complete,limits:{maxFiles:e.limits.maxFiles,maxFileBytes:e.limits.maxFileBytes,maxTotalBytes:e.limits.maxTotalBytes,maxManifestBytes:e.limits.maxManifestBytes,...e.limits.maxDurationMs===void 0?{}:{maxDurationMs:e.limits.maxDurationMs}},...e.policy?{policy:e.policy}:{},entries:i,omitted:n,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:{ref:e.omissionOverflow.ref,hash:e.omissionOverflow.hash,count:e.omissionOverflow.count}}:{}})}function Da(t){let e=new Map;for(let[i,n]of t.entries()){if(n.kind!=="file"&&n.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let r={path:jt(n.path,`Declared artifact ${i} path`),kind:n.kind},a=e.get(r.path);if(a&&a.kind!==r.kind)throw new Error(`Declared artifact path has conflicting kinds: ${r.path}`);e.set(r.path,r)}return[...e.values()].sort((i,n)=>ce(i.path,n.path)||ce(i.kind,n.kind))}function qa(t,e){return t.kind==="file"?t.path===e:e===t.path||e.startsWith(`${t.path}/`)}function wp(t){return t?{hash:t.hash,size:t.size}:null}function Pp(t,e,i){let n=0,r=0;for(;n<t.entries.length||r<e.entries.length;){let a=t.entries[n],o=e.entries[r],s=a===void 0?1:o===void 0?-1:ce(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(n+=1),s>=0&&(r+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!e.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:wp(c),after:wp(l)})}}function rE(t,e){return{...t,attributedTo:e.filter(i=>qa(i,t.path))}}function st(t,e){return{id:`scope:${W(GS,t)}`,kind:t.kind,source:t.source,path:t.path,reason:e}}function aE(t,e){let i=e.omitted.map(n=>st({kind:"snapshot-omission",source:t,path:n.path,evidence:{reason:n.reason,size:n.size,type:n.type}},`${t} snapshot omitted ${n.path}: ${n.reason}`));return e.complete||i.push(st({kind:"snapshot-incomplete",source:t,path:null,evidence:{omittedCount:e.omittedCount}},`${t} snapshot is incomplete`)),e.omissionOverflow&&i.push(st({kind:"snapshot-omission-overflow",source:t,path:null,evidence:{count:e.omissionOverflow.count,hash:e.omissionOverflow.hash,ref:e.omissionOverflow.ref}},`${t} snapshot has ${e.omissionOverflow.count} unlisted omissions`)),i}function yp(t,e){return aE(t,{...e,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Qc(t,e){return ce(t.kind,e.kind)||ce(t.source,e.source)||QS(t.path,e.path)||ce(t.id,e.id)}function oE(t){return[...new Map(t.map(i=>[i.id,i])).values()].sort(Qc)}function sE(t){return[...new Set(t.map((e,i)=>jt(e,`Git path ${i}`)))].sort(ce)}function Ap(t){if(typeof t.contractHash!="string"||!Zc.test(t.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:t.contractHash,declaredArtifacts:Da(t.declaredArtifacts),noCodeReason:t.noCodeReason?.trim()||null,...t.gitChangedPaths===void 0?{}:{gitChangedPaths:sE(t.gitChangedPaths)}}}function cE(t,e,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,u=0;return Pp(t,e,f=>{let d=i.some(p=>qa(p,f.path));if(l+=1,d||(u+=1),a?.has(f.path)&&o.push(f.path),!c&&r.length<YS){let p=rE(f,i),m=Mn(p);s+m<=Xt?(r.push(p),s+=m):c=!0}}),{candidates:r,gitPathsPresentInChanges:o,totalChanges:l,totalUnattributed:u}}function xp(t,e){return st({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:e.changes,hash:t,unattributedCount:e.unattributed,unresolvedCount:e.unresolved}},`Implementation scope summarized ${e.changes} additional change details and ${e.unresolved} unresolved details (${e.unattributed} unattributed); overflow hash ${t}`)}function lE(t){let e=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(t.reason);if(!e)throw new Error("Implementation scope detail overflow is invalid");let i={changes:ki(Number(e[1]),"Scope overflow change count"),unresolved:ki(Number(e[2]),"Scope overflow unresolved count"),unattributed:ki(Number(e[3]),"Scope overflow unattributed count")},n=Yt(e[4],"Scope detail overflow hash");if(JSON.stringify(t)!==JSON.stringify(xp(n,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:n}}function uE(t){let e=Sp("sha256");e.update(`${KS}
|
|
166
|
+
`);let i=0;Pp(t.baseline,t.current,r=>{if(i>=t.detailedChangeCount){_t(e,"change",r);let a=0;for(let o of t.declaredArtifacts)qa(o,r.path)&&(a+=1,_t(e,"change-attribution",o));_t(e,"change-end",{attributionCount:a}),a===0&&_t(e,"unattributed-change",{after:r.after,before:r.before,changeKind:r.kind,path:r.path})}i+=1});let n=0;for(let[r,a]of[["baseline",t.baseline],["current",t.current]])for(let o of a.omitted)n>=t.detailedOmissionCount&&_t(e,"snapshot-omission",{source:r,...o}),n+=1;return e.digest("hex")}function Tp(t,e,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=cE(t,e,r,i.gitChangedPaths),s=W(Hn,t),c=W(Hn,e),l=[];for(let[g,y]of[["baseline",t],["current",e]])for(let w of y.omitted){if(l.length>=XS)break;l.push(st({kind:"snapshot-omission",source:g,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${g} snapshot omitted ${w.path}: ${w.reason}`))}let u=t.omitted.length+e.omitted.length,f=[...yp("baseline",t),...yp("current",e),...o.totalChanges===0&&a===null?[st({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],d=()=>{if(i.gitChangedPaths===void 0)return;let g=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(y=>g.has(y)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(y=>!g.has(y))}},p=g=>{let y=o.candidates.slice(0,g.detailedChangeCount),w=y.filter(Ve=>Ve.attributedTo.length===0),R=o.totalChanges-y.length,_=o.totalUnattributed-w.length,D=u-g.detailedOmissionCount,H=_+D,F=[...w.map(Ve=>st({kind:"unattributed-change",source:"implementation-scope",path:Ve.path,evidence:{after:Ve.after,before:Ve.before,changeKind:Ve.kind}},`Changed path is not covered by a declared artifact: ${Ve.path}`)),...l.slice(0,g.detailedOmissionCount),...f,...R>0||H>0?[xp(g.overflowHash,{changes:R,unattributed:_,unresolved:H})]:[]],z=oE(F),qe=g.includeGitAdvisory?d():void 0;return{schema:Uc,contractHash:n,baselineProjectionRef:Yc(s),baselineProjectionHash:s,currentProjectionRef:Yc(c),currentProjectionHash:c,complete:z.length===0,declaredArtifacts:r,changes:y,unattributed:w,unresolvedScopes:z,noCodeReason:a,...qe?{gitAdvisory:qe}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,S="0".repeat(64);for(;;){let g=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:S});if(Mn({...g,scopeHash:S})<=Xt)break;if(v){v=!1;continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let E=o.totalChanges>m||u>h?uE({baseline:t,current:e,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):S,b=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:E}),k={...b,scopeHash:W(Rp,b)};if(Mn(k)>Xt)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return k}function el(t){let e=Xc(t.baseline),i=Xc(t.current),n=Ap(t);return{authority:n,baseline:e,current:i,scope:Tp(e,i,n)}}var fE=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function ct(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function lt(t,e,i,n){let r=new Set([...e,...i]),a=Object.keys(t).filter(s=>!r.has(s)),o=e.filter(s=>!(s in t));if(a.length>0)throw new Error(`${n} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${n} is missing field(s): ${o.join(", ")}`)}function Yt(t,e){if(typeof t!="string"||!Zc.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function Np(t,e,i){let n=Yc(e);if(t!==n)throw new Error(`${i} ref/hash mismatch`);return n}function Ba(t,e){let i=ct(t,"Native snapshot projection");if(lt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Ep)throw new Error("Native snapshot projection schema is invalid");let n=yn({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),r=Xc(n);if(W(Hn,i)!==W(Hn,r))throw new Error("Native snapshot projection is not canonical");let a=W(Hn,r);if(e!==void 0&&Yt(e,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function tl(t,e){let i=ct(t,`Declared artifact ${e}`);if(lt(i,["path","kind"],[],`Declared artifact ${e}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${e} kind is invalid`);return{path:jt(i.path,`Declared artifact ${e} path`),kind:i.kind}}function bp(t,e){if(t===null)return null;let i=ct(t,e);return lt(i,["hash","size"],[],e),{hash:Yt(i.hash,`${e} hash`),size:ki(i.size,`${e} size`)}}function kp(t,e){let i=ct(t,`Implementation change ${e}`);if(lt(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${e}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${e} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${e} attributedTo must be an array`);let n=i.attributedTo.map(tl),r=Da(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${e} attribution must be sorted and unique`);let a=bp(i.before,`Implementation change ${e} before`),o=bp(i.after,`Implementation change ${e} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${e} before/after state is invalid`);return{path:jt(i.path,`Implementation change ${e} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function dE(t,e){let i=ct(t,`Unresolved scope ${e}`);lt(i,["id","kind","source","path","reason"],[],`Unresolved scope ${e}`);let n=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!n.has(i.kind))throw new Error(`Unresolved scope ${e} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${e} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${e} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${e} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${e} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Cp(i.path,`Unresolved scope ${e} path`):jt(i.path,`Unresolved scope ${e} path`),reason:i.reason}}function Fa(t,e){if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error(`${e} must be an array of paths`);let i=t.map((r,a)=>jt(r,`${e} ${a}`)),n=[...new Set(i)].sort(ce);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${e} must be sorted and unique`);return i}function Va(t){let e=ct(t,"Native implementation scope"),i=[...fE].filter(y=>y!=="gitAdvisory");if(lt(e,i,["gitAdvisory"],"Native implementation scope"),e.schema!==Uc)throw new Error("Native implementation scope schema is invalid");let n=Yt(e.contractHash,"Implementation scope contractHash"),r=Yt(e.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Np(e.baselineProjectionRef,r,"Implementation scope baseline projection"),o=Yt(e.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Np(e.currentProjectionRef,o,"Implementation scope current projection");if(typeof e.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(e.declaredArtifacts)||!Array.isArray(e.changes)||!Array.isArray(e.unattributed)||!Array.isArray(e.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=e.declaredArtifacts.map(tl);if(JSON.stringify(c)!==JSON.stringify(Da(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=e.changes.map(kp),u=[...l].sort((y,w)=>ce(y.path,w.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let f=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(w=>!f.has(`${w.kind}:${w.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(w=>qa(w,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=e.unattributed.map(kp),p=l.filter(y=>y.attributedTo.length===0);if(JSON.stringify(d)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=e.unresolvedScopes.map(dE),h=m.filter(y=>y.kind==="scope-detail-overflow");if(h.length>1)throw new Error("Implementation scope has multiple detail overflow records");let v=h[0]===void 0?null:lE(h[0]);if(v&&(v.changes+v.unresolved===0||v.unattributed>v.changes||v.unattributed>v.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=e.noCodeReason,N=[...p.map(y=>st({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(v?.changes??0)===0&&S===null?[st({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:r,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=m.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Qc))||new Set(m.map(y=>y.id)).size!==m.length||JSON.stringify(E)!==JSON.stringify(N.sort(Qc))||e.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(e.noCodeReason!==null&&(typeof e.noCodeReason!="string"||e.noCodeReason.length===0||e.noCodeReason.trim()!==e.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(e.gitAdvisory!==void 0){let y=ct(e.gitAdvisory,"Implementation scope Git advisory");if(lt(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let w=Fa(y.changedPaths,"Git changed paths"),R=Fa(y.pathsPresentInSnapshotChanges,"Git present paths"),_=Fa(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),D=[...R,..._].sort(ce),H=new Set(l.map(F=>F.path));if(JSON.stringify(D)!==JSON.stringify(w)||(v?.changes??0)===0&&R.some(F=>!H.has(F))||_.some(F=>H.has(F)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:w,pathsPresentInSnapshotChanges:R,pathsAbsentFromSnapshotChanges:_}}let k={schema:Uc,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:e.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:m,noCodeReason:S,...b?{gitAdvisory:b}:{}},g=Yt(e.scopeHash,"Implementation scope scopeHash");if(W(Rp,k)!==g)throw new Error("Implementation scope content hash mismatch");return{...k,scopeHash:g}}function hE(t){let e=ct(t,"Native implementation scope authority");if(lt(e,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths"],"Native implementation scope authority"),!Array.isArray(e.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=e.declaredArtifacts.map(tl);if(JSON.stringify(i)!==JSON.stringify(Da(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(e.noCodeReason!==null&&(typeof e.noCodeReason!="string"||e.noCodeReason.length===0||e.noCodeReason.trim()!==e.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let n;e.gitChangedPaths!==void 0&&(n=Fa(e.gitChangedPaths,"Native implementation scope authority Git paths"));let r=Ap({contractHash:e.contractHash,declaredArtifacts:i,noCodeReason:e.noCodeReason,...n===void 0?{}:{gitChangedPaths:n}});if(r.contractHash!==e.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return r}function Wa(t){let e=ct(t,"Native implementation scope bundle");lt(e,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=hE(e.authority),n=Ba(e.baseline),r=Ba(e.current),a=Va(e.scope),o=Tp(n,r,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:n,current:r,scope:o}}function Ip(t){let e=Va(t.scope);return Wa({authority:{contractHash:e.contractHash,declaredArtifacts:e.declaredArtifacts,noCodeReason:e.noCodeReason,...e.gitAdvisory?{gitChangedPaths:e.gitAdvisory.changedPaths}:{}},baseline:t.baseline,current:t.current,scope:e})}var Op=/^[a-f0-9]{64}$/u;var pE="comet.native.acceptance-trace.v2",mE="comet.native.partial-allowance.v1",vE="comet.native.verification-evidence.v2";function ut(t,e){if(!Op.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function $p(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native evidence source revision must be a positive integer");return t}function Hp(t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native evidence change name: ${t}`);return t}function il(t,e,i=2e3){let n=xe(t).trim();if(n.length===0||n.length>i)throw new Error(`${e} must be between 1 and ${i} characters`);return n}function Ln(t,e){let i=_p.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||_p.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||i!==t||i==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized relative ref`);return t}function gE(t,e,i){let n=Ln(t,e);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=Je(n),a=n.toLowerCase(),o=i?Ln(i,"Native root ref").toLowerCase():null;if(r||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${e} is excluded as sensitive (${r??"native-runtime"}): ${n}`);return n}function nl(t){let e=Ln(t,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(e))throw new Error("Verification receipt ref must identify a typed v3 receipt");return e}function Si(t,e){return t<e?-1:t>e?1:0}function za(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Ja(t,e,i){let n=new Set(e),r=Object.keys(t).filter(o=>!n.has(o)),a=e.filter(o=>!(o in t));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Mp(t,e){if(typeof t!="string")throw new Error(`${e} is invalid`);let i=new Date(t);if(Number.isNaN(i.valueOf())||i.toISOString()!==t)throw new Error(`${e} is invalid`);return t}function jp(t,e,i){if(typeof t!="string")throw new Error(`Native ${e} evidence ref is invalid`);let n=`runtime/evidence/${e}/${i}.json`;if(t!==n)throw new Error(`Native ${e} evidence ref/hash mismatch`);return t}function wE(t){let e=za(t,"Native acceptance trace");if(Ja(e,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),e.schema!=="comet.native.acceptance-trace.v2"||typeof e.nativeRootRef!="string"||typeof e.criteriaHash!="string"||!Op.test(e.criteriaHash)||!Number.isSafeInteger(e.total)||!Number.isSafeInteger(e.evidenced)||!Number.isSafeInteger(e.skipped)||!Array.isArray(e.entries))throw new Error("Native acceptance trace is invalid");let i=Ln(e.nativeRootRef,"Native root ref"),n=e.entries.map((o,s)=>{let c=za(o,`Native acceptance trace entry ${s}`);if(Ja(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(f=>typeof f!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(f=>nl(f)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Si))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Ln(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:il(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>Si(o.acceptanceId,s.acceptanceId)))||new Set(n.map(o=>o.acceptanceId)).size!==n.length||e.total!==n.length||e.evidenced!==n.filter(o=>o.evidenceRefs.length>0).length||e.skipped!==n.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let r={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:e.criteriaHash,total:e.total,evidenced:e.evidenced,skipped:e.skipped,entries:n},a=ut(e.traceHash,"Native acceptance trace hash");if(W(pE,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function Lp(t){let e=za(t,"Native partial allowance");if(Ja(e,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),e.schema!=="comet.native.partial-allowance.v1"||typeof e.change!="string"||typeof e.scopeHash!="string"||!Array.isArray(e.scopeIds)||e.scopeIds.length===0||e.scopeIds.some(r=>typeof r!="string"||!/^scope:[a-f0-9]{64}$/u.test(r))||JSON.stringify(e.scopeIds)!==JSON.stringify([...new Set(e.scopeIds)].sort(Si))||typeof e.reason!="string"||typeof e.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:Hp(e.change),scopeHash:ut(e.scopeHash,"Native partial allowance scopeHash"),scopeIds:e.scopeIds,reason:il(e.reason,"Partial allowance reason"),confirmedSummary:il(e.confirmedSummary,"Partial allowance confirmation"),sourceRevision:$p(e.sourceRevision),confirmedAt:Mp(e.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==e.reason||i.confirmedSummary!==e.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let n=ut(e.allowanceHash,"Native partial allowance hash");if(W(mE,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function rl(t){let e=za(t,"Native verification evidence");if(Ja(e,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),e.schema!=="comet.native.verification-evidence.v2"||typeof e.change!="string"||e.result!=="pass"&&e.result!=="fail"||e.freshness!=="complete"&&e.freshness!=="partial"||typeof e.implementationScopeHash!="string"||typeof e.reportRef!="string"||!Array.isArray(e.requiredReceiptRefs)||!Array.isArray(e.receiptRefs))throw new Error("Native verification evidence is invalid");let i=ut(e.implementationScopeHash,"Native verification implementation scope hash"),n=wE(e.acceptanceTrace),r=ut(e.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(n.criteriaHash!==r)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=e.partialAllowanceRef!==null||e.partialAllowanceHash!==null;if(e.partialAllowanceRef===null!=(e.partialAllowanceHash===null)||e.freshness==="complete"&&a||e.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=e.partialAllowanceHash===null?null:ut(e.partialAllowanceHash,"Native verification allowance hash"),s=e.receiptRefs.map(d=>nl(d));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Si)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(d=>d.evidenceRefs))].sort(Si);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=e.requiredReceiptRefs.map(d=>nl(d));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Si)))throw new Error("Native required receipt refs must be canonical");if(e.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:Hp(e.change),sourceRevision:$p(e.sourceRevision),result:e.result,freshness:e.freshness,contractHash:ut(e.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:jp(e.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:gE(e.reportRef,"Native verification report ref"),reportHash:ut(e.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:jp(e.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Mp(e.createdAt,"Native verification timestamp")},f=ut(e.envelopeHash,"Native verification envelope hash");if(W(vE,u)!==f)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:f}}function al(t,e){if(typeof t!="string"||t.trim().length===0||t.length>4096)throw new Error(`${e} must be between 1 and 4096 characters`)}var yE=/^[a-f0-9]{64}$/u;var Fp=["disposition","overrideSummaryHash","signatureHash"],NE=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"];function sl(t,e){return t<e?-1:t>e?1:0}function bE(t,e,i){let n=Object.keys(t).sort(sl);if(n.length!==e.length||n.some((r,a)=>r!==e[a]))throw new Error(`${i} fields are invalid`)}function kE(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new Error(`${e} must be a plain object`);return t}function ol(t,e){if(typeof t!="string"||!yE.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function SE(t){if(!Array.isArray(t)||t.length>Kc.maxFailedAcceptanceIds||t.some(e=>typeof e!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(e)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(t)].sort(sl)}function Bp(t){let e=kE(t,"Native repair trajectory projection"),i=Object.keys(e).sort(sl),n=i.length===Fp.length&&i.every((l,u)=>l===Fp[u]);n||bE(e,NE,"Native repair trajectory projection");let r=ol(e.signatureHash,"Native repair trajectory signature hash");if(e.disposition!=="continue"&&e.disposition!=="warn"&&e.disposition!=="manual-stop"&&e.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=e.overrideSummaryHash===null?null:ol(e.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&e.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(n)return{signatureHash:r,disposition:e.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=ol(e.contractHash,"Native repair trajectory contract hash"),s=SE(e.failedAcceptanceIds),c=vp(e.failedCheckIds);if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:r,disposition:e.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:e.maxVerifyFailures}}var Ei={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:[]},cl=G("comet-native-runtime:v3:semantic-repair-budget"),EE=[{skillVersion:"2",skillHash:G("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:G("comet-native-runtime:v1")}];function Dp(t){return t.skillVersion===Ei.definition.metadata.version&&t.skillHash===cl||EE.some(e=>e.skillVersion===t.skillVersion&&e.skillHash===t.skillHash)}async function Ga(t){let i={sequence:(await wi(t.changeDir,t.run.trajectoryRef)).length+1,timestamp:(t.now??new Date).toISOString(),type:t.type,runId:t.run.runId,data:t.data};return await Dh(t.changeDir,t.run.trajectoryRef,i),i}async function ll(t){let e={runId:t.run.runId,stateVersion:t.run.iteration,trajectoryOffset:t.trajectoryOffset,contextHash:null,artifactsHash:G(t.evidenceHash),createdAt:(t.now??new Date).toISOString()};return await qh(t.changeDir,t.run.checkpointRef,e),e}function qp(t){return G(JSON.stringify({summary:t.summary,confirmed:t.confirmed??!1,artifacts:[...t.artifacts??[]].sort(),noCodeReason:t.noCodeReason??null,verificationResult:t.verificationResult??null,verificationReport:t.verificationReport??null,allowPartialScopeHash:t.allowPartialScopeHash??null,partialReason:t.partialReason??null,repairOverrideSignature:t.repairOverrideSignature??null,repairOverrideSummary:t.repairOverrideSummary??null}))}var Yp=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],PE=new Set(Yp),Xp=new Set([...Yp,"minimum_runtime_version","revision"]),AE=new Set([...Xp,"operation"]),xE=512*1024,fl=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),TE=new Set([...fl,"implementationScopeHash","repairScopeHash","repairStagnation"]),dl=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function ml(t,e){return CE.join(Y(t,e),"runtime","transition.json")}function IE(t){return`transition-${t}`}async function _E(t,e,i){let n=IE(e);return gn(t,n,i)}async function Ua(t,e,i,n){let r=await _E(t,e,i);try{return await n()}finally{await wn(r)}}function Ya(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native transition journal must be an object");return t}function vl(t,e){let i=Object.keys(t).find(n=>!e.has(n));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Ka(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ue(t,e){return pl(t,e)}function hl(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native transition journal event data is invalid");let i=t,n=Object.keys(i),r=n.find(u=>!TE.has(u)),a=[...fl].find(u=>!Object.hasOwn(i,u)),o=fl.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0);if(r||a||n.length!==o)throw new Error(`Native transition journal event data keys are invalid${r?`: ${r}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==e)throw new Error("Native transition journal event evidence hash mismatch");if(al(i.summary,"Native transition journal event summary"),xe(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(al(i.noCodeReason,"Native transition journal event no-code reason"),xe(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Bp(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:e,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function jE(t,e){if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,n=Object.keys(i),r=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(n.length===r.size&&n.every(a=>r.has(a))&&i.reason==="spec-rebase")return hl({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},e)}return hl(t,e)}function gl(t,e,i=!1){if(t.change!==e)throw new Error("Native transition journal change mismatch");if(typeof t.id!="string"||t.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof t.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(t.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native transition journal timestamp is invalid");let n=i?jE(t.eventData,t.evidenceHash):hl(t.eventData,t.evidenceHash),r=Tc(t.nextRun),a=t.previousRun===null?null:Tc(t.previousRun);return{id:t.id,evidenceHash:t.evidenceHash,createdAt:t.createdAt,previousRun:a,nextRun:r,eventData:n}}function Vp(t,e,i=!1){if(t.skill!==Ei.definition.metadata.name||(i?!Dp(t):t.skillVersion!==Ei.definition.metadata.version||t.skillHash!==cl)||t.orchestration!==Ei.definition.orchestration.mode||t.pendingRef!==Ke.pendingRef||t.trajectoryRef!==Ke.trajectoryRef||t.contextRef!==Ke.contextRef||t.artifactsRef!==Ke.artifactsRef||t.checkpointRef!==Ke.checkpointRef)throw new Error(`Native transition journal ${e} metadata or storage refs are invalid`)}function Wp(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,retries:t.retries}}function zp(t,e){if(t.status!=="running")throw new Error(`Native transition journal ${e} status must be running`);if(t.pending!==null)throw new Error(`Native transition journal ${e} pending action must be null`)}function wl(t,e,i,n=!1){let{previousRun:r,nextRun:a}=i;if(Vp(a,"next Run",n||r!==null),zp(a,"next Run"),a.runId!==e.run_id||a.currentStep!==e.phase)throw new Error("Native transition journal next Run does not match the next change state");if(r===null){if(t.run_id!==null||t.phase!=="shape"||a.iteration!==1||Object.keys(a.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Vp(r,"previous Run",!0),zp(r,"previous Run"),t.run_id!==r.runId||r.currentStep!==t.phase||e.run_id!==r.runId)throw new Error("Native transition journal previous Run does not match the change state");if(a.iteration!==r.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!pl(Wp(r),Wp(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function OE(t,e,i){return G(JSON.stringify({operation:"spec-rebase",change:t,summary:e,specChanges:i}))}function Qp(t,e,i){return t.phase!=="shape"&&e.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Jp(t){return"implementation_scope"in t?{implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance}:null}function yl(t,e,i,n,r=!1){let a=i.eventData,o=Jp(t),s=Jp(e);if(a.previousPhase!==t.phase||a.nextPhase!==e.phase)throw new Error("Native transition journal event phases do not match its states");if(t.archived||e.archived)throw new Error("Native transition journal cannot mutate an archived change");if(n==="evidence-retreat"){let c=t.name===e.name&&t.language===e.language&&t.brief===e.brief&&t.approval===e.approval&&("approved_contract_hash"in t?"approved_contract_hash"in e&&t.approved_contract_hash===e.approved_contract_hash:!("approved_contract_hash"in e))&&t.created_at===e.created_at&&t.run_id===e.run_id&&pl(t.spec_changes,e.spec_changes),l=qp({summary:a.summary});if(!(t.phase==="archive"&&t.verification_result==="pass"||t.phase==="verify"&&t.verification_result==="pending")||e.phase!=="build"||e.verification_result!=="pending"||e.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(n==="spec-rebase"){let c=OE(t.name,a.summary,e.spec_changes),l=G(`spec-rebase:${t.name}:${a.summary}`);if(t.phase==="shape"||e.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||e.verification_report!==null||!r&&i.evidenceHash!==c||r&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in e&&(e.implementation_scope!==null||e.verification_evidence!==null||e.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(t.phase==="shape"){if(e.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||e.verification_result!=="pending"||t.verification_report!==null||e.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(t.phase==="build"){if(e.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||e.verification_result!=="pending"||e.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(t.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||e.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!==a.verificationResult||e.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function $E(t,e){let i=Ya(t);if(vl(i,AE),i.schema!==yi)throw new Error(`Expected Native transition schema ${yi}`);let n=Ka(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(n>3)throw new Error(`Native transition requires runtime protocol ${n}; current protocol is ${3}`);if(n!==3)throw new Error(`Native transition ${yi} minimum_runtime_version must be ${3}`);let r=Ka(i.revision,"Native transition revision");if(r!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat")throw new Error("Native transition journal operation is invalid");let a=gl(i,e),o=ot(i.previousState),s=ot(i.nextState);if(o.name!==e||s.name!==e)throw new Error("Native transition journal state mismatch");if(yl(o,s,a,i.operation),wl(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:yi,minimum_runtime_version:3,revision:r,operation:i.operation,id:a.id,change:e,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function HE(t,e){let i=Ya(t);if(vl(i,PE),i.schema!==Pn)throw new Error(`Expected Native transition schema ${Pn}`);let n=gl(i,e,!0),r=_n(i.previousState),a=_n(i.nextState);if(r.name!==e||a.name!==e)throw new Error("Native transition journal state mismatch");return yl(r,a,n,Qp(r,a,n.eventData),!0),wl(r,a,n,!0),{schema:Pn,id:n.id,change:e,evidenceHash:n.evidenceHash,createdAt:n.createdAt,previousState:r,nextState:a,previousRun:n.previousRun,nextRun:n.nextRun,eventData:n.eventData}}function ME(t,e){let i=Ya(t);if(vl(i,Xp),i.schema!==Ni)throw new Error(`Expected Native transition schema ${Ni}`);if(Ka(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Ni} minimum_runtime_version must be 2`);let r=Ka(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=gl(i,e,!0),o=jn(i.previousState),s=jn(i.nextState);if(o.name!==e||s.name!==e)throw new Error("Native v2 transition journal state mismatch");if(yl(o,s,a,Qp(o,s,a.eventData),!0),wl(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Ni,minimum_runtime_version:2,revision:r,id:a.id,change:e,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function LE(t,e){let i=Ya(t);if(i.schema===yi)return{status:"current",journal:$E(i,e)};if(i.schema===Pn)return{status:"migration-required",journal:HE(i,e)};if(i.schema===Ni)return{status:"migration-required",journal:ME(i,e)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function FE(t,e){let i=ml(t,e);await q(t.nativeRoot,i);try{let n=await it({root:t.nativeRoot,file:i,maxBytes:xE,label:`Native transition journal ${e}`});return LE(JSON.parse(n.bytes.toString("utf8")),e)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ul(t,e){let i=await FE(t,e);if(!i)return null;if(i.status==="migration-required")throw new dl(e);return i.journal}function Gp(t,e){if(Ue(t,e.nextRun))return"next";if(e.previousRun===null){if(t===null)return"previous"}else if(Ue(t,e.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${e.change}; recovery journal was preserved`)}function Kp(t,e){if(Ue(t,e.nextState))return"next";if(Ue(t,e.previousState))return"previous";throw new Error(`Native transition change content changed for ${e.change}; recovery journal was preserved`)}function BE(t){let{journal:e}=t;return Zp({sequence:t.sequence,timestamp:e.createdAt,type:t.type,runId:e.nextRun.runId,data:t.type==="run_started"?{runtime:"comet-native",phase:e.previousState.phase,transitionId:e.id}:{...e.eventData,transitionId:e.id}})}function Zp(t){return{sequence:t.sequence,timestamp:t.timestamp,type:t.type,runId:t.runId,data:t.data}}function Up(t,e){let i=t.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===e.id),n=i.filter(({event:a})=>a.type==="run_started"),r=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==n.length+r.length||n.length>(e.previousRun===null?1:0)||r.length>1||e.previousRun===null&&r.length===1&&(n.length!==1||n[0].index>=r[0].index))throw new Error(`Native trajectory transition id collision for ${e.change}; recovery journal was preserved`);for(let a of[...n,...r]){let o=BE({sequence:a.index+1,journal:e,type:a.event.type});if(!Ue(Zp(a.event),o))throw new Error(`Native trajectory event changed for transition ${e.id}; recovery journal was preserved`)}return{started:n[0]?.event??null,transitioned:r[0]?.event??null}}async function Nl(t,e,i){if(await On(t,e))throw new Error(`Native schema migration is incomplete for ${e}; run doctor --repair`);await Ra(t,e);let n=await ul(t,e);if(!n)return null;let r=Y(t,e),a=Up(await wi(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([Rn(r),ke(t,e)]),c=Gp(o,n),l=Kp(s,n);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${n.change}; recovery journal was preserved`);if(c==="previous"&&(await Ic(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!Ue(await Rn(r),n.nextRun))throw new Error(`Native transition Run content changed while continuing ${n.change}; recovery journal was preserved`);if(l==="previous"){let v=await ja(t,n.nextState,n.previousState.revision);if(!Ue(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!Ue(await ke(t,e),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await ul(t,e);if(!u||!Ue(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let f=Up(await wi(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(f.started||await Ga({changeDir:r,run:n.nextRun,type:"run_started",data:{runtime:"comet-native",phase:n.previousState.phase,transitionId:n.id},now:new Date(n.createdAt)}));let d=f.transitioned;d||(d=await Ga({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await ll({changeDir:r,run:n.nextRun,trajectoryOffset:d.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([Rn(r),ke(t,e)]);Gp(p,{...n,previousRun:n.nextRun}),Kp(m,{...n,previousState:n.nextState});let h=await ul(t,e);if(!h||!Ue(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await RE.rm(ml(t,e),{force:!0}),n.nextState}async function em(t,e,i){let n=await hp(t,e);if(!n)return null;if(await pp(t,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await ja(t,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await mp(t,n.checkpoint),await i?.afterProgressWritten?.(n),await DE.rm(Wc(t,e),{force:!0}),n}async function bl(t,e){await Nl(t,e),await em(t,e)}var Xa="scoped-text-safety",qE=1,VE=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var WE="comet.native.checker-policy.v1";var sj=W(WE,{policy:Xa,version:qE,limits:VE,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var zE=["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"],cj=new Set(zE);var vj=512*1024;import lm from"node:path";import tm from"node:path";var JE="comet.native.acceptance.v1",GE=/^acceptance-[a-f0-9]{64}$/u,KE=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),UE=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u;var Nj=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Bn=Object.freeze({maxCriteria:1024}),Fn="<!-- comet-native:acceptance-evidence:start -->",Ri="<!-- comet-native:acceptance-evidence:end -->";function El(t){let e=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(t);return e?{level:e[1].length,text:e[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function kl(t,e){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(t);if(!i)return e;let n=i[1][0];return e===null?{marker:n,length:i[1].length}:n===e.marker&&i[1].length>=e.length&&i[2].trim().length===0?null:e}function im(t){return t.includes("-->")||t.includes("--!>")}function*Ci(t){let e=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=t.replace(/\r\n?/gu,`
|
|
161
167
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
162
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:e===null&&!i&&n===null,index:s},s+=1,e!==null)e=
|
|
163
|
-
`))),"Brief")}function
|
|
164
|
-
`),a.context)),a=null}};for(let{line:s,body:c}of
|
|
165
|
-
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=
|
|
166
|
-
`)}var
|
|
167
|
-
`))}function bE(t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.capability))throw new Error(`Invalid Native contract capability: ${t.capability}`);if(t.operation!=="create"&&t.operation!=="replace"&&t.operation!=="remove")throw new Error(`Invalid Native contract operation for ${t.capability}`);if(t.operation==="remove"){if(t.source!==null||t.markdown!==null||!t.baseHash?.match(Fp))throw new Error(`Remove contract ${t.capability} requires only a base hash`);return{snapshot:{capability:t.capability,operation:"remove",source:null,baseHash:t.baseHash,contentHash:null},markdown:null}}if(t.source===null||t.markdown===null)throw new Error(`${t.operation} contract ${t.capability} requires source content`);if(t.operation==="create"&&t.baseHash!==null)throw new Error(`Create contract ${t.capability} requires a null base hash`);if(t.operation==="replace"&&!t.baseHash?.match(Fp))throw new Error(`Replace contract ${t.capability} requires a base hash`);let e=Bp(t.source,`Contract source for ${t.capability}`);return{snapshot:{capability:t.capability,operation:t.operation,source:e,baseHash:t.baseHash,contentHash:qp(t.markdown)},markdown:t.markdown}}function SE(t,e){return Vp(t.id,e.id)}function Vp(t,e){return t<e?-1:t>e?1:0}function zp(t){let e=Bp(t.briefSource??"brief.md","Native brief source"),i=t.specs.map(bE).sort((f,d)=>Vp(f.snapshot.capability,d.snapshot.capability)),n=i.map(({snapshot:f})=>f.capability);if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate capabilities");let r=[e,...i.flatMap(({snapshot:f})=>f.source===null?[]:[f.source])];if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate artifact sources");let a=Op(t.briefMarkdown,e,jn.maxAcceptanceCriteria);for(let{snapshot:f,markdown:d}of i)d===null||f.source===null||(a.push(...jp(d,f.source,jn.maxAcceptanceCriteria-a.length)),a.push(...$p(d,f.source,jn.maxAcceptanceCriteria-a.length)));if(a.sort(SE),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>jn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${jn.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:f})=>f);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:e,contentHash:qp(t.briefMarkdown)},c=i.map(({snapshot:f})=>f),l=W(NE,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:W(yE,u)}}var La={maxSpecs:64,maxFileBytes:Fr,maxTotalBytes:4*1024*1024};async function ul(t){if(t.specChanges.length>La.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let e=await Ie({root:t.changeDir,ref:t.briefRef,maxBytes:La.maxFileBytes}),i=e.size,n=[];for(let r of t.specChanges){if(r.operation==="remove"){n.push({capability:r.capability,operation:"remove",source:null,baseHash:r.base_hash,markdown:null});continue}if(!r.source)throw new Error(`Native contract ${r.capability} has no proposed spec source`);let a=await Ie({root:t.changeDir,ref:r.source,maxBytes:La.maxFileBytes});if(i+=a.size,i>La.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");n.push({capability:r.capability,operation:r.operation,source:a.ref,baseHash:r.base_hash,markdown:a.text})}return{contract:zp({briefSource:e.ref,briefMarkdown:e.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{createHash as $E}from"node:crypto";import{promises as Fe}from"node:fs";import Ue from"node:path";var Da="comet.native.verification-receipt.v3",Wp=Da,kE="comet.native.declared-artifacts.v1",EE=/^[a-f0-9]{64}$/u,RE=/^acceptance-[a-f0-9]{64}$/u,CE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,PE=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,AE=4096,xE=256,TE=1024;function ki(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new Error(`${e} must be a plain object`);return t}function _t(t,e,i){let n=Object.keys(t).sort(),r=[...e].sort();if(n.length!==r.length||n.some((a,o)=>a!==r[o]))throw new Error(`${i} fields are invalid`)}function lt(t,e){if(typeof t!="string"||!EE.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function De(t,e){if(typeof t!="string")throw new Error(`${e} must be text`);let i=Ce(t).trim();if(!i||i.length>AE||i!==t.trim())throw new Error(`${e} is invalid`);return i}function fl(t,e){let i=De(t,e),n=new Date(i);if(Number.isNaN(n.getTime())||n.toISOString()!==i)throw new Error(`${e} must be a canonical timestamp`);return i}function $n(t,e,i=De,n=!1,r=xE){if(!Array.isArray(t)||t.length>r||!n&&t.length===0)throw new Error(`${e} must be a bounded non-empty array`);let a=t.map((o,s)=>i(o,`${e} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${e} has duplicates`);return a}function IE(t,e){if(typeof t!="string"||!RE.test(t))throw new Error(`${e} is invalid`);return t}function _E(t){let e=ki(t,"Native verification receipt bindings");if(_t(e,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof e.change!="string"||!CE.test(e.change)||!Number.isSafeInteger(e.sourceRevision)||e.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:e.change,sourceRevision:e.sourceRevision,contractHash:lt(e.contractHash,"Native verification receipt contract hash"),scopeHash:lt(e.scopeHash,"Native verification receipt scope hash"),snapshotHash:lt(e.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:lt(e.artifactHash,"Native verification receipt artifact hash")}}function OE(t){if(typeof t!="string")throw new Error("Native static check receipt ref is invalid");let e=PE.exec(t);if(!e)throw new Error("Native static check receipt ref is invalid");return{ref:t,hash:e[1]}}function jE(t,e,i,n){let r=ki(e,`Native ${t} evidence`);if(t==="automated-check"){if(_t(r,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(r.exitCode)||!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1||r.timeoutMs>3600*1e3||typeof r.timedOut!="boolean"||typeof r.outputTruncated!="boolean"||r.signal!==null&&typeof r.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=fl(r.startedAt,"Native automated-check start time"),o=fl(r.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&r.exitCode!==0||i==="failed"&&r.exitCode===0||i==="passed"&&(r.timedOut||r.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=ki(r.worktree,"Native automated-check worktree");if(_t(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=ki(r.afterFence,"Native automated-check after fence");if(_t(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:De(r.executable,"Native automated-check executable"),args:$n(r.args,"Native automated-check arguments",De,!0),cwd:De(r.cwd,"Native automated-check cwd"),exitCode:r.exitCode,signal:r.signal,timedOut:r.timedOut,timeoutMs:r.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:De(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:lt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:lt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:lt(r.outputHash,"Native automated-check output hash"),outputSummary:De(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(t==="static-inspection"){_t(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=OE(r.checkReceiptRef);if(lt(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:$n(r.subjects,"Native static inspection subjects",De,n==="required-check"),rule:De(r.rule,"Native static inspection rule"),resultSummary:De(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(t==="manual-evidence")return _t(r,["steps","observations"],"Native manual-evidence evidence"),{steps:$n(r.steps,"Native manual evidence steps"),observations:$n(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${t}`)}function Jp(t){let e=ki(t,"Native verification receipt");if(_t(e,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(e.kind)||e.role!=="required-check"&&e.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(e.status))throw new Error("Native verification receipt kind or status is invalid");let i=e.kind,n=e.role,r=e.status,a=De(e.actor,"Native verification receipt actor"),o=$n(e.acceptanceIds,"Native receipt acceptance IDs",IE,n==="required-check",TE).sort();if(n==="required-check"&&o.length!==0||n==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(n==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Da,kind:i,role:n,status:r,bindings:_E(e.bindings),acceptanceIds:o,actor:a,issuedAt:fl(e.issuedAt,"Native verification receipt issue time"),evidence:jE(i,e.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Ma||s.actor!==`native-runtime:${Ma}`))throw new Error("Native required check policy identity is invalid");return s}function dl(t){let e=Jp({schema:Da,...t});return{...e,receiptHash:W(Wp,e)}}function hl(t){let e=ki(t,"Native verification receipt");if(_t(e,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),e.schema!==Da)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=e,r=Jp(n),a=lt(e.receiptHash,"Native verification receipt hash");if(W(Wp,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function pl(t){return W(kE,[...t].map(e=>({path:e.path,kind:e.kind})).sort((e,i)=>e.path.localeCompare(i.path)||e.kind.localeCompare(i.kind)))}var Yp=/^[a-f0-9]{64}$/u,Ot=Gt,L_=3*Ot;function ml(t,e){let i=Ue.relative(t,e);return i===""||!Ue.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ue.sep}`)}function HE(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Fa(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?F(i,n):F(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Kp(t){let e=await Fe.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${t}`);return{path:t,realPath:await Fe.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function ME(t,e){let i=Ue.resolve(t),n=Ue.resolve(e);if(!ml(i,n))throw new Error("Native evidence path is outside its change");let r=[await Kp(i)],a=i;for(let o of Ue.relative(i,n).split(Ue.sep).filter(Boolean)){a=Ue.join(a,o);let s=await Kp(a);if(!ml(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function Gp(t){for(let e of t){let i=await Fe.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!HE(e,i)||await Fe.realpath(e.path)!==e.realPath)throw new Error(`Native evidence parent changed while reading: ${e.path}`)}}async function LE(t,e,i={}){let n=await ME(e,Ue.dirname(t));await i.afterParentChainCaptured?.();let r=await Fe.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Fe.realpath(t);if(!ml(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Fe.open(t,"r");try{let[s,c,l]=await Promise.all([o.stat(),Fe.lstat(t),Fe.realpath(t)]);if(await Gp(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Fa(s,r)||!Fa(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Ot)throw new Error(`Native evidence document exceeds ${Ot} bytes`);await i.afterOpen?.();let u=[],f=0,d=Buffer.allocUnsafe(64*1024);for(;;){let v=Ot+1-f,w=await o.read(d,0,Math.min(d.length,v),null);if(w.bytesRead===0)break;if(f+=w.bytesRead,f>Ot)throw new Error(`Native evidence document exceeds ${Ot} bytes`);u.push(Buffer.from(d.subarray(0,w.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Fe.lstat(t),Fe.realpath(t)]);if(await Gp(n),!m.isFile()||m.isSymbolicLink()||h!==a||!Fa(s,p)||!Fa(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,f).toString("utf8"))}finally{await o.close()}}function Ba(t,e){if(!Yp.test(e))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${t}/${e}.json`}async function DE(t,e,i,n,r){if(!Yp.test(i))throw new Error("Native report evidence hash is invalid");let a=await ut({paths:t,name:e,kind:"reports",hash:i,hooks:n,changeDir:r});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||$E("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function Ei(t,e){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(t);if(!i||i[1]!==e)throw new Error(`Native evidence ref is invalid for ${e}`);return i[2]}function Xp(t,e,i,n,r){return Ue.join(r??Y(t,e),...Ba(i,n).split("/"))}async function ut(t){let e=t.changeDir??Y(t.paths,t.name),i=Xp(t.paths,t.name,t.kind,t.hash,e);return await q(t.paths.nativeRoot,i),LE(i,e,t.hooks)}async function FE(t){BE(t.value);let e=Xp(t.paths,t.name,t.kind,t.hash);await q(t.paths.nativeRoot,e);try{let n=await ut(t);if(JSON.stringify(n)!==JSON.stringify(t.value))throw new Error(`Native evidence hash collision for ${t.hash}`);return Ba(t.kind,t.hash)}catch(n){if(n.code!=="ENOENT")throw n}await Oe(e,t.value,{containedRoot:t.paths.nativeRoot});let i=await ut(t);if(JSON.stringify(i)!==JSON.stringify(t.value))throw new Error(`Native evidence changed during commit for ${t.hash}`);return Ba(t.kind,t.hash)}function BE(t){if(qE(t)>Ot)throw new Error(`Native evidence document exceeds ${Ot} bytes`)}function qE(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
168
|
-
`,"utf8")}function Up(t,e){return Ca(t,e)}function VE(t,e){let i=xa(t);if(i.scopeHash!==e)throw new Error("Native implementation scope ref/hash mismatch");return i}function zE(t,e,i){let n=pp(t);if(n.change!==e||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function WE(t,e,i){let n=Fc(t);if(n.change!==e||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function JE(t,e,i,n=!1,r){let a=await Qp(t,e,i.implementationScopeRef,void 0,r);if(n&&await DE(t,e,i.reportHash,void 0,r),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await Zp(t,e,i.partialAllowanceRef,void 0,r);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function qa(t,e,i,n,r){let a=Ei(i,"scopes"),o=VE(await ut({paths:t,name:e,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=Ei(o.baselineProjectionRef,"snapshots"),c=Ei(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([ut({paths:t,name:e,kind:"snapshots",hash:s,changeDir:r}).then(f=>Up(f,s)),ut({paths:t,name:e,kind:"snapshots",hash:c,changeDir:r}).then(f=>Up(f,c))]);return sp({baseline:l,current:u,scope:o})}async function Qp(t,e,i,n,r){return(await qa(t,e,i,n,r)).scope}async function Zp(t,e,i,n,r){let a=Ei(i,"allowances");return zE(await ut({paths:t,name:e,kind:"allowances",hash:a,hooks:n,changeDir:r}),e,a)}async function vl(t){let e=hl(t.receipt);if(e.bindings.change!==t.name)throw new Error("Native verification receipt change mismatch");return FE({paths:t.paths,name:t.name,kind:"receipts",hash:e.receiptHash,value:e})}async function gl(t,e,i,n,r){let a=Ei(i,"receipts"),o=hl(await ut({paths:t,name:e,kind:"receipts",hash:a,hooks:n,changeDir:r}));if(o.bindings.change!==e||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function wl(t,e,i,n,r){let a=Ei(i,"verifications"),o=WE(await ut({paths:t,name:e,kind:"verifications",hash:a,hooks:n,changeDir:r}),e,a);return await JE(t,e,o,!1,r),o}var Nl=64*1024,YE=12e4,Hn=3600*1e3,XE=4e3,QE="native-runtime:manual-evidence",em=UE(KE),ZE=new Set([".bat",".cmd",".ps1"]),eR=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function tR(t){let e=(t.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...e,".ps1"])]}function iR(t,e,i){let r=Ye.win32.isAbsolute(t)||/[\\/]/u.test(t)?[""]:(e.PATH??"").split(Ye.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Ye.win32.extname(t)?[t]:tR(e).map(s=>`${t}${s}`);return r.flatMap(s=>o.map(c=>s?Ye.join(s,c):Ye.resolve(i,c)))}function nR(t,e,i){return iR(t,e,i).find(n=>im(n))??t}function rR(t){let e=t.SYSTEMROOT??t.SystemRoot;if(e){let i=Ye.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe");if(im(i))return i}return"powershell.exe"}function aR(t,e,i){let n=Buffer.from(JSON.stringify({command:t,arguments:[...e]}),"utf8").toString("base64"),r=Buffer.from(eR,"utf16le").toString("base64");return yl(rR(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",r],{cwd:i.cwd,env:{...i.env,COMET_NATIVE_COMMAND_PAYLOAD:n},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function oR(t,e,i){if(process.platform!=="win32")return yl(t,[...e],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=nR(t,i.env,i.cwd);return ZE.has(Ye.win32.extname(n).toLowerCase())?aR(n,e,i):yl(n,[...e],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}async function nm(t){return kt(t.paths,t.operation,()=>$a(t.paths,t.name,t.operation,async()=>(await nl(t.paths,t.name),t.issue(await Ne(t.paths,t.name)))))}function sR(t,e){let i=t.trim();if(!i||Buffer.byteLength(i,"utf8")>Nl)throw new Error(`${e} is invalid`);return i}function rm(t,e){let i=[...t].sort();if(i.length===0||new Set(i).size!==i.length||i.some(n=>!e.includes(n)))throw new Error("Native receipt acceptance IDs do not match the current contract");return i}async function Va(t,e){if(e.phase!=="verify")throw new Error(`Native verification receipt issuance requires Verify, got ${e.phase}`);if(!e.implementation_scope)throw new Error("Native verification receipt issuance requires an implementation scope");let[i,n]=await Promise.all([qa(t,e.name,e.implementation_scope),ul({changeDir:Y(t,e.name),briefRef:e.brief,specChanges:e.spec_changes})]);if(i.scope.contractHash!==n.contract.contractHash)throw new Error("Native verification receipt contract/scope mismatch");let r=e.run_id?`run:${e.run_id}`:`scope:${i.scope.scopeHash}`;return{bindings:{change:e.name,sourceRevision:e.revision,contractHash:n.contract.contractHash,scopeHash:i.scope.scopeHash,snapshotHash:i.scope.currentProjectionHash,artifactHash:pl(i.scope.declaredArtifacts)},acceptanceIds:n.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${r}`,implementationExecutionId:r,scope:i}}var cR=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function bl(t,e){let i=[];for(let n of cR){let r=t.bindings[n],a=e[n];r!==a&&i.push(`${n}: expected ${JSON.stringify(a)}, got ${JSON.stringify(r)}`)}return{ok:i.length===0,mismatches:i}}async function za(t){return nm({paths:t.paths,name:t.name,operation:`issue manual receipt ${t.name}`,issue:e=>lR({...t,state:e})})}async function lR(t){let e=await Va(t.paths,t.state),i=dl({kind:"manual-evidence",role:"acceptance-evidence",status:"passed",bindings:e.bindings,acceptanceIds:rm(t.acceptanceIds,e.acceptanceIds),actor:QE,issuedAt:(t.now??new Date).toISOString(),evidence:{steps:[...t.steps],observations:[...t.observations]}});return{receipt:i,ref:await vl({paths:t.paths,name:t.state.name,receipt:i})}}function uR(t){return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...t.capture?{capture:t.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:t.complete,limits:t.limits,...t.policy?{policy:t.policy}:{},entries:t.entries,omitted:t.omitted,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:t.omissionOverflow}:{}}}async function fR(t){let e=uR(t.context.scope.baseline),i=await dc(t.paths,e,{origin:"explicit",now:t.now}),n=Hc({baseline:e,current:i,contractHash:t.context.bindings.contractHash,declaredArtifacts:t.context.scope.scope.declaredArtifacts,noCodeReason:t.context.scope.scope.noCodeReason,gitChangedPaths:t.context.scope.authority.gitChangedPaths});return{snapshotHash:n.scope.currentProjectionHash,scopeHash:n.scope.scopeHash,matched:n.scope.currentProjectionHash===t.context.bindings.snapshotHash&&n.scope.scopeHash===t.context.bindings.scopeHash}}async function tm(t){try{let[{stdout:e},{stdout:i}]=await Promise.all([em("git",["-C",t,"rev-parse","--show-toplevel"],{windowsHide:!0,timeout:1e4}),em("git",["-C",t,"rev-parse","HEAD"],{windowsHide:!0,timeout:1e4})]),n=Ye.resolve(e.trim()),r=Ye.relative(t,n).replaceAll("\\","/");if(r===".."||r.startsWith("../")||Ye.posix.isAbsolute(r))throw new Error("Git worktree is outside the Native project root");let a=i.trim().toLowerCase();if(!/^[a-f0-9]{40,64}$/u.test(a))throw new Error("Git commit identity is invalid");return{provider:"git",root:r||".",commit:a}}catch{return{provider:"none",root:".",commit:null}}}async function am(t){return nm({paths:t.paths,name:t.name,operation:`issue automated receipt ${t.name}`,issue:e=>dR({...t,state:e})})}async function dR(t){let e=await Va(t.paths,t.state),i=await tm(t.paths.projectRoot),n=(t.now?.()??new Date).toISOString(),r=t.timeoutMs??YE;if(!Number.isSafeInteger(r)||r<1||r>Hn)throw new Error(`Native automated command timeout must be an integer from 1 through ${Hn}`);let a=[],o=0,s=0,c=GE("sha256"),l=!1,u=oR(t.command,t.args,{cwd:t.paths.projectRoot,env:{...process.env}}),f=g=>{if(c.update(g),s+=g.byteLength,o>=Nl)return;let b=Nl-o,y=g.subarray(0,b);a.push(Buffer.from(y)),o+=y.byteLength};u.stdout.on("data",f),u.stderr.on("data",f);let d=await new Promise((g,b)=>{let y=!1,R=null,O=null,B=D=>{y||(y=!0,clearTimeout(H),O&&clearTimeout(O),g(D))},H=setTimeout(()=>{l=!0,R=Al(u).catch(()=>{u.kill("SIGKILL"),u.stdout?.destroy(),u.stderr?.destroy()}),O=setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),B({exitCode:124,signal:"SIGKILL"})},XE)},r);u.once("error",D=>{if(l){(R??Promise.resolve()).then(()=>B({exitCode:124,signal:"SIGKILL"}));return}y||(y=!0,clearTimeout(H),O&&clearTimeout(O),b(D))}),u.once("close",(D,J)=>{(R??Promise.resolve()).then(()=>B({exitCode:l?124:D??1,signal:J??(l?"SIGKILL":null)}))})}),p=(t.now?.()??new Date).toISOString(),[m,h]=await Promise.all([tm(t.paths.projectRoot),fR({paths:t.paths,context:e,now:t.now?.()})]),v=e.scope.current.capture,E=(!(v?.provider==="git"||v?.provider==="physical-tree"&&v.projection?.provider==="git")||i.provider==="git")&&i.provider===m.provider&&i.root===m.root&&i.commit===m.commit,k=l||!h.matched||!E?"blocked":d.exitCode===0?"passed":"failed",N=Buffer.concat(a,o).toString("utf8").trim(),S=dl({kind:"automated-check",role:"acceptance-evidence",status:k,bindings:e.bindings,acceptanceIds:rm(t.acceptanceIds,e.acceptanceIds),actor:`native-runtime:command:${t.command}`,issuedAt:p,evidence:{executable:t.command,args:[...t.args],cwd:".",exitCode:d.exitCode,signal:d.signal,timedOut:l,timeoutMs:r,startedAt:n,endedAt:p,worktree:{provider:i.provider,root:i.root,beforeCommit:i.commit,afterCommit:m.commit},afterFence:{...h,matched:h.matched&&E},outputHash:c.digest("hex"),outputSummary:sR(Ce(N||`(exit ${d.exitCode})`),"Native command output summary"),outputTruncated:s>o}});return{receipt:S,ref:await vl({paths:t.paths,name:t.state.name,receipt:S})}}import hR from"node:path";var pR="Native receipt re-issued after revision bump";function mR(t){return!t.ok&&t.mismatches.length===1&&t.mismatches[0]?.startsWith("sourceRevision: ")===!0}function vR(t){return t.kind!=="automated-check"?"<unknown automated receipt>":[t.evidence.executable,...t.evidence.args].map(i=>/\s/u.test(i)?JSON.stringify(i):i).join(" ")}function gR(t){return`${pR} to revision ${t}`}function wR(){return"Manual evidence re-issued via `comet native receipt refresh` to restore revision binding."}async function om(t){let e=await Ne(t.paths,t.name);if(e.phase!=="verify")throw new Error(`Native receipt refresh requires Verify, got ${e.phase} for ${t.name}`);if(!e.verification_evidence)return{refreshed:[],requiresRerun:[],requiresManual:[],requiresCheck:[],applied:!1,verificationReport:null};let i=await Va(t.paths,e),n=await wl(t.paths,t.name,e.verification_evidence),r=[],a=[],o=[],s=[],c=new Set,l=[...new Set([...n.requiredReceiptRefs,...n.receiptRefs])];for(let S of l){let g=await gl(t.paths,t.name,S),b=bl(g,i.bindings);if(!b.ok)if(c.add(S),g.kind==="manual-evidence"){let y={oldRef:S,acceptanceIds:[...g.acceptanceIds]};mR(b)?r.push(y):a.push({...y,mismatches:b.mismatches})}else g.kind==="automated-check"?o.push({oldRef:S,acceptanceIds:[...g.acceptanceIds],command:vR(g),timeoutMs:g.evidence.timeoutMs}):g.kind==="static-inspection"&&s.push({oldRef:S})}if(!(t.apply&&o.length===0&&a.length===0&&r.length>0))return{refreshed:[],requiresRerun:o,requiresManual:a,requiresCheck:s,applied:!1,verificationReport:e.verification_report};let f=[],d=new Map,p=new Map;for(let S of r){let g=[...S.acceptanceIds].sort().join(`
|
|
169
|
-
`),
|
|
170
|
-
`),
|
|
171
|
-
`}}function
|
|
172
|
-
`}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function
|
|
173
|
-
`)}if(i==="automated"){let a=t.indexOf("--");if(a<0||a===t.length-1)throw new
|
|
174
|
-
`
|
|
168
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:e===null&&!i&&n===null,index:s},s+=1,e!==null)e=kl(l,e);else if(i)im(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let f=kl(l,null);if(f!==null)e=f;else{let d=l.trimStart();if(d.startsWith("<!--")&&!im(d))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);p&&r.has(p[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(d)&&(n=p[1])}}}if(c===-1)break;o=c+1}}function YE(t){return[...Ci(t)].map(({line:e,body:i})=>({line:e,body:i}))}function Sl(t){return t.normalize("NFC").replace(/\s+/gu," ").trim()}function XE(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function Rl(t,e,i,n=[]){let r=Sl(i),a=e.replaceAll("\\","/").trim(),o=n.map(Sl);if(r.length===0)throw new Error(`${t} acceptance criterion must not be empty`);if(a.length===0)throw new Error(`${t} acceptance criterion source must not be empty`);return{id:`acceptance-${W(JE,{kind:t,source:a,context:o,text:r})}`,kind:t,source:a,context:o,text:r}}function Cl(t,e){let i=new Set;for(let n of t){if(i.has(n.id))throw new Error(`${e} contains duplicate acceptance criteria`);i.add(n.id)}return t}function QE(t){let e=null,i=null,n=0,r=0;for(let{line:a,body:o,index:s}of Ci(t)){r=s+1;let c=o?El(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(n+=1,n===1&&(e=s+1)):e!==null&&i===null&&(i=s))}if(n===0||e===null)return null;if(n!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:e,end:i??r}}function nm(t,e="brief.md",i=Bn.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=QE(t);if(n===null)return[];let r=null;for(let{line:c,body:l,index:u}of Ci(t)){if(u<n.start||u>=n.end)continue;let f=l?/^( {0,3})[-*+][ \t]+/u.exec(c):null;if(f===null)continue;let d=f[1].length;r=r===null?d:Math.min(r,d)}let a=[],o=null,s=()=>{if(o!==null){if(a.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);a.push(o)}};for(let{line:c,body:l,index:u}of Ci(t)){if(u<n.start||u>=n.end)continue;let f=l?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;f&&f[1].length===r?(s(),o=[f[2]]):o!==null&&o.push(c)}return s(),Cl(a.map(c=>Rl("brief-example",e,c.join(`
|
|
169
|
+
`))),"Brief")}function rm(t,e="spec.md",i=Bn.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],r=[],a=null,o=()=>{if(a!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Rl("spec-scenario",e,[a.title,...a.body].join(`
|
|
170
|
+
`),a.context)),a=null}};for(let{line:s,body:c}of Ci(t)){let l=c?El(s):null,u=l?/^Scenario\s*:\s*(.*)$/iu.exec(l.text):null;if(u){for(o();r.at(-1)&&r.at(-1).level>=l.level;)r.pop();let f=Sl(u[1]);if(f.length===0)throw new Error("Scenario title must not be empty");a={level:l.level,title:f,body:[],context:r.map(d=>d.text)}}else if(l){for(a!==null&&l.level<=a.level?o():a!==null&&a.body.push(s);r.at(-1)&&r.at(-1).level>=l.level;)r.pop();r.push(l)}else a!==null&&c&&a.body.push(s)}return o(),Cl(n,"Specification")}function am(t,e="spec.md",i=Bn.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],r=[],a=null,o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Rl("spec-must",e,o.parts.join(" "),o.context)),o=null}},c=()=>r.some(l=>/^(?:non-?goals?|非目标)$/iu.test(l.text.trim()));for(let{line:l,body:u}of Ci(t)){let f=u?El(l):null;if(f){for(s(),a!==null&&f.level<=a&&(a=null);r.at(-1)&&r.at(-1).level>=f.level;)r.pop();r.push(f),/^Scenario\s*:/iu.test(f.text)&&(a=f.level);continue}let d=l.trim();if(!u||a!==null||c()){s();continue}if(d.length===0||kl(l,null)!==null||d.startsWith("<!--")||d==="-->"||d==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(d)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(d)||/^(?:[-*_]\s*){3,}$/u.test(d)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(d)){s();continue}let p=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(l);if(p){s(),o={parts:[p[1]],context:r.map(m=>m.text)};continue}if(/^\|.*\|$/u.test(d)){s(),o={parts:[d],context:r.map(m=>m.text)},s();continue}o===null?o={parts:[d],context:r.map(m=>m.text)}:o.parts.push(d)}return s(),Cl(n,"Specification mandatory requirements")}function ZE(t,e){let i=t.trim().replaceAll("\\","/");if(i.length===0||XE(i)||tm.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${e} has an unsafe evidence ref`);let n=tm.posix.normalize(i);if(n==="."||n===".."||n.startsWith("../"))throw new Error(`Acceptance evidence ${e} has an unsafe evidence ref`);if(n.split("/").some(r=>r.toLowerCase()===".git"||r.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${e} references sensitive content`);if(!UE.test(n))throw new Error(`Acceptance evidence ${e} must reference a content-addressed typed receipt`);return n}function eR(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`Acceptance evidence entry ${e} must be an object`);let i=t,n=Object.keys(i).filter(r=>!KE.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${e} has unknown field(s): ${n.join(", ")}`);return i}function om(t){if(!Array.isArray(t))throw new Error("Native acceptance evidence block must be a JSON array");let e=new Set;return t.map((i,n)=>{let r=eR(i,n),a=r.acceptance_id;if(typeof a!="string"||!GE.test(a))throw new Error(`Acceptance evidence entry ${n} has an invalid acceptance_id`);if(e.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(e.add(a),!Array.isArray(r.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=r.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return ZE(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=r.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(r,"skipped_reason")){if(typeof r.skipped_reason!="string"||r.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=r.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function Pl(t){let e=YE(t);if(e.some(({line:l,body:u})=>!u&&(l===Fn||l===Ri)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=e.flatMap(({line:l,body:u},f)=>u&&l===Fn?[f]:[]),r=e.flatMap(({line:l,body:u},f)=>u&&l===Ri?[f]:[]);if(n.length!==1||r.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(n[0]>=r[0])throw new Error("Native acceptance evidence markers are out of order");let a=e.slice(n[0]+1,r[0]).map(({line:l})=>l).join(`
|
|
171
|
+
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=om(o),c=sm(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function sm(t){let e=om([...t]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,n)=>i.acceptance_id.localeCompare(n.acceptance_id));return JSON.stringify(e,null,2)}function cm(t){return[Fn,sm(t),Ri].join(`
|
|
172
|
+
`)}var tR="comet.native.contract.v1",iR="comet.native.acceptance-set.v1",um=/^[a-f0-9]{64}$/u,Dn={maxAcceptanceCriteria:Bn.maxCriteria};function fm(t,e){let i=lm.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||lm.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||i!==t||i==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized project-relative ref`);return t}function dm(t){return W("comet.native.contract-content.v1",t.replace(/\r\n?/gu,`
|
|
173
|
+
`))}function nR(t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.capability))throw new Error(`Invalid Native contract capability: ${t.capability}`);if(t.operation!=="create"&&t.operation!=="replace"&&t.operation!=="remove")throw new Error(`Invalid Native contract operation for ${t.capability}`);if(t.operation==="remove"){if(t.source!==null||t.markdown!==null||!t.baseHash?.match(um))throw new Error(`Remove contract ${t.capability} requires only a base hash`);return{snapshot:{capability:t.capability,operation:"remove",source:null,baseHash:t.baseHash,contentHash:null},markdown:null}}if(t.source===null||t.markdown===null)throw new Error(`${t.operation} contract ${t.capability} requires source content`);if(t.operation==="create"&&t.baseHash!==null)throw new Error(`Create contract ${t.capability} requires a null base hash`);if(t.operation==="replace"&&!t.baseHash?.match(um))throw new Error(`Replace contract ${t.capability} requires a base hash`);let e=fm(t.source,`Contract source for ${t.capability}`);return{snapshot:{capability:t.capability,operation:t.operation,source:e,baseHash:t.baseHash,contentHash:dm(t.markdown)},markdown:t.markdown}}function rR(t,e){return hm(t.id,e.id)}function hm(t,e){return t<e?-1:t>e?1:0}function pm(t){let e=fm(t.briefSource??"brief.md","Native brief source"),i=t.specs.map(nR).sort((f,d)=>hm(f.snapshot.capability,d.snapshot.capability)),n=i.map(({snapshot:f})=>f.capability);if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate capabilities");let r=[e,...i.flatMap(({snapshot:f})=>f.source===null?[]:[f.source])];if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate artifact sources");let a=nm(t.briefMarkdown,e,Dn.maxAcceptanceCriteria);for(let{snapshot:f,markdown:d}of i)d===null||f.source===null||(a.push(...rm(d,f.source,Dn.maxAcceptanceCriteria-a.length)),a.push(...am(d,f.source,Dn.maxAcceptanceCriteria-a.length)));if(a.sort(rR),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Dn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Dn.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:f})=>f);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:e,contentHash:dm(t.briefMarkdown)},c=i.map(({snapshot:f})=>f),l=W(iR,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:W(tR,u)}}var Qa={maxSpecs:64,maxFileBytes:Ur,maxTotalBytes:4*1024*1024};async function Al(t){if(t.specChanges.length>Qa.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let e=await Re({root:t.changeDir,ref:t.briefRef,maxBytes:Qa.maxFileBytes}),i=e.size,n=[];for(let r of t.specChanges){if(r.operation==="remove"){n.push({capability:r.capability,operation:"remove",source:null,baseHash:r.base_hash,markdown:null});continue}if(!r.source)throw new Error(`Native contract ${r.capability} has no proposed spec source`);let a=await Re({root:t.changeDir,ref:r.source,maxBytes:Qa.maxFileBytes});if(i+=a.size,i>Qa.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");n.push({capability:r.capability,operation:r.operation,source:a.ref,baseHash:r.base_hash,markdown:a.text})}return{contract:pm({briefSource:e.ref,briefMarkdown:e.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{createHash as gR}from"node:crypto";import{promises as De}from"node:fs";import Ye from"node:path";var Za="comet.native.verification-receipt.v3",mm=Za,aR="comet.native.declared-artifacts.v1",oR=/^[a-f0-9]{64}$/u,sR=/^acceptance-[a-f0-9]{64}$/u,cR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lR=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,uR=4096,fR=256,dR=1024;function Pi(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new Error(`${e} must be a plain object`);return t}function Ot(t,e,i){let n=Object.keys(t).sort(),r=[...e].sort();if(n.length!==r.length||n.some((a,o)=>a!==r[o]))throw new Error(`${i} fields are invalid`)}function ft(t,e){if(typeof t!="string"||!oR.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function Be(t,e){if(typeof t!="string")throw new Error(`${e} must be text`);let i=xe(t).trim();if(!i||i.length>uR||i!==t.trim())throw new Error(`${e} is invalid`);return i}function xl(t,e){let i=Be(t,e),n=new Date(i);if(Number.isNaN(n.getTime())||n.toISOString()!==i)throw new Error(`${e} must be a canonical timestamp`);return i}function qn(t,e,i=Be,n=!1,r=fR){if(!Array.isArray(t)||t.length>r||!n&&t.length===0)throw new Error(`${e} must be a bounded non-empty array`);let a=t.map((o,s)=>i(o,`${e} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${e} has duplicates`);return a}function hR(t,e){if(typeof t!="string"||!sR.test(t))throw new Error(`${e} is invalid`);return t}function pR(t){let e=Pi(t,"Native verification receipt bindings");if(Ot(e,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof e.change!="string"||!cR.test(e.change)||!Number.isSafeInteger(e.sourceRevision)||e.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:e.change,sourceRevision:e.sourceRevision,contractHash:ft(e.contractHash,"Native verification receipt contract hash"),scopeHash:ft(e.scopeHash,"Native verification receipt scope hash"),snapshotHash:ft(e.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:ft(e.artifactHash,"Native verification receipt artifact hash")}}function mR(t){if(typeof t!="string")throw new Error("Native static check receipt ref is invalid");let e=lR.exec(t);if(!e)throw new Error("Native static check receipt ref is invalid");return{ref:t,hash:e[1]}}function vR(t,e,i,n){let r=Pi(e,`Native ${t} evidence`);if(t==="automated-check"){if(Ot(r,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(r.exitCode)||!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1||r.timeoutMs>3600*1e3||typeof r.timedOut!="boolean"||typeof r.outputTruncated!="boolean"||r.signal!==null&&typeof r.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=xl(r.startedAt,"Native automated-check start time"),o=xl(r.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&r.exitCode!==0||i==="failed"&&r.exitCode===0||i==="passed"&&(r.timedOut||r.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Pi(r.worktree,"Native automated-check worktree");if(Ot(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=Pi(r.afterFence,"Native automated-check after fence");if(Ot(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Be(r.executable,"Native automated-check executable"),args:qn(r.args,"Native automated-check arguments",Be,!0),cwd:Be(r.cwd,"Native automated-check cwd"),exitCode:r.exitCode,signal:r.signal,timedOut:r.timedOut,timeoutMs:r.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:Be(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:ft(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:ft(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:ft(r.outputHash,"Native automated-check output hash"),outputSummary:Be(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(t==="static-inspection"){Ot(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=mR(r.checkReceiptRef);if(ft(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:qn(r.subjects,"Native static inspection subjects",Be,n==="required-check"),rule:Be(r.rule,"Native static inspection rule"),resultSummary:Be(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(t==="manual-evidence")return Ot(r,["steps","observations"],"Native manual-evidence evidence"),{steps:qn(r.steps,"Native manual evidence steps"),observations:qn(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${t}`)}function vm(t){let e=Pi(t,"Native verification receipt");if(Ot(e,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(e.kind)||e.role!=="required-check"&&e.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(e.status))throw new Error("Native verification receipt kind or status is invalid");let i=e.kind,n=e.role,r=e.status,a=Be(e.actor,"Native verification receipt actor"),o=qn(e.acceptanceIds,"Native receipt acceptance IDs",hR,n==="required-check",dR).sort();if(n==="required-check"&&o.length!==0||n==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(n==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Za,kind:i,role:n,status:r,bindings:pR(e.bindings),acceptanceIds:o,actor:a,issuedAt:xl(e.issuedAt,"Native verification receipt issue time"),evidence:vR(i,e.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Xa||s.actor!==`native-runtime:${Xa}`))throw new Error("Native required check policy identity is invalid");return s}function Tl(t){let e=vm({schema:Za,...t});return{...e,receiptHash:W(mm,e)}}function Il(t){let e=Pi(t,"Native verification receipt");if(Ot(e,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),e.schema!==Za)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=e,r=vm(n),a=ft(e.receiptHash,"Native verification receipt hash");if(W(mm,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function _l(t){return W(aR,[...t].map(e=>({path:e.path,kind:e.kind})).sort((e,i)=>e.path.localeCompare(i.path)||e.kind.localeCompare(i.kind)))}var Nm=/^[a-f0-9]{64}$/u,$t=Xt,Vj=3*$t;function jl(t,e){let i=Ye.relative(t,e);return i===""||!Ye.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ye.sep}`)}function wR(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function eo(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return ue(i,n)?B(i,n):B(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function gm(t){let e=await De.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${t}`);return{path:t,realPath:await De.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function yR(t,e){let i=Ye.resolve(t),n=Ye.resolve(e);if(!jl(i,n))throw new Error("Native evidence path is outside its change");let r=[await gm(i)],a=i;for(let o of Ye.relative(i,n).split(Ye.sep).filter(Boolean)){a=Ye.join(a,o);let s=await gm(a);if(!jl(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function wm(t){for(let e of t){let i=await De.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!wR(e,i)||await De.realpath(e.path)!==e.realPath)throw new Error(`Native evidence parent changed while reading: ${e.path}`)}}async function NR(t,e,i={}){let n=await yR(e,Ye.dirname(t));await i.afterParentChainCaptured?.();let r=await De.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await De.realpath(t);if(!jl(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await De.open(t,"r");try{let[s,c,l]=await Promise.all([o.stat(),De.lstat(t),De.realpath(t)]);if(await wm(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!eo(s,r)||!eo(s,c))throw new Error("Native evidence document changed while opening");if(s.size>$t)throw new Error(`Native evidence document exceeds ${$t} bytes`);await i.afterOpen?.();let u=[],f=0,d=Buffer.allocUnsafe(64*1024);for(;;){let v=$t+1-f,S=await o.read(d,0,Math.min(d.length,v),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,f>$t)throw new Error(`Native evidence document exceeds ${$t} bytes`);u.push(Buffer.from(d.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),De.lstat(t),De.realpath(t)]);if(await wm(n),!m.isFile()||m.isSymbolicLink()||h!==a||!eo(s,p)||!eo(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,f).toString("utf8"))}finally{await o.close()}}function to(t,e){if(!Nm.test(e))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${t}/${e}.json`}async function bR(t,e,i,n,r){if(!Nm.test(i))throw new Error("Native report evidence hash is invalid");let a=await dt({paths:t,name:e,kind:"reports",hash:i,hooks:n,changeDir:r});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||gR("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function Ai(t,e){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(t);if(!i||i[1]!==e)throw new Error(`Native evidence ref is invalid for ${e}`);return i[2]}function bm(t,e,i,n,r){return Ye.join(r??Y(t,e),...to(i,n).split("/"))}async function dt(t){let e=t.changeDir??Y(t.paths,t.name),i=bm(t.paths,t.name,t.kind,t.hash,e);return await q(t.paths.nativeRoot,i),NR(i,e,t.hooks)}async function kR(t){SR(t.value);let e=bm(t.paths,t.name,t.kind,t.hash);await q(t.paths.nativeRoot,e);try{let n=await dt(t);if(JSON.stringify(n)!==JSON.stringify(t.value))throw new Error(`Native evidence hash collision for ${t.hash}`);return to(t.kind,t.hash)}catch(n){if(n.code!=="ENOENT")throw n}await Oe(e,t.value,{containedRoot:t.paths.nativeRoot});let i=await dt(t);if(JSON.stringify(i)!==JSON.stringify(t.value))throw new Error(`Native evidence changed during commit for ${t.hash}`);return to(t.kind,t.hash)}function SR(t){if(ER(t)>$t)throw new Error(`Native evidence document exceeds ${$t} bytes`)}function ER(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
174
|
+
`,"utf8")}function ym(t,e){return Ba(t,e)}function RR(t,e){let i=Va(t);if(i.scopeHash!==e)throw new Error("Native implementation scope ref/hash mismatch");return i}function CR(t,e,i){let n=Lp(t);if(n.change!==e||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function PR(t,e,i){let n=rl(t);if(n.change!==e||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function AR(t,e,i,n=!1,r){let a=await km(t,e,i.implementationScopeRef,void 0,r);if(n&&await bR(t,e,i.reportHash,void 0,r),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await Sm(t,e,i.partialAllowanceRef,void 0,r);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function io(t,e,i,n,r){let a=Ai(i,"scopes"),o=RR(await dt({paths:t,name:e,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=Ai(o.baselineProjectionRef,"snapshots"),c=Ai(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([dt({paths:t,name:e,kind:"snapshots",hash:s,changeDir:r}).then(f=>ym(f,s)),dt({paths:t,name:e,kind:"snapshots",hash:c,changeDir:r}).then(f=>ym(f,c))]);return Ip({baseline:l,current:u,scope:o})}async function km(t,e,i,n,r){return(await io(t,e,i,n,r)).scope}async function Sm(t,e,i,n,r){let a=Ai(i,"allowances");return CR(await dt({paths:t,name:e,kind:"allowances",hash:a,hooks:n,changeDir:r}),e,a)}async function Ol(t){let e=Il(t.receipt);if(e.bindings.change!==t.name)throw new Error("Native verification receipt change mismatch");return kR({paths:t.paths,name:t.name,kind:"receipts",hash:e.receiptHash,value:e})}async function no(t,e,i,n,r){let a=Ai(i,"receipts"),o=Il(await dt({paths:t,name:e,kind:"receipts",hash:a,hooks:n,changeDir:r}));if(o.bindings.change!==e||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function $l(t,e,i,n,r){let a=Ai(i,"verifications"),o=PR(await dt({paths:t,name:e,kind:"verifications",hash:a,hooks:n,changeDir:r}),e,a);return await AR(t,e,o,!1,r),o}var xi=class extends Error{recovery;constructor(e,i){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var Ml=64*1024,_R=12e4,Vn=3600*1e3,jR=4e3,OR="native-runtime:manual-evidence",Em=IR(xR),$R=new Set([".bat",".cmd",".ps1"]),HR=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function MR(t){let e=(t.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...e,".ps1"])]}function LR(t,e,i){let r=Xe.win32.isAbsolute(t)||/[\\/]/u.test(t)?[""]:(e.PATH??"").split(Xe.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Xe.win32.extname(t)?[t]:MR(e).map(s=>`${t}${s}`);return r.flatMap(s=>o.map(c=>s?Xe.join(s,c):Xe.resolve(i,c)))}function FR(t,e,i){return LR(t,e,i).find(n=>Cm(n))??t}function BR(t){let e=t.SYSTEMROOT??t.SystemRoot;if(e){let i=Xe.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe");if(Cm(i))return i}return"powershell.exe"}function DR(t,e,i){let n=Buffer.from(JSON.stringify({command:t,arguments:[...e]}),"utf8").toString("base64"),r=Buffer.from(HR,"utf16le").toString("base64");return Hl(BR(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",r],{cwd:i.cwd,env:{...i.env,COMET_NATIVE_COMMAND_PAYLOAD:n},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function qR(t,e,i){if(process.platform!=="win32")return Hl(t,[...e],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=FR(t,i.env,i.cwd);return $R.has(Xe.win32.extname(n).toLowerCase())?DR(n,e,i):Hl(n,[...e],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}async function Pm(t){return rt(t.paths,t.operation,()=>Ua(t.paths,t.name,t.operation,async()=>(await bl(t.paths,t.name),t.issue(await ke(t.paths,t.name)))))}function VR(t,e){let i=t.trim();if(!i||Buffer.byteLength(i,"utf8")>Ml)throw new Error(`${e} is invalid`);return i}function Am(t,e){let i=[...t].sort();if(i.length===0||new Set(i).size!==i.length||i.some(n=>!e.includes(n)))throw new Error("Native receipt acceptance IDs do not match the current contract");return i}async function Wn(t,e){if(e.phase!=="verify")throw new Error(`Native verification receipt issuance requires Verify, got ${e.phase}`);if(!e.implementation_scope)throw new Error("Native verification receipt issuance requires an implementation scope");let[i,n]=await Promise.all([io(t,e.name,e.implementation_scope),Al({changeDir:Y(t,e.name),briefRef:e.brief,specChanges:e.spec_changes})]);if(i.scope.contractHash!==n.contract.contractHash)throw new Error("Native verification receipt contract/scope mismatch");let r=e.run_id?`run:${e.run_id}`:`scope:${i.scope.scopeHash}`;return{bindings:{change:e.name,sourceRevision:e.revision,contractHash:n.contract.contractHash,scopeHash:i.scope.scopeHash,snapshotHash:i.scope.currentProjectionHash,artifactHash:_l(i.scope.declaredArtifacts)},acceptanceIds:n.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${r}`,implementationExecutionId:r,scope:i}}var WR=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Ll(t,e){let i=[];for(let n of WR){let r=t.bindings[n],a=e[n];r!==a&&i.push(`${n}: expected ${JSON.stringify(a)}, got ${JSON.stringify(r)}`)}return{ok:i.length===0,mismatches:i}}async function ro(t){return Pm({paths:t.paths,name:t.name,operation:`issue manual receipt ${t.name}`,issue:e=>zR({...t,state:e})})}async function zR(t){let e=await Wn(t.paths,t.state);await ao({paths:t.paths,state:t.state,context:e});let i=Tl({kind:"manual-evidence",role:"acceptance-evidence",status:"passed",bindings:e.bindings,acceptanceIds:Am(t.acceptanceIds,e.acceptanceIds),actor:OR,issuedAt:(t.now??new Date).toISOString(),evidence:{steps:[...t.steps],observations:[...t.observations]}});return{receipt:i,ref:await Ol({paths:t.paths,name:t.state.name,receipt:i})}}function JR(t){return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...t.capture?{capture:t.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:t.complete,limits:t.limits,...t.policy?{policy:t.policy}:{},entries:t.entries,omitted:t.omitted,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:t.omissionOverflow}:{}}}var GR=20;function KR(t,e){let i=[],n=0,r=0,a=0;for(;r<t.entries.length||a<e.entries.length;){let o=t.entries[r],s=e.entries[a],c=o===void 0?1:s===void 0||o.path<s.path?-1:o.path>s.path?1:0,l=c<=0?o:void 0,u=c>=0?s:void 0;if(c<=0&&(r+=1),c>=0&&(a+=1),l&&u&&l.hash===u.hash&&l.size===u.size)continue;let f=l?.path??u?.path;f&&(n+=1,i.length<GR&&i.push({path:f,kind:l?u?"modified":"removed":"added"}))}return{changedPaths:i,changedPathCount:n,changedPathsTruncated:i.length!==n}}function xm(t,e,i){return{reason:i?"implementation-changed-during-command":"implementation-scope-stale",commandExecuted:i,expectedScopeHash:e.expectedScopeHash,actualScopeHash:e.actualScopeHash,expectedSnapshotHash:e.expectedSnapshotHash,actualSnapshotHash:e.actualSnapshotHash,changedPaths:e.changedPaths,changedPathCount:e.changedPathCount,changedPathsTruncated:e.changedPathsTruncated,requiredAction:"return-to-build-and-refresh-implementation-scope",nextCommand:`comet native next ${t} --summary "Implementation changed after Build; return to Build and refresh scope"`,requiresUserDecision:!1}}function UR(t,e){let i=xm(t,e,!1),n=i.changedPaths.map(r=>`${r.kind}: ${r.path}`).join(", ");return new xi(`Native receipt stopped before command execution because the implementation scope changed after Build${n?` (${n}${i.changedPathsTruncated?", ...":""})`:""}. Return to Build with \`${i.nextCommand}\`, re-freeze the implementation scope, and then issue fresh receipts.`,i)}async function Tm(t){let e=JR(t.context.scope.baseline),i=await Pc(t.paths,e,{origin:"explicit",now:t.now}),n=el({baseline:e,current:i,contractHash:t.context.bindings.contractHash,declaredArtifacts:t.context.scope.scope.declaredArtifacts,noCodeReason:t.context.scope.scope.noCodeReason,gitChangedPaths:t.context.scope.authority.gitChangedPaths}),r=KR(t.context.scope.current,n.current);return{expectedScopeHash:t.context.bindings.scopeHash,actualScopeHash:n.scope.scopeHash,expectedSnapshotHash:t.context.bindings.snapshotHash,actualSnapshotHash:n.scope.currentProjectionHash,matched:n.scope.currentProjectionHash===t.context.bindings.snapshotHash&&n.scope.scopeHash===t.context.bindings.scopeHash,...r}}async function ao(t){let e=t.context??await Wn(t.paths,t.state),i=await Tm({paths:t.paths,context:e});if(!i.matched)throw UR(t.state.name,i);return e}async function Rm(t){try{let[{stdout:e},{stdout:i}]=await Promise.all([Em("git",["-C",t,"rev-parse","--show-toplevel"],{windowsHide:!0,timeout:1e4}),Em("git",["-C",t,"rev-parse","HEAD"],{windowsHide:!0,timeout:1e4})]),n=Xe.resolve(e.trim()),r=Xe.relative(t,n).replaceAll("\\","/");if(r===".."||r.startsWith("../")||Xe.posix.isAbsolute(r))throw new Error("Git worktree is outside the Native project root");let a=i.trim().toLowerCase();if(!/^[a-f0-9]{40,64}$/u.test(a))throw new Error("Git commit identity is invalid");return{provider:"git",root:r||".",commit:a}}catch{return{provider:"none",root:".",commit:null}}}async function Im(t){return Pm({paths:t.paths,name:t.name,operation:`issue automated receipt ${t.name}`,issue:e=>YR({...t,state:e})})}async function YR(t){let e=await Wn(t.paths,t.state);await ao({paths:t.paths,state:t.state,context:e});let i=await Rm(t.paths.projectRoot),n=(t.now?.()??new Date).toISOString(),r=t.timeoutMs??_R;if(!Number.isSafeInteger(r)||r<1||r>Vn)throw new Error(`Native automated command timeout must be an integer from 1 through ${Vn}`);let a=[],o=0,s=0,c=TR("sha256"),l=!1,u=qR(t.command,t.args,{cwd:t.paths.projectRoot,env:{...process.env}}),f=g=>{if(c.update(g),s+=g.byteLength,o>=Ml)return;let y=Ml-o,w=g.subarray(0,y);a.push(Buffer.from(w)),o+=w.byteLength};u.stdout.on("data",f),u.stderr.on("data",f);let d=await new Promise((g,y)=>{let w=!1,R=null,_=null,D=F=>{w||(w=!0,clearTimeout(H),_&&clearTimeout(_),g(F))},H=setTimeout(()=>{l=!0,R=Wl(u).catch(()=>{u.kill("SIGKILL"),u.stdout?.destroy(),u.stderr?.destroy()}),_=setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),D({exitCode:124,signal:"SIGKILL"})},jR)},r);u.once("error",F=>{if(l){(R??Promise.resolve()).then(()=>D({exitCode:124,signal:"SIGKILL"}));return}w||(w=!0,clearTimeout(H),_&&clearTimeout(_),y(F))}),u.once("close",(F,z)=>{(R??Promise.resolve()).then(()=>D({exitCode:l?124:F??1,signal:z??(l?"SIGKILL":null)}))})}),p=(t.now?.()??new Date).toISOString(),[m,h]=await Promise.all([Rm(t.paths.projectRoot),Tm({paths:t.paths,context:e,now:t.now?.()})]),v=e.scope.current.capture,N=(!(v?.provider==="git"||v?.provider==="physical-tree"&&v.projection?.provider==="git")||i.provider==="git")&&i.provider===m.provider&&i.root===m.root&&i.commit===m.commit,E=l||!h.matched||!N?"blocked":d.exitCode===0?"passed":"failed",b=Buffer.concat(a,o).toString("utf8").trim(),k=Tl({kind:"automated-check",role:"acceptance-evidence",status:E,bindings:e.bindings,acceptanceIds:Am(t.acceptanceIds,e.acceptanceIds),actor:`native-runtime:command:${t.command}`,issuedAt:p,evidence:{executable:t.command,args:[...t.args],cwd:".",exitCode:d.exitCode,signal:d.signal,timedOut:l,timeoutMs:r,startedAt:n,endedAt:p,worktree:{provider:i.provider,root:i.root,beforeCommit:i.commit,afterCommit:m.commit},afterFence:{snapshotHash:h.actualSnapshotHash,scopeHash:h.actualScopeHash,matched:h.matched&&N},outputHash:c.digest("hex"),outputSummary:VR(xe(b||`(exit ${d.exitCode})`),"Native command output summary"),outputTruncated:s>o}});return{receipt:k,ref:await Ol({paths:t.paths,name:t.state.name,receipt:k}),...!h.matched||!N?{recovery:xm(t.state.name,h,!0)}:{}}}import XR from"node:path";var QR="Native receipt re-issued after revision bump";function ZR(t){return!t.ok&&t.mismatches.length===1&&t.mismatches[0]?.startsWith("sourceRevision: ")===!0}function eC(t){return t.kind!=="automated-check"?"<unknown automated receipt>":[t.evidence.executable,...t.evidence.args].map(i=>/\s/u.test(i)?JSON.stringify(i):i).join(" ")}function tC(t){return`${QR} to revision ${t}`}function iC(){return"Manual evidence re-issued via `comet native receipt refresh` to restore revision binding."}async function _m(t){let e=await ke(t.paths,t.name);if(e.phase!=="verify")throw new Error(`Native receipt refresh requires Verify, got ${e.phase} for ${t.name}`);let i=e.implementation_scope?await Wn(t.paths,e):null;if(i&&await ao({paths:t.paths,state:e,context:i}),!e.verification_evidence)return{refreshed:[],requiresRerun:[],requiresManual:[],requiresCheck:[],applied:!1,verificationReport:null};if(!i)throw new Error("Native receipt refresh requires an implementation scope");let n=await $l(t.paths,t.name,e.verification_evidence),r=[],a=[],o=[],s=[],c=new Set,l=[...new Set([...n.requiredReceiptRefs,...n.receiptRefs])];for(let k of l){let g=await no(t.paths,t.name,k),y=Ll(g,i.bindings);if(!y.ok)if(c.add(k),g.kind==="manual-evidence"){let w={oldRef:k,acceptanceIds:[...g.acceptanceIds]};ZR(y)?r.push(w):a.push({...w,mismatches:y.mismatches})}else g.kind==="automated-check"?o.push({oldRef:k,acceptanceIds:[...g.acceptanceIds],command:eC(g),timeoutMs:g.evidence.timeoutMs}):g.kind==="static-inspection"&&s.push({oldRef:k})}if(!(t.apply&&o.length===0&&a.length===0&&r.length>0))return{refreshed:[],requiresRerun:o,requiresManual:a,requiresCheck:s,applied:!1,verificationReport:e.verification_report};let f=[],d=new Map,p=new Map;for(let k of r){let g=[...k.acceptanceIds].sort().join(`
|
|
175
|
+
`),y=p.get(g);y?y.push(k.oldRef):p.set(g,[k.oldRef])}for(let[k,g]of p){let y=k.split(`
|
|
176
|
+
`),w=await ro({paths:t.paths,name:t.name,acceptanceIds:y,steps:[tC(e.revision)],observations:[iC()]});for(let R of y)d.set(R,w.ref);for(let R of g){let _=r.find(D=>D.oldRef===R)?.acceptanceIds[0];_&&f.push({acceptanceId:_,oldRef:R,newRef:w.ref})}}let m=e.verification_report;if(!m)throw new Error(`Native receipt refresh cannot rewrite verification report: ${t.name} has no report ref`);let h=Y(t.paths,t.name),v=await Re({root:h,ref:m}),S=Pl(v.text),N=nC(n.acceptanceTrace.entries,S,c,d),E=cm(N),b=rC(v.text,E);return await et(XR.join(h,...m.split("/")),b),{refreshed:f,requiresRerun:[],requiresManual:[],requiresCheck:s,applied:!0,verificationReport:m}}function nC(t,e,i,n){let r=new Map;for(let o of e)r.set(o.acceptance_id,o);let a=[];for(let o of t){let s=r.get(o.acceptanceId);if(!s)continue;if(o.status==="failed"){a.push(s);continue}let c=s.evidence_refs.filter(d=>!i.has(d)),l=n.get(o.acceptanceId),u=l!==void 0?[...c,l]:c;if(u.length===0){a.push(s);continue}let f={acceptance_id:s.acceptance_id,status:s.status,evidence_refs:[...new Set(u)].sort()};s.skipped_reason!==void 0&&(f.skipped_reason=s.skipped_reason),a.push(f)}return a}function rC(t,e){let i=t.indexOf(Fn);if(i<0)throw new Error("Native verification report is missing the acceptance-evidence start marker");let n=t.indexOf(Ri,i);if(n<0)throw new Error("Native verification report is missing the acceptance-evidence end marker");let r=t.slice(0,i),a=t.slice(n+Ri.length);return`${r}${e}${a}`}import dC from"path";var oC=["Outcome","Scope","Non-goals","Acceptance examples"],OO=[...oC,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var sC=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 oo=class extends Error{details;constructor(e){let i=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(n=>`${n.ref}${n.acceptanceId?`[${n.acceptanceId}]`:""} -> ${n.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=e}};var E0={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var O0=16*1024*1024,$0=256*1024,H0=16*1024;var F0=16*1024;var Y0=16*1024;var M$=16*1024*1024,so=class extends Error{constructor(i,n,r,a){super(`Canonical spec conflict for ${i}: expected ${n??"(missing)"}, actual ${r??"(missing)"}`);this.capability=i;this.expectedHash=n;this.actualHash=r;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},co=class extends Error{constructor(i,n=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(n);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var G$=10*1024*1024,ge=class extends Error{};function zn(t,e){let i=t.flatMap((n,r)=>n===e?[r]:[]);if(i.length>1)throw new ge(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function lo(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new ge(`${e} may only be provided once`);if(i.length===0)return;let n=i[0],r=t[n+1];if(r===void 0||r.startsWith("--"))throw new ge(`${e} requires a value`);return t.splice(n,2),r}function Jn(t,e){let i=[];for(let n=0;n<t.length;){if(t[n]!==e){n+=1;continue}let r=t[n+1];if(r===void 0||r.startsWith("--"))throw new ge(`${e} requires a value`);i.push(r),t.splice(n,2)}return i}function uo(t){if(t.length>0)throw new ge(`Unexpected argument: ${t[0]}`)}function Fl(t,e){let i=t.shift();if(!i||i.startsWith("--"))throw new ge(`${e} is required`);return i}async function jm(t){return t?dC.resolve(t):sa(process.cwd())}async function Om(t){let e=await Jd({startPath:t,allowMissingConfig:!1});return{config:e.config,paths:e.paths}}function Bl(t,e,i){return{command:t,exitCode:0,data:e,text:i??JSON.stringify(e,null,2)+`
|
|
177
|
+
`}}function $m(t,e){if(e instanceof ge)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof so)return{command:t,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof co)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof xn)return{command:t,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof Ta)return{command:t,exitCode:73,data:{requestedIsolation:e.requestedIsolation,activeChanges:e.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:e.message}};if(e instanceof Ia)return{command:t,exitCode:65,data:{change:e.change,complete:!1,omittedCount:e.omittedCount,omittedByReason:e.omittedByReason,samplePaths:e.samplePaths,sampleTruncated:e.sampleTruncated,effectiveLimits:e.effectiveLimits,policyHash:e.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:e.message}};if(e instanceof oo)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof xi)return{command:t,exitCode:65,data:e.recovery,error:{code:"implementation-scope-stale",message:e.message}};if(e instanceof Error){let i=e.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:t,exitCode:70,error:{code:"internal",message:e.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function Hm(t,e){return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
|
|
178
|
+
`}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function Mm(t,e){let i=Fl(t,"receipt subcommand"),n=Fl(t,"change name"),{paths:r}=await Om(e);if(i==="manual"){let a=Jn(t,"--acceptance"),o=Jn(t,"--step"),s=Jn(t,"--observation");uo(t);let c=await ro({paths:r,name:n,acceptanceIds:a,steps:o,observations:s});return Bl("receipt manual",c,`Native manual receipt: ${c.ref}
|
|
179
|
+
`)}if(i==="automated"){let a=t.indexOf("--");if(a<0||a===t.length-1)throw new ge("receipt automated requires -- <executable> [args...]");let o=t.splice(a+1);t.splice(a,1);let s=Jn(t,"--acceptance"),c=lo(t,"--timeout-ms");uo(t);let l=c===void 0?void 0:/^[1-9]\d*$/u.test(c)&&Number.isSafeInteger(Number(c))&&Number(c)<=Vn?Number(c):null;if(l===null)throw new ge(`--timeout-ms must be an integer from 1 through ${Vn}`);let u=await Im({paths:r,name:n,acceptanceIds:s,command:o[0],args:o.slice(1),...l===void 0?{}:{timeoutMs:l}}),f=[`Native automated receipt ${u.receipt.status}: ${u.ref}`];if(u.recovery){let d=u.recovery.changedPaths.map(p=>` ${p.kind}: ${p.path}`).join(`
|
|
180
|
+
`);f.push("Implementation changed while the verification command was running."),d&&f.push(d),u.recovery.changedPathsTruncated&&f.push(` ... ${u.recovery.changedPathCount-u.recovery.changedPaths.length} more path(s)`),f.push(`Recover with: ${u.recovery.nextCommand}`)}return{command:"receipt automated",exitCode:u.receipt.status==="passed"?0:1,data:u,text:`${f.join(`
|
|
175
181
|
`)}
|
|
176
|
-
`)
|
|
177
|
-
`
|
|
182
|
+
`}}if(i==="refresh"){let a=zn(t,"--apply"),o=zn(t,"--dry-run");if(uo(t),a&&o)throw new ge("receipt refresh --apply and --dry-run cannot be combined");let s=await _m({paths:r,name:n,apply:a}),c=[];if(s.refreshed.length>0){c.push(`Re-issued ${s.refreshed.length} manual receipt(s) at the current revision:`);for(let l of s.refreshed)c.push(` ${l.acceptanceId}: ${l.oldRef} -> ${l.newRef}`)}if(s.requiresRerun.length>0){c.push(`Re-run ${s.requiresRerun.length} stale automated receipt(s) (they cannot be re-issued without a real execution):`);for(let l of s.requiresRerun){let u=l.acceptanceIds.join(", ");c.push(` [${u}] ${l.command}`)}}if(s.requiresManual.length>0){c.push(`Re-run manual verification for ${s.requiresManual.length} receipt(s); contract, scope, snapshot, or artifact bindings changed:`);for(let l of s.requiresManual)c.push(` [${l.acceptanceIds.join(", ")}] ${l.mismatches.join("; ")}`)}return s.requiresCheck.length>0&&c.push(`Re-run \`comet native check ${n}\` to refresh ${s.requiresCheck.length} required-check receipt(s).`),s.applied?c.push(`Updated acceptance evidence in ${s.verificationReport}.`):s.refreshed.length===0&&s.requiresRerun.length===0&&s.requiresManual.length===0&&s.requiresCheck.length===0?c.push("No stale receipts found."):a?s.requiresManual.length>0&&c.push("Fresh manual verification is required before these receipts can be refreshed."):c.push("Dry run only. Re-run with --apply to re-issue manual receipts."),Bl("receipt refresh",s,`${c.join(`
|
|
183
|
+
`)}
|
|
184
|
+
`)}throw new ge(`Unknown receipt command: ${i}`)}function hC(t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
|
|
185
|
+
`}}async function Lm(t,e,i=process.argv.slice(2)){let n=i.indexOf("--"),r=n<0?[...i]:i.slice(0,n),a=n<0?[]:i.slice(n),o=r.includes("--json"),s,c;try{zn(r,"--json"),s=lo(r,"--project-root");let u=[...r,...a],f=await jm(s);c=await e(u,f)}catch(u){c=$m(t,u)}let l=o?hC(c):Hm(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
|
|
178
186
|
`)?"":`
|
|
179
|
-
`)),l.exitCode}process.exitCode=await
|
|
187
|
+
`)),l.exitCode}process.exitCode=await Lm("receipt",Mm);
|