@rpamis/comet 0.4.0-beta.14 → 0.4.0-beta.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +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 +85 -85
- package/assets/skills/comet/scripts/comet-guard.mjs +111 -111
- package/assets/skills/comet/scripts/comet-handoff.mjs +85 -85
- 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 +77 -77
- 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 +95 -95
- 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 +138 -37
- 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-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-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-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 +15 -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 +16 -16
- 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/pyproject.toml +4 -4
- package/eval/scaffold/shell/docker.sh +5 -0
- package/package.json +1 -1
- 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,173 +1,179 @@
|
|
|
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 Fm=Object.create;var jl=Object.defineProperty;var Lm=Object.getOwnPropertyDescriptor;var Mm=Object.getOwnPropertyNames;var Bm=Object.getPrototypeOf,Dm=Object.prototype.hasOwnProperty;var nr=(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 R=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(i){throw e=0,i}};var qm=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Mm(e))!Dm.call(t,r)&&r!==i&&jl(t,r,{get:()=>e[r],enumerable:!(n=Lm(e,r))||n.enumerable});return t};var wo=(t,e,i)=>(i=t!=null?Fm(Bm(t)):{},qm(e||!t||!t.__esModule?jl(i,"default",{value:t,enumerable:!0}):i,t));var $=R(se=>{"use strict";var yo=Symbol.for("yaml.alias"),Hl=Symbol.for("yaml.document"),rr=Symbol.for("yaml.map"),$l=Symbol.for("yaml.pair"),No=Symbol.for("yaml.scalar"),ar=Symbol.for("yaml.seq"),et=Symbol.for("yaml.node.type"),Vm=t=>!!t&&typeof t=="object"&&t[et]===yo,Wm=t=>!!t&&typeof t=="object"&&t[et]===Hl,zm=t=>!!t&&typeof t=="object"&&t[et]===rr,Jm=t=>!!t&&typeof t=="object"&&t[et]===$l,Fl=t=>!!t&&typeof t=="object"&&t[et]===No,Gm=t=>!!t&&typeof t=="object"&&t[et]===ar;function Ll(t){if(t&&typeof t=="object")switch(t[et]){case rr:case ar:return!0}return!1}function Km(t){if(t&&typeof t=="object")switch(t[et]){case yo:case rr:case No:case ar:return!0}return!1}var Um=t=>(Fl(t)||Ll(t))&&!!t.anchor;se.ALIAS=yo;se.DOC=Hl;se.MAP=rr;se.NODE_TYPE=et;se.PAIR=$l;se.SCALAR=No;se.SEQ=ar;se.hasAnchor=Um;se.isAlias=Vm;se.isCollection=Ll;se.isDocument=Wm;se.isMap=zm;se.isNode=Km;se.isPair=Jm;se.isScalar=Fl;se.isSeq=Gm});var $i=R(bo=>{"use strict";var oe=$(),me=Symbol("break visit"),Ml=Symbol("skip children"),Je=Symbol("remove node");function or(t,e){let i=Bl(e);oe.isDocument(t)?li(null,t.contents,i,Object.freeze([t]))===Je&&(t.contents=null):li(null,t,i,Object.freeze([]))}or.BREAK=me;or.SKIP=Ml;or.REMOVE=Je;function li(t,e,i,n){let r=Dl(t,e,i,n);if(oe.isNode(r)||oe.isPair(r))return ql(t,n,r),li(t,r,i,n);if(typeof r!="symbol"){if(oe.isCollection(e)){n=Object.freeze(n.concat(e));for(let a=0;a<e.items.length;++a){let o=li(a,e.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===me)return me;o===Je&&(e.items.splice(a,1),a-=1)}}}else if(oe.isPair(e)){n=Object.freeze(n.concat(e));let a=li("key",e.key,i,n);if(a===me)return me;a===Je&&(e.key=null);let o=li("value",e.value,i,n);if(o===me)return me;o===Je&&(e.value=null)}}return r}async function sr(t,e){let i=Bl(e);oe.isDocument(t)?await ui(null,t.contents,i,Object.freeze([t]))===Je&&(t.contents=null):await ui(null,t,i,Object.freeze([]))}sr.BREAK=me;sr.SKIP=Ml;sr.REMOVE=Je;async function ui(t,e,i,n){let r=await Dl(t,e,i,n);if(oe.isNode(r)||oe.isPair(r))return ql(t,n,r),ui(t,r,i,n);if(typeof r!="symbol"){if(oe.isCollection(e)){n=Object.freeze(n.concat(e));for(let a=0;a<e.items.length;++a){let o=await ui(a,e.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===me)return me;o===Je&&(e.items.splice(a,1),a-=1)}}}else if(oe.isPair(e)){n=Object.freeze(n.concat(e));let a=await ui("key",e.key,i,n);if(a===me)return me;a===Je&&(e.key=null);let o=await ui("value",e.value,i,n);if(o===me)return me;o===Je&&(e.value=null)}}return r}function Bl(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 Dl(t,e,i,n){if(typeof i=="function")return i(t,e,n);if(oe.isMap(e))return i.Map?.(t,e,n);if(oe.isSeq(e))return i.Seq?.(t,e,n);if(oe.isPair(e))return i.Pair?.(t,e,n);if(oe.isScalar(e))return i.Scalar?.(t,e,n);if(oe.isAlias(e))return i.Alias?.(t,e,n)}function ql(t,e,i){let n=e[e.length-1];if(oe.isCollection(n))n.items[t]=i;else if(oe.isPair(n))t==="key"?n.key=i:n.value=i;else if(oe.isDocument(n))n.contents=i;else{let r=oe.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}bo.visit=or;bo.visitAsync=sr});var ko=R(Wl=>{"use strict";var Vl=$(),Ym=$i(),Xm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Qm=t=>t.replace(/[!,[\]{}]/g,e=>Xm[e]),Fi=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+Qm(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&&Vl.isNode(e.contents)){let a={};Ym.visit(e.contents,(o,s)=>{Vl.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
|
+
`)}};Fi.defaultYaml={explicit:!1,version:"1.2"};Fi.defaultTags={"!!":"tag:yaml.org,2002:"};Wl.Directives=Fi});var cr=R(Li=>{"use strict";var zl=$(),Zm=$i();function ev(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 Jl(t){let e=new Set;return Zm.visit(t,{Value(i,n){n.anchor&&e.add(n.anchor)}}),e}function Gl(t,e){for(let i=1;;++i){let n=`${t}${i}`;if(!e.has(n))return n}}function tv(t,e){let i=[],n=new Map,r=null;return{onAnchor:a=>{i.push(a),r??(r=Jl(t));let o=Gl(e,r);return r.add(o),o},setAnchors:()=>{for(let a of i){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(zl.isScalar(o.node)||zl.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}}Li.anchorIsValid=ev;Li.anchorNames=Jl;Li.createNodeAnchors=tv;Li.findNewAnchor=Gl});var So=R(Kl=>{"use strict";function Mi(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=Mi(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=Mi(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=Mi(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=Mi(t,n,r,a);o===void 0?delete n[r]:o!==a&&(n[r]=o)}return t.call(e,i,n)}Kl.applyReviver=Mi});var ht=R(Yl=>{"use strict";var iv=$();function Ul(t,e,i){if(Array.isArray(t))return t.map((n,r)=>Ul(n,String(r),i));if(t&&typeof t.toJSON=="function"){if(!i||!iv.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}Yl.toJS=Ul});var lr=R(Ql=>{"use strict";var nv=So(),Xl=$(),rv=ht(),Eo=class{constructor(e){Object.defineProperty(this,Xl.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(!Xl.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=rv.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof a=="function"?nv.applyReviver(a,{"":s},"",s):s}};Ql.NodeBase=Eo});var Bi=R(Zl=>{"use strict";var av=cr(),ov=$i(),fi=$(),sv=lr(),cv=ht(),Co=class extends sv.NodeBase{constructor(e){super(fi.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=[],ov.visit(e,{Node:(a,o)=>{(fi.isAlias(o)||fi.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||(cv.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=ur(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(av.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 ur(t,e,i){if(fi.isAlias(e)){let n=e.resolve(t),r=i&&n&&i.get(n);return r?r.count*r.aliasCount:0}else if(fi.isCollection(e)){let n=0;for(let r of e.items){let a=ur(t,r,i);a>n&&(n=a)}return n}else if(fi.isPair(e)){let n=ur(t,e.key,i),r=ur(t,e.value,i);return Math.max(n,r)}return 1}Zl.Alias=Co});var ie=R(Ro=>{"use strict";var lv=$(),uv=lr(),fv=ht(),dv=t=>!t||typeof t!="function"&&typeof t!="object",pt=class extends uv.NodeBase{constructor(e){super(lv.SCALAR),this.value=e}toJSON(e,i){return i?.keep?this.value:fv.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";Ro.Scalar=pt;Ro.isScalarValue=dv});var Di=R(tu=>{"use strict";var hv=Bi(),Lt=$(),eu=ie(),pv="tag:yaml.org,2002:";function mv(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 vv(t,e,i){if(Lt.isDocument(t)&&(t=t.contents),Lt.isNode(t))return t;if(Lt.isPair(t)){let u=i.schema[Lt.MAP].createNode?.(i.schema,null,i);return u.items.push(t),u}(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 hv.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=pv+e.slice(2));let l=mv(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new eu.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[Lt.MAP]:Symbol.iterator in Object(t)?o[Lt.SEQ]:o[Lt.MAP]}a&&(a(l),delete i.onTagObj);let f=l?.createNode?l.createNode(i.schema,t,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,t,i):new eu.Scalar(t);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}tu.createNode=vv});var dr=R(fr=>{"use strict";var gv=Di(),Ge=$(),wv=lr();function Po(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 gv.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 iu=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Ao=class extends wv.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=>Ge.isNode(n)||Ge.isPair(n)?n.clone(e):n),this.range&&(i.range=this.range.slice()),i}addIn(e,i){if(iu(e))this.add(i);else{let[n,...r]=e,a=this.get(n,!0);if(Ge.isCollection(a))a.addIn(r,i);else if(a===void 0&&this.schema)this.set(n,Po(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(Ge.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&&Ge.isScalar(a)?a.value:a:Ge.isCollection(a)?a.getIn(r,i):void 0}hasAllNullValues(e){return this.items.every(i=>{if(!Ge.isPair(i))return!1;let n=i.value;return n==null||e&&Ge.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 Ge.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(Ge.isCollection(a))a.setIn(r,i);else if(a===void 0&&this.schema)this.set(n,Po(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};fr.Collection=Ao;fr.collectionFromPath=Po;fr.isEmptyPath=iu});var qi=R(hr=>{"use strict";var yv=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function xo(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Nv=(t,e,i)=>t.endsWith(`
|
|
6
|
+
`)?xo(i,e):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)i===
|
|
8
|
+
`+xo(i,e):(t.endsWith(" ")?"":" ")+i;hr.indentComment=xo;hr.lineComment=Nv;hr.stringifyComment=yv});var ru=R(Vi=>{"use strict";var bv="flow",To="block",pr="quoted";function kv(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=[],f={},u=r-e.length;typeof n=="number"&&(n>r-Math.max(2,a)?l.push(0):u=r-n);let d,p,m=!1,h=-1,v=-1,b=-1;i===To&&(h=nu(t,h,e.length),h!==-1&&(u=h+c));for(let y;y=t[h+=1];){if(i===pr&&y==="\\"){switch(v=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}b=h}if(y===`
|
|
9
|
+
`)i===To&&(h=nu(t,h,e.length)),u=h+e.length+c,d=void 0;else{if(y===" "&&p&&p!==" "&&p!==`
|
|
10
10
|
`&&p!==" "){let w=t[h+1];w&&w!==" "&&w!==`
|
|
11
|
-
`&&w!==" "&&(d=h)}if(h>=u)if(d)l.push(d),u=d+c,d=void 0;else if(i===
|
|
12
|
-
${e}${t.slice(0,
|
|
13
|
-
${e}${t.slice(w+1,
|
|
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
|
|
11
|
+
`&&w!==" "&&(d=h)}if(h>=u)if(d)l.push(d),u=d+c,d=void 0;else if(i===pr){for(;p===" "||p===" ";)p=y,y=t[h+=1],m=!0;let w=h>b+1?h-2:v-1;if(f[w])return t;l.push(w),f[w]=!0,u=w+c,d=void 0}else m=!0}p=y}if(m&&s&&s(),l.length===0)return t;o&&o();let N=t.slice(0,l[0]);for(let y=0;y<l.length;++y){let w=l[y],E=l[y+1]||t.length;w===0?N=`
|
|
12
|
+
${e}${t.slice(0,E)}`:(i===pr&&f[w]&&(N+=`${t[w]}\\`),N+=`
|
|
13
|
+
${e}${t.slice(w+1,E)}`)}return N}function nu(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}Vi.FOLD_BLOCK=To;Vi.FOLD_FLOW=bv;Vi.FOLD_QUOTED=pr;Vi.foldFlowLines=kv});var zi=R(au=>{"use strict";var _e=ie(),mt=ru(),vr=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),gr=t=>/^(%|---|\.\.\.)/m.test(t);function Sv(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 Wi(t,e){let i=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return i;let{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(gr(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 f=i.substr(c+2,4);switch(f){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:f.substr(0,2)==="00"?o+="\\x"+f.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,vr(e,!1))}function Io(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(t))return Wi(t,e);let i=e.indent||(gr(t)?" ":""),n="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return e.implicitKey?n:mt.foldFlowLines(n,i,mt.FOLD_FLOW,vr(e,!1))}function di(t,e){let{singleQuote:i}=e.options,n;if(i===!1)n=Wi;else{let r=t.includes('"'),a=t.includes("'");r&&!a?n=Io:a&&!r?n=Wi:n=i?Io:Wi}return n(t,e)}var _o;try{_o=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{_o=/\n+(?!\n|$)/g}function mr({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 di(i,n);let l=n.indent||(n.forceBlockIndent||gr(i)?" ":""),f=o==="literal"?!0:o==="folded"||e===_e.Scalar.BLOCK_FOLDED?!1:e===_e.Scalar.BLOCK_LITERAL?!0:!Sv(i,c,l.length);if(!i)return f?`|
|
|
24
24
|
`:`>
|
|
25
|
-
`;let u,d;for(d=i.length;d>0;--d){let
|
|
26
|
-
`&&
|
|
25
|
+
`;let u,d;for(d=i.length;d>0;--d){let E=i[d-1];if(E!==`
|
|
26
|
+
`&&E!==" "&&E!==" ")break}let p=i.substring(d),m=p.indexOf(`
|
|
27
27
|
`);m===-1?u="-":i===p||m!==p.length-1?(u="+",a&&a()):u="",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
|
-
`)||f&&/[[\]{},]/.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(u),{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
|
-
${
|
|
28
|
+
`&&(p=p.slice(0,-1)),p=p.replace(_o,`$&${l}`));let h=!1,v,b=-1;for(v=0;v<i.length;++v){let E=i[v];if(E===" ")h=!0;else if(E===`
|
|
29
|
+
`)b=v;else break}let N=i.substring(0,b<v?b+1:v);N&&(i=i.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let w=(h?l?"2":"1":"")+u;if(t&&(w+=" "+s(t.replace(/ ?[\r\n]+/g," ")),r&&r()),!f){let E=i.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,S=vr(n,!0);o!=="folded"&&e!==_e.Scalar.BLOCK_FOLDED&&(S.onOverflow=()=>{g=!0});let k=mt.foldFlowLines(`${N}${E}${p}`,l,mt.FOLD_BLOCK,S);if(!g)return`>${w}
|
|
31
|
+
${l}${k}`}return i=i.replace(/\n+/g,`$&${l}`),`|${w}
|
|
32
|
+
${l}${N}${i}${p}`}function Ev(t,e,i,n){let{type:r,value:a}=t,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=e;if(s&&a.includes(`
|
|
33
|
+
`)||f&&/[[\]{},]/.test(a))return di(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
|
|
34
|
+
`)?di(a,e):mr(t,e,i,n);if(!s&&!f&&r!==_e.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return mr(t,e,i,n);if(gr(a)){if(c==="")return e.forceBlockIndent=!0,mr(t,e,i,n);if(s&&c===l)return di(a,e)}let u=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:p,tags:m}=e.doc.schema;if(m.some(d)||p?.some(d))return di(a,e)}return s?u:mt.foldFlowLines(u,c,mt.FOLD_FLOW,vr(e,!1))}function Cv(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!==_e.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=_e.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case _e.Scalar.BLOCK_FOLDED:case _e.Scalar.BLOCK_LITERAL:return r||a?di(o.value,e):mr(o,e,i,n);case _e.Scalar.QUOTE_DOUBLE:return Wi(o.value,e);case _e.Scalar.QUOTE_SINGLE:return Io(o.value,e);case _e.Scalar.PLAIN:return Ev(o,e,i,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=r&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}au.stringifyString=Cv});var Ji=R(Oo=>{"use strict";var Rv=cr(),vt=$(),Pv=qi(),Av=zi();function xv(t,e){let i=Object.assign({blockQuote:!0,commentString:Pv.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 Tv(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 Iv(t,e,{anchors:i,doc:n}){if(!n.directives)return"";let r=[],a=(vt.isScalar(t)||vt.isCollection(t))&&t.anchor;a&&Rv.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 _v(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=Tv(e.doc.schema.tags,a));let o=Iv(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)?Av.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}Oo.createStringifyContext=xv;Oo.stringify=_v});var lu=R(cu=>{"use strict";var tt=$(),ou=ie(),su=Ji(),Gi=qi();function Ov({key:t,value:e},i,n,r){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=i,d=tt.isNode(t)&&t.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(tt.isCollection(t)||!tt.isNode(t)&&typeof t=="object"){let S="With simple keys, collection cannot be used as a key value";throw new Error(S)}}let p=!u&&(!t||d&&e==null&&!i.inFlow||tt.isCollection(t)||(tt.isScalar(t)?t.type===ou.Scalar.BLOCK_FOLDED||t.type===ou.Scalar.BLOCK_LITERAL:typeof t=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(u||!a),indent:s+c});let m=!1,h=!1,v=su.stringify(t,i,()=>m=!0,()=>h=!0);if(!p&&!i.inFlow&&v.length>1024){if(u)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&&!u||e==null&&p)return v=`? ${v}`,d&&!m?v+=Gi.lineComment(v,i.indent,l(d)):h&&r&&r(),v;m&&(d=null),p?(d&&(v+=Gi.lineComment(v,i.indent,l(d))),v=`? ${v}
|
|
38
|
+
${s}:`):(v=`${v}:`,d&&(v+=Gi.lineComment(v,i.indent,l(d))));let b,N,y;tt.isNode(e)?(b=!!e.spaceBefore,N=e.commentBefore,y=e.comment):(b=!1,N=null,y=null,e&&typeof e=="object"&&(e=o.createNode(e))),i.implicitKey=!1,!p&&!d&&tt.isScalar(e)&&(i.indentAtStart=v.length+1),h=!1,!f&&c.length>=2&&!i.inFlow&&!p&&tt.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(i.indent=i.indent.substring(2));let w=!1,E=su.stringify(e,i,()=>w=!0,()=>h=!0),g=" ";if(d||b||N){if(g=b?`
|
|
39
|
+
`:"",N){let S=l(N);g+=`
|
|
40
|
+
${Gi.indentComment(S,i.indent)}`}E===""&&!i.inFlow?g===`
|
|
41
41
|
`&&y&&(g=`
|
|
42
42
|
|
|
43
43
|
`):g+=`
|
|
44
|
-
${i.indent}`}else if(!p&&
|
|
45
|
-
`),C=
|
|
46
|
-
${i.indent}`)}}else(
|
|
47
|
-
`)&&(g="");return v+=g+
|
|
44
|
+
${i.indent}`}else if(!p&&tt.isCollection(e)){let S=E[0],k=E.indexOf(`
|
|
45
|
+
`),C=k!==-1,B=i.inFlow??e.flow??e.items.length===0;if(C||!B){let G=!1;if(C&&(S==="&"||S==="!")){let M=E.indexOf(" ");S==="&"&&M!==-1&&M<k&&E[M+1]==="!"&&(M=E.indexOf(" ",M+1)),(M===-1||k<M)&&(G=!0)}G||(g=`
|
|
46
|
+
${i.indent}`)}}else(E===""||E[0]===`
|
|
47
|
+
`)&&(g="");return v+=g+E,i.inFlow?w&&n&&n():y&&!w?v+=Gi.lineComment(v,i.indent,l(y)):h&&r&&r(),v}cu.stringifyPair=Ov});var Ho=R(jo=>{"use strict";var uu=nr("process");function jv(t,...e){t==="debug"&&console.log(...e)}function Hv(t,e){(t==="debug"||t==="warn")&&(typeof uu.emitWarning=="function"?uu.emitWarning(e):console.warn(e))}jo.debug=jv;jo.warn=Hv});var kr=R(br=>{"use strict";var Nr=$(),fu=ie(),wr="<<",yr={identify:t=>t===wr||typeof t=="symbol"&&t.description===wr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new fu.Scalar(Symbol(wr)),{addToJSMap:du}),stringify:()=>wr},$v=(t,e)=>(yr.identify(e)||Nr.isScalar(e)&&(!e.type||e.type===fu.Scalar.PLAIN)&&yr.identify(e.value))&&t?.doc.schema.tags.some(i=>i.tag===yr.tag&&i.default);function du(t,e,i){let n=hu(t,i);if(Nr.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=hu(t,i);if(!Nr.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 hu(t,e){return t&&Nr.isAlias(e)?e.resolve(t.doc,t):e}br.addMergeToJSMap=du;br.isMergeKey=$v;br.merge=yr});var Lo=R(vu=>{"use strict";var Fv=Ho(),pu=kr(),Lv=Ji(),mu=$(),Fo=ht();function Mv(t,e,{key:i,value:n}){if(mu.isNode(i)&&i.addToJSMap)i.addToJSMap(t,e,n);else if(pu.isMergeKey(t,i))pu.addMergeToJSMap(t,e,n);else{let r=Fo.toJS(i,"",t);if(e instanceof Map)e.set(r,Fo.toJS(n,r,t));else if(e instanceof Set)e.add(r);else{let a=Bv(i,r,t),o=Fo.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 Bv(t,e,i){if(e===null)return"";if(typeof e!="object")return String(e);if(mu.isNode(t)&&i?.doc){let n=Lv.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)+'..."'),Fv.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)}vu.addPairToJSMap=Mv});var gt=R(Mo=>{"use strict";var gu=Di(),Dv=lu(),qv=Lo(),Sr=$();function Vv(t,e,i){let n=gu.createNode(t,void 0,i),r=gu.createNode(e,void 0,i);return new Er(n,r)}var Er=class t{constructor(e,i=null){Object.defineProperty(this,Sr.NODE_TYPE,{value:Sr.PAIR}),this.key=e,this.value=i}clone(e){let{key:i,value:n}=this;return Sr.isNode(i)&&(i=i.clone(e)),Sr.isNode(n)&&(n=n.clone(e)),new t(i,n)}toJSON(e,i){let n=i?.mapAsMap?new Map:{};return qv.addPairToJSMap(i,n,this)}toString(e,i,n){return e?.doc?Dv.stringifyPair(this,e,i,n):JSON.stringify(this)}};Mo.Pair=Er;Mo.createPair=Vv});var Bo=R(yu=>{"use strict";var Mt=$(),wu=Ji(),Cr=qi();function Wv(t,e,i){return(e.inFlow??t.flow?Jv:zv)(t,e,i)}function zv({comment:t,items:e},i,{blockItemPrefix:n,flowChars:r,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,f=Object.assign({},i,{indent:a,type:null}),u=!1,d=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(Mt.isNode(h))!u&&h.spaceBefore&&d.push(""),Rr(i,d,h.commentBefore,u),h.comment&&(v=h.comment);else if(Mt.isPair(h)){let N=Mt.isNode(h.key)?h.key:null;N&&(!u&&N.spaceBefore&&d.push(""),Rr(i,d,N.commentBefore,u))}u=!1;let b=wu.stringify(h,f,()=>v=null,()=>u=!0);v&&(b+=Cr.lineComment(b,a,l(v))),u&&v&&(u=!1),d.push(n+b)}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
|
+
`+Cr.indentComment(l(t),c),s&&s()):u&&o&&o(),p}function Jv({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,f=0,u=[];for(let m=0;m<t.length;++m){let h=t[m],v=null;if(Mt.isNode(h))h.spaceBefore&&u.push(""),Rr(e,u,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&&u.push(""),Rr(e,u,N.commentBefore,!1),N.comment&&(l=!0));let y=Mt.isNode(h.value)?h.value:null;y?(y.comment&&(v=y.comment),y.commentBefore&&(l=!0)):h.value==null&&N?.comment&&(v=N.comment)}v&&(l=!0);let b=wu.stringify(h,c,()=>v=null);l||(l=u.length>f||b.includes(`
|
|
51
|
+
`)),m<t.length-1?b+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=u.reduce((N,y)=>N+y.length+2,2)+(b.length+2)>e.options.lineWidth)),l&&(b+=",")),v&&(b+=Cr.lineComment(b,n,s(v))),u.push(b),f=u.length}let{start:d,end:p}=i;if(u.length===0)return d+p;if(!l){let m=u.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 u)m+=h?`
|
|
52
52
|
${a}${r}${h}`:`
|
|
53
53
|
`;return`${m}
|
|
54
|
-
${r}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function
|
|
55
|
-
`:" ")}return
|
|
54
|
+
${r}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function Rr({indent:t,options:{commentString:e}},i,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let a=Cr.indentComment(e(n),t);i.push(a.trimStart())}}yu.stringifyCollection=Wv});var yt=R(qo=>{"use strict";var Gv=Bo(),Kv=Lo(),Uv=dr(),wt=$(),Pr=gt(),Yv=ie();function Ki(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 Do=class extends Uv.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(Pr.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 Pr.Pair(e,e?.value):n=new Pr.Pair(e.key,e.value);let r=Ki(this.items,n.key),a=this.schema?.sortMapEntries;if(r){if(!i)throw new Error(`Key ${n.key} already set`);wt.isScalar(r.value)&&Yv.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=Ki(this.items,e);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(e,i){let r=Ki(this.items,e)?.value;return(!i&&wt.isScalar(r)?r.value:r)??void 0}has(e){return!!Ki(this.items,e)}set(e,i){this.add(new Pr.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)Kv.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})),Gv.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:i})}};qo.YAMLMap=Do;qo.findPair=Ki});var hi=R(bu=>{"use strict";var Xv=$(),Nu=yt(),Qv={collection:"map",default:!0,nodeClass:Nu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return Xv.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,i)=>Nu.YAMLMap.from(t,e,i)};bu.map=Qv});var Nt=R(ku=>{"use strict";var Zv=Di(),eg=Bo(),tg=dr(),xr=$(),ig=ie(),ng=ht(),Vo=class extends tg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(xr.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let i=Ar(e);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(e,i){let n=Ar(e);if(typeof n!="number")return;let r=this.items[n];return!i&&xr.isScalar(r)?r.value:r}has(e){let i=Ar(e);return typeof i=="number"&&i<this.items.length}set(e,i){let n=Ar(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let r=this.items[n];xr.isScalar(r)&&ig.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(ng.toJS(a,String(r++),i));return n}toString(e,i,n){return e?eg.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(Zv.createNode(s,void 0,n))}}return a}};function Ar(t){let e=xr.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}ku.YAMLSeq=Vo});var pi=R(Eu=>{"use strict";var rg=$(),Su=Nt(),ag={collection:"seq",default:!0,nodeClass:Su.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return rg.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,i)=>Su.YAMLSeq.from(t,e,i)};Eu.seq=ag});var Ui=R(Cu=>{"use strict";var og=zi(),sg={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),og.stringifyString(t,e,i,n)}};Cu.string=sg});var Tr=R(Au=>{"use strict";var Ru=ie(),Pu={identify:t=>t==null,createNode:()=>new Ru.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ru.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Pu.test.test(t)?t:e.options.nullStr};Au.nullTag=Pu});var Wo=R(Tu=>{"use strict";var cg=ie(),xu={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new cg.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},i){if(t&&xu.test.test(t)){let n=t[0]==="t"||t[0]==="T";if(e===n)return t}return e?i.options.trueStr:i.options.falseStr}};Tu.boolTag=xu});var mi=R(Iu=>{"use strict";function lg({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}Iu.stringifyNumber=lg});var Jo=R(Ir=>{"use strict";var ug=ie(),zo=mi(),fg={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:zo.stringifyNumber},dg={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():zo.stringifyNumber(t)}},hg={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 ug.Scalar(parseFloat(t)),i=t.indexOf(".");return i!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-i-1),e},stringify:zo.stringifyNumber};Ir.float=hg;Ir.floatExp=dg;Ir.floatNaN=fg});var Ko=R(Or=>{"use strict";var _u=mi(),_r=t=>typeof t=="bigint"||Number.isInteger(t),Go=(t,e,i,{intAsBigInt:n})=>n?BigInt(t):parseInt(t.substring(e),i);function Ou(t,e,i){let{value:n}=t;return _r(n)&&n>=0?i+n.toString(e):_u.stringifyNumber(t)}var pg={identify:t=>_r(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,i)=>Go(t,2,8,i),stringify:t=>Ou(t,8,"0o")},mg={identify:_r,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,i)=>Go(t,0,10,i),stringify:_u.stringifyNumber},vg={identify:t=>_r(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,i)=>Go(t,2,16,i),stringify:t=>Ou(t,16,"0x")};Or.int=mg;Or.intHex=vg;Or.intOct=pg});var Hu=R(ju=>{"use strict";var gg=hi(),wg=Tr(),yg=pi(),Ng=Ui(),bg=Wo(),Uo=Jo(),Yo=Ko(),kg=[gg.map,yg.seq,Ng.string,wg.nullTag,bg.boolTag,Yo.intOct,Yo.int,Yo.intHex,Uo.floatNaN,Uo.floatExp,Uo.float];ju.schema=kg});var Lu=R(Fu=>{"use strict";var Sg=ie(),Eg=hi(),Cg=pi();function $u(t){return typeof t=="bigint"||Number.isInteger(t)}var jr=({value:t})=>JSON.stringify(t),Rg=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:jr},{identify:t=>t==null,createNode:()=>new Sg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:jr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:jr},{identify:$u,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})=>$u(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:jr}],Pg={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Ag=[Eg.map,Cg.seq].concat(Rg,Pg);Fu.schema=Ag});var Qo=R(Mu=>{"use strict";var Yi=nr("buffer"),Xo=ie(),xg=zi(),Tg={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Yi.Buffer=="function")return Yi.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 Yi.Buffer=="function")s=o instanceof Yi.Buffer?o.toString("base64"):Yi.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=Xo.Scalar.BLOCK_LITERAL),e!==Xo.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(s.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=s.substr(d,c);s=f.join(e===Xo.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return xg.stringifyString({comment:t,type:e,value:s},n,r,a)}};Mu.binary=Tg});var Fr=R($r=>{"use strict";var Hr=$(),Zo=gt(),Ig=ie(),_g=Nt();function Bu(t,e){if(Hr.isSeq(t))for(let i=0;i<t.items.length;++i){let n=t.items[i];if(!Hr.isPair(n)){if(Hr.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let r=n.items[0]||new Zo.Pair(new Ig.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]=Cr.isPair(n)?n:new Lo.Pair(n)}}else e("Expected a sequence for this tag");return t}function Eu(t,e,i){let{replacer:n}=i,r=new ng.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(Lo.createPair(s,c,i))}return r}var rg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ku,createNode:Eu};Rr.createPairs=Eu;Rr.pairs=rg;Rr.resolvePairs=ku});var Do=R(Fo=>{"use strict";var Cu=$(),Mo=dt(),Ji=wt(),ag=yt(),Ru=Pr(),Mt=class t extends ag.YAMLSeq{constructor(){super(),this.add=Ji.YAMLMap.prototype.add.bind(this),this.delete=Ji.YAMLMap.prototype.delete.bind(this),this.get=Ji.YAMLMap.prototype.get.bind(this),this.has=Ji.YAMLMap.prototype.has.bind(this),this.set=Ji.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(Cu.isPair(r)?(a=Mo.toJS(r.key,"",i),o=Mo.toJS(r.value,a,i)):a=Mo.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=Ru.createPairs(e,i,n),a=new this;return a.items=r.items,a}};Mt.tag="tag:yaml.org,2002:omap";var og={collection:"seq",identify:t=>t instanceof Map,nodeClass:Mt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=Ru.resolvePairs(t,e),n=[];for(let{key:r}of i.items)Cu.isScalar(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Mt,i)},createNode:(t,e,i)=>Mt.from(t,e,i)};Fo.YAMLOMap=Mt;Fo.omap=og});var Iu=R(Bo=>{"use strict";var Pu=ee();function Au({value:t,source:e},i){return e&&(t?xu:Tu).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var xu={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 Pu.Scalar(!0),stringify:Au},Tu={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 Pu.Scalar(!1),stringify:Au};Bo.falseTag=Tu;Bo.trueTag=xu});var _u=R(Ar=>{"use strict";var sg=ee(),qo=di(),cg={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:qo.stringifyNumber},lg={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():qo.stringifyNumber(t)}},ug={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 sg.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:qo.stringifyNumber};Ar.float=ug;Ar.floatExp=lg;Ar.floatNaN=cg});var ju=R(Gi=>{"use strict";var Ou=di(),Ki=t=>typeof t=="bigint"||Number.isInteger(t);function xr(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 Vo(t,e,i){let{value:n}=t;if(Ki(n)){let r=n.toString(e);return n<0?"-"+i+r.substr(1):i+r}return Ou.stringifyNumber(t)}var fg={identify:Ki,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>xr(t,2,2,i),stringify:t=>Vo(t,2,"0b")},dg={identify:Ki,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>xr(t,1,8,i),stringify:t=>Vo(t,8,"0")},hg={identify:Ki,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>xr(t,0,10,i),stringify:Ou.stringifyNumber},pg={identify:Ki,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>xr(t,2,16,i),stringify:t=>Vo(t,16,"0x")};Gi.int=hg;Gi.intBin=fg;Gi.intHex=pg;Gi.intOct=dg});var Wo=R(zo=>{"use strict";var _r=$(),Tr=vt(),Ir=wt(),Ft=class t extends Ir.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;_r.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new Tr.Pair(e.key,null):i=new Tr.Pair(e,null),Ir.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let n=Ir.findPair(this.items,e);return!i&&_r.isPair(n)?_r.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=Ir.findPair(this.items,e);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new Tr.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(Tr.createPair(o,null,n));return a}};Ft.tag="tag:yaml.org,2002:set";var mg={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(_r.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}};zo.YAMLSet=Ft;zo.set=mg});var Ko=R(Or=>{"use strict";var vg=di();function Jo(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 Hu(t){let{value:e}=t,i=o=>o;if(typeof e=="bigint")i=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return vg.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 gg={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})=>Jo(t,i),stringify:Hu},wg={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=>Jo(t,!1),stringify:Hu},$u={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($u.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),f=e[8];if(f&&f!=="Z"){let u=Jo(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Or.floatTime=wg;Or.intTime=gg;Or.timestamp=$u});var Fu=R(Mu=>{"use strict";var yg=ui(),Ng=Nr(),bg=fi(),Sg=zi(),kg=$o(),Lu=Iu(),Go=_u(),jr=ju(),Eg=dr(),Cg=Do(),Rg=Pr(),Pg=Wo(),Uo=Ko(),Ag=[yg.map,bg.seq,Sg.string,Ng.nullTag,Lu.trueTag,Lu.falseTag,jr.intBin,jr.intOct,jr.int,jr.intHex,Go.floatNaN,Go.floatExp,Go.float,kg.binary,Eg.merge,Cg.omap,Rg.pairs,Pg.set,Uo.intTime,Uo.floatTime,Uo.timestamp];Mu.schema=Ag});var Uu=R(Qo=>{"use strict";var Vu=ui(),xg=Nr(),zu=fi(),Tg=zi(),Ig=Ao(),Yo=To(),Xo=_o(),_g=wu(),Og=bu(),Wu=$o(),Ui=dr(),Ju=Do(),Ku=Pr(),Du=Fu(),Gu=Wo(),Hr=Ko(),Bu=new Map([["core",_g.schema],["failsafe",[Vu.map,zu.seq,Tg.string]],["json",Og.schema],["yaml11",Du.schema],["yaml-1.1",Du.schema]]),qu={binary:Wu.binary,bool:Ig.boolTag,float:Yo.float,floatExp:Yo.floatExp,floatNaN:Yo.floatNaN,floatTime:Hr.floatTime,int:Xo.int,intHex:Xo.intHex,intOct:Xo.intOct,intTime:Hr.intTime,map:Vu.map,merge:Ui.merge,null:xg.nullTag,omap:Ju.omap,pairs:Ku.pairs,seq:zu.seq,set:Gu.set,timestamp:Hr.timestamp},jg={"tag:yaml.org,2002:binary":Wu.binary,"tag:yaml.org,2002:merge":Ui.merge,"tag:yaml.org,2002:omap":Ju.omap,"tag:yaml.org,2002:pairs":Ku.pairs,"tag:yaml.org,2002:set":Gu.set,"tag:yaml.org,2002:timestamp":Hr.timestamp};function Hg(t,e,i){let n=Bu.get(e);if(n&&!t)return i&&!n.includes(Ui.merge)?n.concat(Ui.merge):n.slice();let r=n;if(!r)if(Array.isArray(t))r=[];else{let a=Array.from(Bu.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(Ui.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?qu[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(qu).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Qo.coreKnownTags=jg;Qo.getTags=Hg});var ts=R(Yu=>{"use strict";var Zo=$(),$g=ui(),Lg=fi(),Mg=zi(),$r=Uu(),Fg=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,es=class t{constructor({compat:e,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?$r.getTags(e,"compat"):e?$r.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?$r.coreKnownTags:{},this.tags=$r.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,Zo.MAP,{value:$g.map}),Object.defineProperty(this,Zo.SCALAR,{value:Mg.string}),Object.defineProperty(this,Zo.SEQ,{value:Lg.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Fg:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Yu.Schema=es});var Qu=R(Xu=>{"use strict";var Dg=$(),is=Bi(),Yi=Li();function Bg(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=is.createStringifyContext(t,e),{commentString:a}=r.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=a(t.commentBefore);i.unshift(Yi.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(Dg.isNode(t.contents)){if(t.contents.spaceBefore&&n&&i.push(""),t.contents.commentBefore){let f=a(t.contents.commentBefore);i.push(Yi.indentComment(f,""))}r.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=is.stringify(t.contents,r,()=>s=null,c);s&&(l+=Yi.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(is.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]=Hr.isPair(n)?n:new Zo.Pair(n)}}else e("Expected a sequence for this tag");return t}function Du(t,e,i){let{replacer:n}=i,r=new _g.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(Zo.createPair(s,c,i))}return r}var Og={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Bu,createNode:Du};$r.createPairs=Du;$r.pairs=Og;$r.resolvePairs=Bu});var is=R(ts=>{"use strict";var qu=$(),es=ht(),Xi=yt(),jg=Nt(),Vu=Fr(),Bt=class t extends jg.YAMLSeq{constructor(){super(),this.add=Xi.YAMLMap.prototype.add.bind(this),this.delete=Xi.YAMLMap.prototype.delete.bind(this),this.get=Xi.YAMLMap.prototype.get.bind(this),this.has=Xi.YAMLMap.prototype.has.bind(this),this.set=Xi.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=es.toJS(r.key,"",i),o=es.toJS(r.value,a,i)):a=es.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=Vu.createPairs(e,i,n),a=new this;return a.items=r.items,a}};Bt.tag="tag:yaml.org,2002:omap";var Hg={collection:"seq",identify:t=>t instanceof Map,nodeClass:Bt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=Vu.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 Bt,i)},createNode:(t,e,i)=>Bt.from(t,e,i)};ts.YAMLOMap=Bt;ts.omap=Hg});var Ku=R(ns=>{"use strict";var Wu=ie();function zu({value:t,source:e},i){return e&&(t?Ju:Gu).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var Ju={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 Wu.Scalar(!0),stringify:zu},Gu={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 Wu.Scalar(!1),stringify:zu};ns.falseTag=Gu;ns.trueTag=Ju});var Uu=R(Lr=>{"use strict";var $g=ie(),rs=mi(),Fg={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:rs.stringifyNumber},Lg={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():rs.stringifyNumber(t)}},Mg={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 $g.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:rs.stringifyNumber};Lr.float=Mg;Lr.floatExp=Lg;Lr.floatNaN=Fg});var Xu=R(Zi=>{"use strict";var Yu=mi(),Qi=t=>typeof t=="bigint"||Number.isInteger(t);function Mr(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 as(t,e,i){let{value:n}=t;if(Qi(n)){let r=n.toString(e);return n<0?"-"+i+r.substr(1):i+r}return Yu.stringifyNumber(t)}var Bg={identify:Qi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>Mr(t,2,2,i),stringify:t=>as(t,2,"0b")},Dg={identify:Qi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>Mr(t,1,8,i),stringify:t=>as(t,8,"0")},qg={identify:Qi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>Mr(t,0,10,i),stringify:Yu.stringifyNumber},Vg={identify:Qi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>Mr(t,2,16,i),stringify:t=>as(t,16,"0x")};Zi.int=qg;Zi.intBin=Bg;Zi.intHex=Vg;Zi.intOct=Dg});var ss=R(os=>{"use strict";var qr=$(),Br=gt(),Dr=yt(),Dt=class t extends Dr.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;qr.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new Br.Pair(e.key,null):i=new Br.Pair(e,null),Dr.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let n=Dr.findPair(this.items,e);return!i&&qr.isPair(n)?qr.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=Dr.findPair(this.items,e);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new Br.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(Br.createPair(o,null,n));return a}};Dt.tag="tag:yaml.org,2002:set";var Wg={collection:"map",identify:t=>t instanceof Set,nodeClass:Dt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>Dt.from(t,e,i),resolve(t,e){if(qr.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Dt,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};os.YAMLSet=Dt;os.set=Wg});var ls=R(Vr=>{"use strict";var zg=mi();function cs(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 Qu(t){let{value:e}=t,i=o=>o;if(typeof e=="bigint")i=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return zg.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 Jg={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})=>cs(t,i),stringify:Qu},Gg={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=>cs(t,!1),stringify:Qu},Zu={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(Zu.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),f=e[8];if(f&&f!=="Z"){let u=cs(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Vr.floatTime=Gg;Vr.intTime=Jg;Vr.timestamp=Zu});var nf=R(tf=>{"use strict";var Kg=hi(),Ug=Tr(),Yg=pi(),Xg=Ui(),Qg=Qo(),ef=Ku(),us=Uu(),Wr=Xu(),Zg=kr(),ew=is(),tw=Fr(),iw=ss(),fs=ls(),nw=[Kg.map,Yg.seq,Xg.string,Ug.nullTag,ef.trueTag,ef.falseTag,Wr.intBin,Wr.intOct,Wr.int,Wr.intHex,us.floatNaN,us.floatExp,us.float,Qg.binary,Zg.merge,ew.omap,tw.pairs,iw.set,fs.intTime,fs.floatTime,fs.timestamp];tf.schema=nw});var hf=R(ps=>{"use strict";var sf=hi(),rw=Tr(),cf=pi(),aw=Ui(),ow=Wo(),ds=Jo(),hs=Ko(),sw=Hu(),cw=Lu(),lf=Qo(),en=kr(),uf=is(),ff=Fr(),rf=nf(),df=ss(),zr=ls(),af=new Map([["core",sw.schema],["failsafe",[sf.map,cf.seq,aw.string]],["json",cw.schema],["yaml11",rf.schema],["yaml-1.1",rf.schema]]),of={binary:lf.binary,bool:ow.boolTag,float:ds.float,floatExp:ds.floatExp,floatNaN:ds.floatNaN,floatTime:zr.floatTime,int:hs.int,intHex:hs.intHex,intOct:hs.intOct,intTime:zr.intTime,map:sf.map,merge:en.merge,null:rw.nullTag,omap:uf.omap,pairs:ff.pairs,seq:cf.seq,set:df.set,timestamp:zr.timestamp},lw={"tag:yaml.org,2002:binary":lf.binary,"tag:yaml.org,2002:merge":en.merge,"tag:yaml.org,2002:omap":uf.omap,"tag:yaml.org,2002:pairs":ff.pairs,"tag:yaml.org,2002:set":df.set,"tag:yaml.org,2002:timestamp":zr.timestamp};function uw(t,e,i){let n=af.get(e);if(n&&!t)return i&&!n.includes(en.merge)?n.concat(en.merge):n.slice();let r=n;if(!r)if(Array.isArray(t))r=[];else{let a=Array.from(af.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(en.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?of[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(of).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}ps.coreKnownTags=lw;ps.getTags=uw});var gs=R(pf=>{"use strict";var ms=$(),fw=hi(),dw=pi(),hw=Ui(),Jr=hf(),pw=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,vs=class t{constructor({compat:e,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?Jr.getTags(e,"compat"):e?Jr.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?Jr.coreKnownTags:{},this.tags=Jr.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,ms.MAP,{value:fw.map}),Object.defineProperty(this,ms.SCALAR,{value:hw.string}),Object.defineProperty(this,ms.SEQ,{value:dw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?pw:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};pf.Schema=vs});var vf=R(mf=>{"use strict";var mw=$(),ws=Ji(),tn=qi();function vw(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=ws.createStringifyContext(t,e),{commentString:a}=r.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=a(t.commentBefore);i.unshift(tn.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(mw.isNode(t.contents)){if(t.contents.spaceBefore&&n&&i.push(""),t.contents.commentBefore){let f=a(t.contents.commentBefore);i.push(tn.indentComment(f,""))}r.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=ws.stringify(t.contents,r,()=>s=null,c);s&&(l+=tn.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(ws.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
|
|
58
|
+
`)?(i.push("..."),i.push(tn.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(tn.indentComment(a(c),"")))}return i.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}mf.stringifyDocument=vw});var nn=R(gf=>{"use strict";var gw=Bi(),vi=dr(),Se=$(),ww=gt(),yw=ht(),Nw=gs(),bw=vf(),ys=cr(),kw=So(),Sw=Di(),Ns=ko(),bs=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 Ns.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){gi(this.contents)&&this.contents.add(e)}addIn(e,i){gi(this.contents)&&this.contents.addIn(e,i)}createAlias(e,i){if(!e.anchor){let n=ys.anchorNames(this);e.anchor=!i||n.has(i)?ys.findNewAnchor(i||"a",n):i}return new gw.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,b=i.filter(v).map(String);b.length>0&&(i=i.concat(b)),r=i}else n===void 0&&i&&(n=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=ys.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:p},h=Sw.createNode(e,f,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 ww.Pair(r,a)}delete(e){return gi(this.contents)?this.contents.delete(e):!1}deleteIn(e){return vi.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):gi(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 vi.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 vi.isEmptyPath(e)?this.contents!==void 0:Se.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,i){this.contents==null?this.contents=vi.collectionFromPath(this.schema,[e],i):gi(this.contents)&&this.contents.set(e,i)}setIn(e,i){vi.isEmptyPath(e)?this.contents=i:this.contents==null?this.contents=vi.collectionFromPath(this.schema,Array.from(e),i):gi(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 Ns.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 Ns.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 Nw.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=yw.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?kw.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 bw.stringifyDocument(this,e)}};function gi(t){if(Se.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}gf.Document=bs});var on=R(an=>{"use strict";var rn=class extends Error{constructor(e,i,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=i}},ks=class extends rn{constructor(e,i,n){super("YAMLParseError",e,i,n)}},Ss=class extends rn{constructor(e,i,n){super("YAMLWarning",e,i,n)}},Ew=(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
|
-
`+y.comment:
|
|
69
|
-
`+g.comment:l.comment=g.comment),u=g.end;continue}!o&&i.options.strict&&
|
|
70
|
-
`+
|
|
71
|
-
`+C.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,f=0;for(let h=0;h<s;++h){let[v,
|
|
74
|
-
`;for(let h=f;h<s;++h){let[v,
|
|
75
|
-
`):v.length>c||
|
|
65
|
+
`}};an.YAMLError=rn;an.YAMLParseError=ks;an.YAMLWarning=Ss;an.prettifyError=Ew});var sn=R(wf=>{"use strict";function Cw(t,{flow:e,indicator:i,next:n,offset:r,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,u="",d="",p=!1,m=!1,h=null,v=null,b=null,N=null,y=null,w=null,E=null;for(let k of t)switch(m&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&a(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&k.type!=="comment"&&k.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),k.type){case"space":!e&&(i!=="doc-start"||n?.type!=="flow-collection")&&k.source.includes(" ")&&(h=k),f=!0;break;case"comment":{f||a(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let C=k.source.substring(1)||" ";u?u+=d+C:u=C,d="",l=!1;break}case"newline":l?u?u+=k.source:(!w||i!=="seq-item-ind")&&(c=!0):d+=k.source,l=!0,p=!0,(v||b)&&(N=k),f=!0;break;case"anchor":v&&a(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&a(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=k,E??(E=k.offset),l=!1,f=!1,m=!0;break;case"tag":{b&&a(k,"MULTIPLE_TAGS","A node can have at most one tag"),b=k,E??(E=k.offset),l=!1,f=!1,m=!0;break}case i:(v||b)&&a(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),w&&a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${e??"collection"}`),w=k,l=i==="seq-item-ind"||i==="explicit-key-ind",f=!1;break;case"comma":if(e){y&&a(k,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),y=k,l=!1,f=!1;break}default:a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,f=!1}let g=t[t.length-1],S=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:y,found:w,spaceBefore:c,comment:u,hasNewline:p,anchor:v,tag:b,newlineAfterProp:N,end:S,start:E??S}}wf.resolveProps=Cw});var Gr=R(yf=>{"use strict";function Es(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(Es(e.key)||Es(e.value))return!0}return!1;default:return!0}}yf.containsNewline=Es});var Cs=R(Nf=>{"use strict";var Rw=Gr();function Pw(t,e,i){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===t&&(n.source==="]"||n.source==="}")&&Rw.containsNewline(e)&&i(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Nf.flowIndentCheck=Pw});var Rs=R(kf=>{"use strict";var bf=$();function Aw(t,e,i){let{uniqueKeys:n}=t.options;if(n===!1)return!1;let r=typeof n=="function"?n:(a,o)=>a===o||bf.isScalar(a)&&bf.isScalar(o)&&a.value===o.value;return e.some(a=>r(a.key,i))}kf.mapIncludes=Aw});var Af=R(Pf=>{"use strict";var Sf=gt(),xw=yt(),Ef=sn(),Tw=Gr(),Cf=Cs(),Iw=Rs(),Rf="All mapping items must start at the same column";function _w({composeNode:t,composeEmptyNode:e},i,n,r,a){let o=a?.nodeClass??xw.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:u,key:d,sep:p,value:m}=f,h=Ef.resolveProps(u,{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",Rf)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Tw.containsNewline(d))&&r(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&r(c,"BAD_INDENT",Rf);i.atKey=!0;let b=h.end,N=d?t(i,d,h,r):e(i,b,u,null,h,r);i.schema.compat&&Cf.flowIndentCheck(n.indent,d,r),i.atKey=!1,Iw.mapIncludes(i,s.items,N)&&r(b,"DUPLICATE_KEY","Map keys must be unique");let y=Ef.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=y.end,y.found){v&&(m?.type==="block-map"&&!y.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<y.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 w=m?t(i,m,y,r):e(i,c,p,null,y,r);i.schema.compat&&Cf.flowIndentCheck(n.indent,m,r),c=w.range[2];let E=new Sf.Pair(N,w);i.options.keepSourceTokens&&(E.srcToken=f),s.items.push(E)}else{v&&r(N.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(N.comment?N.comment+=`
|
|
68
|
+
`+y.comment:N.comment=y.comment);let w=new Sf.Pair(N);i.options.keepSourceTokens&&(w.srcToken=f),s.items.push(w)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}Pf.resolveBlockMap=_w});var Tf=R(xf=>{"use strict";var Ow=Nt(),jw=sn(),Hw=Cs();function $w({composeNode:t,composeEmptyNode:e},i,n,r,a){let o=a?.nodeClass??Ow.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:f,value:u}of n.items){let d=jw.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.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=u?t(i,u,d,r):e(i,d.end,f,null,d,r);i.schema.compat&&Hw.flowIndentCheck(n.indent,u,r),c=p.range[2],s.items.push(p)}return s.range=[n.offset,c,l??c],s}xf.resolveBlockSeq=$w});var wi=R(If=>{"use strict";function Fw(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 f=c.substring(1)||" ";r?r+=o+f:r=f,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}}If.resolveEnd=Fw});var Hf=R(jf=>{"use strict";var Lw=$(),Mw=gt(),_f=yt(),Bw=Nt(),Dw=wi(),Of=sn(),qw=Gr(),Vw=Rs(),Ps="Block collections are not allowed within flow collections",As=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Ww({composeNode:t,composeEmptyNode:e},i,n,r,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?_f.YAMLMap:Bw.YAMLSeq),l=new c(i.schema);l.flow=!0;let f=i.atRoot;f&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let u=n.offset+n.start.source.length;for(let v=0;v<n.items.length;++v){let b=n.items[v],{start:N,key:y,sep:w,value:E}=b,g=Of.resolveProps(N,{flow:s,indicator:"explicit-key-ind",next:y??w?.[0],offset:u,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!g.found){if(!g.anchor&&!g.tag&&!w&&!E){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),u=g.end;continue}!o&&i.options.strict&&qw.containsNewline(y)&&r(y,"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 S="";e:for(let k of N)switch(k.type){case"comma":case"space":break;case"comment":S=k.source.substring(1);break e;default:break e}if(S){let k=l.items[l.items.length-1];Lw.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
|
|
70
|
+
`+S:k.comment=S,g.comment=g.comment.substring(S.length+1)}}if(!o&&!w&&!g.found){let S=E?t(i,E,g,r):e(i,g.end,w,null,g,r);l.items.push(S),u=S.range[2],As(E)&&r(S.range,"BLOCK_IN_FLOW",Ps)}else{i.atKey=!0;let S=g.end,k=y?t(i,y,g,r):e(i,S,N,null,g,r);As(y)&&r(k.range,"BLOCK_IN_FLOW",Ps),i.atKey=!1;let C=Of.resolveProps(w??[],{flow:s,indicator:"map-value-ind",next:E,offset:k.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(C.found){if(!o&&!g.found&&i.options.strict){if(w)for(let M of w){if(M===C.found)break;if(M.type==="newline"){r(M,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}g.start<C.found.offset-1024&&r(C.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?r(E,"MISSING_CHAR",`Missing space after : in ${s}`):r(C.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let B=E?t(i,E,C,r):C.found?e(i,C.end,w,null,C,r):null;B?As(E)&&r(B.range,"BLOCK_IN_FLOW",Ps):C.comment&&(k.comment?k.comment+=`
|
|
71
|
+
`+C.comment:k.comment=C.comment);let G=new Mw.Pair(k,B);if(i.options.keepSourceTokens&&(G.srcToken=b),o){let M=l;Vw.mapIncludes(i,M.items,k)&&r(S,"DUPLICATE_KEY","Map keys must be unique"),M.items.push(G)}else{let M=new _f.YAMLMap(i.schema);M.flow=!0,M.items.push(G);let V=(B??k).range;M.range=[k.range[0],V[1],V[2]],l.items.push(M)}u=B?B.range[2]:C.end}}let d=o?"}":"]",[p,...m]=n.end,h=u;if(p?.source===d)h=p.offset+p.source.length;else{let v=s[0].toUpperCase()+s.substring(1),b=f?`${v} must end with a ${d}`:`${v} in block collection must be sufficiently indented and end with a ${d}`;r(u,f?"MISSING_CHAR":"BAD_INDENT",b),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let v=Dw.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}jf.resolveFlowCollection=Ww});var Ff=R($f=>{"use strict";var zw=$(),Jw=ie(),Gw=yt(),Kw=Nt(),Uw=Af(),Yw=Tf(),Xw=Hf();function xs(t,e,i,n,r,a){let o=i.type==="block-map"?Uw.resolveBlockMap(t,e,i,n,a):i.type==="block-seq"?Yw.resolveBlockSeq(t,e,i,n,a):Xw.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 Qw(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===Gw.YAMLMap.tagName&&s==="map"||o===Kw.YAMLSeq.tagName&&s==="seq")return xs(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),xs(t,e,i,r,o)}let l=xs(t,e,i,r,o,c),f=c.resolve?.(l,d=>r(a,"TAG_RESOLVE_FAILED",d),e.options)??l,u=zw.isNode(f)?f:new Jw.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}$f.composeCollection=Qw});var Is=R(Lf=>{"use strict";var Ts=ie();function Zw(t,e,i){let n=e.offset,r=ey(e,t.options.strict,i);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let a=r.mode===">"?Ts.Scalar.BLOCK_FOLDED:Ts.Scalar.BLOCK_LITERAL,o=e.source?ty(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,f=0;for(let h=0;h<s;++h){let[v,b]=o[h];if(b===""||b==="\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),f=h,c===0&&!t.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+b.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let u="",d="",p=!1;for(let h=0;h<f;++h)u+=o[h][0].slice(c)+`
|
|
74
|
+
`;for(let h=f;h<s;++h){let[v,b]=o[h];l+=v.length+b.length+1;let N=b[b.length-1]==="\r";if(N&&(b=b.slice(0,-1)),b&&v.length<c){let w=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;i(l-b.length-(N?2:1),"BAD_INDENT",w),v=""}a===Ts.Scalar.BLOCK_LITERAL?(u+=d+v.slice(c)+b,d=`
|
|
75
|
+
`):v.length>c||b[0]===" "?(d===" "?d=`
|
|
76
76
|
`:!p&&d===`
|
|
77
77
|
`&&(d=`
|
|
78
78
|
|
|
79
|
-
`),u+=d+v.slice(c)+
|
|
80
|
-
`,p=!0):
|
|
79
|
+
`),u+=d+v.slice(c)+b,d=`
|
|
80
|
+
`,p=!0):b===""?d===`
|
|
81
81
|
`?u+=`
|
|
82
82
|
`:d=`
|
|
83
|
-
`:(u+=d+
|
|
83
|
+
`:(u+=d+b,d=" ",p=!1)}switch(r.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)u+=`
|
|
84
84
|
`+o[h][0].slice(c);u[u.length-1]!==`
|
|
85
85
|
`&&(u+=`
|
|
86
86
|
`);break;default:u+=`
|
|
87
|
-
`}let m=n+r.length+e.source.length;return{value:u,type:a,comment:r.comment,range:[n,m,m]}}function
|
|
87
|
+
`}let m=n+r.length+e.source.length;return{value:u,type:a,comment:r.comment,range:[n,m,m]}}function ey({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,f="",u=r.length;for(let d=1;d<e.length;++d){let p=e[d];switch(p.type){case"space":l=!0;case"newline":u+=p.source.length;break;case"comment":i&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,f=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),u+=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"&&(u+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:u}}function ty(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}Lf.resolveBlockScalar=Zw});var Os=R(Bf=>{"use strict";var _s=ie(),iy=wi();function ny(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=_s.Scalar.PLAIN,c=ry(a,l);break;case"single-quoted-scalar":s=_s.Scalar.QUOTE_SINGLE,c=ay(a,l);break;case"double-quoted-scalar":s=_s.Scalar.QUOTE_DOUBLE,c=oy(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 f=n+a.length,u=iy.resolveEnd(o,f,e,i);return{value:c,type:s,comment:u.comment,range:[n,f,u.offset]}}function ry(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}`),Mf(t)}function ay(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Mf(t.slice(1,-1)).replace(/''/g,"'")}function Mf(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 oy(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}=sy(t,n);i+=a,n=o}else if(r==="\\"){let a=t[++n],o=cy[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+=ly(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 sy(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 cy={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function ly(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}}Bf.resolveFlowScalar=ny});var Vf=R(qf=>{"use strict";var qt=$(),Df=ie(),uy=Is(),fy=Os();function dy(t,e,i,n){let{value:r,type:a,comment:o,range:s}=e.type==="block-scalar"?uy.resolveBlockScalar(t,e,n):fy.resolveFlowScalar(e,t.options.strict,n),c=i?t.directives.tagName(i.source,u=>n(i,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[qt.SCALAR]:c?l=hy(t.schema,r,c,i,n):e.type==="scalar"?l=py(t,r,e,n):l=t.schema[qt.SCALAR];let f;try{let u=l.resolve(r,d=>n(i??e,"TAG_RESOLVE_FAILED",d),t.options);f=qt.isScalar(u)?u:new Df.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);n(i??e,"TAG_RESOLVE_FAILED",d),f=new Df.Scalar(r)}return f.range=s,f.source=r,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function hy(t,e,i,n,r){if(i==="!")return t[qt.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[qt.SCALAR])}function py({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[qt.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(n))??i[qt.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}qf.composeScalar=dy});var zf=R(Wf=>{"use strict";function my(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}Wf.emptyScalarPosition=my});var Kf=R(Hs=>{"use strict";var vy=Bi(),gy=$(),wy=Ff(),Jf=Vf(),yy=wi(),Ny=zf(),by={composeNode:Gf,composeEmptyNode:js};function Gf(t,e,i,n){let r=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,f=!0;switch(e.type){case"alias":l=ky(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=Jf.composeScalar(t,e,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=wy.composeCollection(by,t,e,i,n),s&&(l.anchor=s.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);n(e,"RESOURCE_EXHAUSTION",d)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=js(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&&(!gy.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&&f&&(l.srcToken=e),l}function js(t,e,i,n,{spaceBefore:r,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Ny.emptyScalarPosition(e,i,n),indent:-1,source:""},u=Jf.composeScalar(t,f,s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function ky({options:t},{offset:e,source:i,end:n},r){let a=new vy.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=yy.resolveEnd(n,o,t.strict,r);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}Hs.composeEmptyNode=js;Hs.composeNode=Gf});var Xf=R(Yf=>{"use strict";var Sy=nn(),Uf=Kf(),Ey=wi(),Cy=sn();function Ry(t,e,{offset:i,start:n,value:r,end:a},o){let s=Object.assign({_directives:e},t),c=new Sy.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Cy.resolveProps(n,{indicator:"doc-start",next:r??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?Uf.composeNode(l,r,f,o):Uf.composeEmptyNode(l,f.end,n,null,f,o);let u=c.contents.range[2],d=Ey.resolveEnd(a,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[i,u,d.offset],c}Yf.composeDoc=Ry});var Fs=R(ed=>{"use strict";var Py=nr("process"),Ay=ko(),xy=nn(),cn=on(),Qf=$(),Ty=Xf(),Iy=wi();function ln(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 Zf(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=ln(i);a?this.warnings.push(new cn.YAMLWarning(o,n,r)):this.errors.push(new cn.YAMLParseError(o,n,r))},this.directives=new Ay.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,i){let{comment:n,afterEmptyLine:r}=Zf(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(Qf.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Qf.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:Zf(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(Py.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(i,n,r)=>{let a=ln(e);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let i=Ty.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 cn.YAMLParseError(ln(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 cn.YAMLParseError(ln(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let i=Iy.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 cn.YAMLParseError(ln(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 xy.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}}};ed.Composer=$s});var nd=R(Kr=>{"use strict";var _y=Is(),Oy=Os(),jy=on(),td=zi();function Hy(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 jy.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Oy.resolveFlowScalar(t,e,n);case"block-scalar":return _y.resolveBlockScalar({options:{strict:e}},t,n)}}return null}function $y(t,e){let{implicitKey:i=!1,indent:n,inFlow:r=!1,offset:a=-1,type:o="PLAIN"}=e,s=td.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
|
`),f=s.substring(0,l),u=s.substring(l+1)+`
|
|
112
|
-
`,d=[{type:"block-scalar-header",offset:a,indent:n,source:f}];return
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:n,props:d,source:u}}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:f}];return id(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:n,props:d,source:u}}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 Fy(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=td.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">":Ly(t,c);break;case'"':Ls(t,c,"double-quoted-scalar");break;case"'":Ls(t,c,"single-quoted-scalar");break;default:Ls(t,c,"scalar")}}function Ly(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}];id(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 id(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 Ls(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})}}}Kr.createScalarToken=$y;Kr.resolveAsScalar=Hy;Kr.setScalarValue=Fy});var ad=R(rd=>{"use strict";var My=t=>"type"in t?Yr(t):Ur(t);function Yr(t){switch(t.type){case"block-scalar":{let e="";for(let i of t.props)e+=Yr(i);return e+t.source}case"block-map":case"block-seq":{let e="";for(let i of t.items)e+=Ur(i);return e}case"flow-collection":{let e=t.start.source;for(let i of t.items)e+=Ur(i);for(let i of t.end)e+=i.source;return e}case"document":{let e=Ur(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 Ur({start:t,key:e,sep:i,value:n}){let r="";for(let a of t)r+=a.source;if(e&&(r+=Yr(e)),i)for(let a of i)r+=a.source;return n&&(r+=Yr(n)),r}rd.stringify=My});var ld=R(cd=>{"use strict";var Ms=Symbol("break visit"),By=Symbol("skip children"),od=Symbol("remove item");function Vt(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),sd(Object.freeze([]),t,e)}Vt.BREAK=Ms;Vt.SKIP=By;Vt.REMOVE=od;Vt.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};Vt.parentCollection=(t,e)=>{let i=Vt.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 sd(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=sd(Object.freeze(t.concat([[r,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===Ms)return Ms;s===od&&(a.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(e,t))}}return typeof n=="function"?n(e,t):n}cd.visit=Vt});var Xr=R(ve=>{"use strict";var Bs=nd(),Dy=ad(),qy=ld(),Ds="\uFEFF",qs="",Vs="",Ws="",Vy=t=>!!t&&"items"in t,Wy=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function zy(t){switch(t){case Ds:return"<BOM>";case qs:return"<DOC>";case Vs:return"<FLOW_END>";case Ws:return"<SCALAR>";default:return JSON.stringify(t)}}function Jy(t){switch(t){case Ds:return"byte-order-mark";case qs:return"doc-mode";case Vs:return"flow-error-end";case Ws: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}ve.createScalarToken=Bs.createScalarToken;ve.resolveAsScalar=Bs.resolveAsScalar;ve.setScalarValue=Bs.setScalarValue;ve.stringify=Dy.stringify;ve.visit=qy.visit;ve.BOM=Ds;ve.DOCUMENT=qs;ve.FLOW_END=Vs;ve.SCALAR=Ws;ve.isCollection=Vy;ve.isScalar=Wy;ve.prettyToken=zy;ve.tokenType=Jy});var Gs=R(fd=>{"use strict";var un=Xr();function Oe(t){switch(t){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var ud=new Set("0123456789ABCDEFabcdef"),Gy=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Qr=new Set(",[]{}"),Ky=new Set(` ,[]{}
|
|
121
|
+
\r `),zs=t=>!t||Ky.has(t),Js=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==="...")&&Oe(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]===un.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 un.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==="...")&&Oe(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&&!Oe(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===":")&&Oe(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(zs),"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("..."))&&Oe(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield un.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(zs),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Oe(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=>Oe(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 un.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(Oe(a)||e&&Qr.has(a))break;i=n}else if(Oe(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&&Qr.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&&Qr.has(r))break;i=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield un.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(zs),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,n=this.charAt(1);if(Oe(n)||i&&Qr.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(;!Oe(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(Gy.has(i))i=this.buffer[++e];else if(i==="%"&&ud.has(this.buffer[e+1])&&ud.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)}};fd.Lexer=Js});var Us=R(dd=>{"use strict";var Ks=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}}}};dd.LineCounter=Ks});var Xs=R(gd=>{"use strict";var Uy=nr("process"),hd=Xr(),Yy=Gs();function bt(t,e){for(let i=0;i<t.length;++i)if(t[i].type===e)return!0;return!1}function pd(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 vd(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 Zr(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 yi(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 ea(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 md(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,vd(e.value)?e.value.end?ea(e.value.end,e.sep):e.value.end=e.sep:ea(e.start,e.sep),delete e.sep)}var Ys=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 Yy.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,Uy.env.LOG_TOKENS&&console.log("|",hd.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let i=hd.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"&&md(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&&pd(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":{pd(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=Zr(this.peek(2)),n=yi(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)){ea(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(vd(i.key)&&!bt(i.sep,"newline")){let o=yi(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=yi(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)){ea(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=Zr(n),a=yi(r);md(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=Vr(e),n=vi(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=Vr(e),n=vi(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())}}};ed.Parser=js});var ad=R(sn=>{"use strict";var td=bs(),Sy=Xi(),on=en(),ky=yo(),Ey=$(),Cy=Os(),id=Hs();function nd(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Cy.LineCounter||null,prettyErrors:e}}function Ry(t,e={}){let{lineCounter:i,prettyErrors:n}=nd(e),r=new id.Parser(i?.addNewLine),a=new td.Composer(e),o=Array.from(a.compose(r.parse(t)));if(n&&i)for(let s of o)s.errors.forEach(on.prettifyError(t,i)),s.warnings.forEach(on.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function rd(t,e={}){let{lineCounter:i,prettyErrors:n}=nd(e),r=new id.Parser(i?.addNewLine),a=new td.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 on.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(on.prettifyError(t,i)),o.warnings.forEach(on.prettifyError(t,i))),o}function Py(t,e,i){let n;typeof e=="function"?n=e:i===void 0&&e&&typeof e=="object"&&(i=e);let r=rd(t,i);if(!r)return null;if(r.warnings.forEach(a=>ky.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 Ay(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 Ey.isDocument(t)&&!n?t.toString(i):new Sy.Document(t,n,i).toString(i)}sn.parse=Py;sn.parseAllDocuments=Ry;sn.parseDocument=rd;sn.stringify=Ay});var Ls=R(q=>{"use strict";var xy=bs(),Ty=Xi(),Iy=ts(),$s=en(),_y=Hi(),bt=$(),Oy=vt(),jy=ee(),Hy=wt(),$y=yt(),Ly=Br(),My=Is(),Fy=Os(),Dy=Hs(),Wr=ad(),od=Ii();q.Composer=xy.Composer;q.Document=Ty.Document;q.Schema=Iy.Schema;q.YAMLError=$s.YAMLError;q.YAMLParseError=$s.YAMLParseError;q.YAMLWarning=$s.YAMLWarning;q.Alias=_y.Alias;q.isAlias=bt.isAlias;q.isCollection=bt.isCollection;q.isDocument=bt.isDocument;q.isMap=bt.isMap;q.isNode=bt.isNode;q.isPair=bt.isPair;q.isScalar=bt.isScalar;q.isSeq=bt.isSeq;q.Pair=Oy.Pair;q.Scalar=jy.Scalar;q.YAMLMap=Hy.YAMLMap;q.YAMLSeq=$y.YAMLSeq;q.CST=Ly;q.Lexer=My.Lexer;q.LineCounter=Fy.LineCounter;q.Parser=Dy.Parser;q.parse=Wr.parse;q.parseAllDocuments=Wr.parseAllDocuments;q.parseDocument=Wr.parseDocument;q.stringify=Wr.stringify;q.visit=od.visit;q.visitAsync=od.visitAsync});import{promises as Jk}from"fs";var Ra=gl(Ls(),1);import{promises as yh}from"fs";import at from"path";import{createHash as zy}from"node:crypto";import{promises as _e}from"node:fs";import Se from"node:path";import{TextDecoder as Wy}from"node:util";import Ms from"path";var By=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),qy=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Vy(t){return t.toLowerCase().startsWith(".env")}function Ze(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>Vy(n))?"environment-file":i.some(n=>qy.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>By.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function sd(t,e){let i=Ze(e);if(i)return i;let n=Ms.resolve(t.projectRoot,...e.split("/")),r=Ms.relative(t.projectRoot,t.nativeRoot).replaceAll("\\","/"),a=e.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===Ms.resolve(t.configFile)?"native-runtime":null}function St(t){return t!==0&&t!==0n&&t!=="0"}function se(t,e){return St(t.dev)&&St(e.dev)&&St(t.ino)&&St(e.ino)}function H(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 Kr=1024*1024;function Fs(t,e){let i=Se.relative(t,e);return i===""||!Se.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Se.sep}`)}function Jy(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=Ze(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 Ky(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function Gy(t,e){return H({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Jr(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?H(i,n):H(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function cd(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 Uy(t,e){let i=Se.resolve(t),n=Se.resolve(e);if(!Fs(i,n))throw new Error("Native artifact path is outside its root");let r=[await cd(i)],a=i;for(let o of Se.relative(i,n).split(Se.sep).filter(Boolean)){a=Se.join(a,o);let s=await cd(a);if(!Fs(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function ld(t){for(let e of t){let i=await _e.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Gy(e,i)||await _e.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function et(t){let e=Jy(t.ref),i=Ky(t.maxBytes??Kr),n=Se.resolve(t.root,...e.split("/")),r=await Uy(t.root,Se.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(!Fs(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,f]=await Promise.all([s.stat(),_e.lstat(n),_e.realpath(n)]);if(await ld(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!Jr(a,c)||!Jr(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let y=i+1-d,w=await s.read(p,0,Math.min(p.length,y),null);if(w.bytesRead===0)break;if(d+=w.bytesRead,d>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);u.push(Buffer.from(p.subarray(0,w.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),_e.lstat(n),_e.realpath(n)]);if(await ld(r),!h.isFile()||h.isSymbolicLink()||v!==o||!Jr(c,m)||!Jr(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let N=Buffer.concat(u,d),b;try{b=new Wy("utf-8",{fatal:!0}).decode(N)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:y})}return{ref:e,size:d,hash:zy("sha256").update(N).digest("hex"),text:b}}finally{await s.close()}}import{randomUUID as Yy}from"crypto";import{promises as ce}from"fs";import Oe from"path";function Bs(t,e){let i=Oe.relative(t,e);return i===""||!Oe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Oe.sep}`)}function Xy(t,e){return H({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Ds(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?H(i,n):H(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function ud(t){let e=await ce.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 ce.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function cn(t){for(let e of t){let i=await ce.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Xy(e,i)||await ce.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function Qy(t,e){let i=Oe.resolve(t),n=Oe.resolve(e);if(!Bs(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let r=[await ud(i)],a=Oe.relative(i,n).split(Oe.sep).filter(Boolean),o=i;for(let s of a){await cn(r),o=Oe.join(o,s);try{await ce.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await ud(o);if(!Bs(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await cn(r),r}async function Zy(t){let e;try{e=await ce.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 eN(t,e,i={}){let n=Oe.dirname(t),r=i.containedRoot?await Qy(i.containedRoot,n):null;r||await ce.mkdir(n,{recursive:!0});let a=Oe.join(n,`.${Oe.basename(t)}.${Yy()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await ce.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([ce.lstat(a),ce.realpath(a)]);if(await cn(r),!c.isFile()||c.isSymbolicLink()||!Ds(s,c)||!Bs(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(),!Ds(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 cn(r);let c=await ce.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Ds(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await ce.link(a,t),await ce.unlink(a)):await ce.rename(a,t),await Zy(n)}catch(c){if(await o?.close(),!r)await ce.rm(a,{force:!0});else try{await cn(r),await ce.rm(a,{force:!0})}catch{}throw c}}async function qt(t,e,i={}){await eN(t,e,i)}async function ke(t,e,i={}){await qt(t,JSON.stringify(e,null,2)+`
|
|
143
|
-
`,i)}var Vs=gl(Ls(),1);import Gr from"path";var Xr=64*1024,Ur=1024,Yr=64,zs=5,tN=[".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/**"],pe={include:["**/*"],exclude:[...tN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function iN(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Gr.posix.isAbsolute(i)||Gr.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 Vt(t){let e=iN(t,"native.artifact_root");return e.length===0?".":e.join("/")}function dd(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 Ws(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||Gr.posix.isAbsolute(n)||Gr.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 ln(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function hd(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 Qr(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>Ur)throw new Error(`${e} exceeds ${Ur} 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>Yr)throw new Error(`${e} contains more than ${Yr} wildcard tokens`);return t}function fd(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=>Qr(n,e)))].sort((n,r)=>n.localeCompare(r,"en"))}function qs(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 nN(t){if(t===void 0)return{...pe,include:[...pe.include],exclude:[...pe.exclude]};let e=ln(t,"native.snapshot");return{include:fd(e.include,"native.snapshot.include",pe.include),exclude:fd(e.exclude,"native.snapshot.exclude",pe.exclude),max_files:qs(e.max_files,pe.max_files,"native.snapshot.max_files"),max_total_bytes:qs(e.max_total_bytes,pe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:qs(e.max_duration_ms,pe.max_duration_ms,"native.snapshot.max_duration_ms")}}function rN(t){if(t===void 0)return;let e=ln(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=ln(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=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 f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:i,fromArtifactRoot:Vt(n),toArtifactRoot:Vt(r),stage:a,...o?{cleanup:o}:{}}}function aN(t,e={}){let i=ln(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??zs;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=rN(i.pending_root_move);return{artifact_root:Vt(n),language:hd(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:nN(i.snapshot),...s?{pending_root_move:s}:{}}}function oN(t){let e=ln(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:dd(e.artifact_layout),language:hd(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function sN(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function cN(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 Zr(t,e={}){let i=(0,Vs.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=sN(r.ambient_resume),o=r.native===void 0?void 0:aN(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=r.classic===void 0?void 0:oN(r.classic),c=cN(r,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function Js(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Vt(t),language:e,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:zs,snapshot:{...pe,include:[...pe.include],exclude:[...pe.exclude]}}}}import{createHash as uN}from"crypto";import{promises as ia}from"fs";import kt from"path";import{constants as ea,promises as zt}from"fs";var je=class extends Error{reason;constructor(e,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=e}};function Ks(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function pd(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function un(t){return{dev:t.dev,ino:t.ino,birthtime:Ks(t)}}function ta(t,e){let i=un(t),n=un(e);return se(i,n)?H(i,n):H(i,n)&&Ks(t)===Ks(e)&&pd(t)===pd(e)&&t.size===e.size}async function gi(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 zt.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 zt.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:un(a)});let s=process.platform==="win32"?ea.O_RDONLY:ea.O_RDONLY|ea.O_NOFOLLOW|ea.O_NONBLOCK,c;try{c=await zt.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,f,u]=await Promise.all([c.stat({bigint:r}),zt.lstat(t,{bigint:r}),zt.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!ta(a,l)||!ta(a,f))throw new je("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:u,identity:un(l)}),await i.hooks?.afterOpen?.();let d=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let b=e+1-p,{bytesRead:y}=await c.read(m,0,Math.min(m.length,b),null);if(y===0)break;if(p+=y,p>e)throw new je("too-large",`${n} exceeds ${e} bytes`);d.push(Buffer.from(m.subarray(0,y)))}await i.hooks?.beforeFinalCheck?.();let[h,v,N]=await Promise.all([c.stat({bigint:r}),zt.lstat(t,{bigint:r}),zt.realpath(t)]);if(!v.isFile()||v.isSymbolicLink()||N!==o||!ta(a,h)||!ta(a,v))throw new je("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:N,identity:un(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:N}}finally{await c.close()}}function lN(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Gs(t,e){let i=kt.relative(t,e);return i===""||!kt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${kt.sep}`)}async function md(t,e){let i=kt.resolve(t),n=await ia.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return ia.realpath(i)}async function vd(t,e,i,n){let r=t;for(let a=0;a<i.length;a++){r=kt.join(r,i[a]);let o;try{o=await ia.lstat(r)}catch(f){if(lN(f))return{exists:!1,kind:"missing"};throw f}let s=kt.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 ia.realpath(r);if(!Gs(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 fn(t,e,i){let n=Ws(e,i.label),r=kt.resolve(t),a=await md(r,i.label),o=n.split("/"),s=kt.resolve(r,...o);if(!Gs(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 wi(t,e,i,n){let r=await fn(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 md(r.projectRoot,n.label);return gi(r.target,i,{...n,verify:async(o,s)=>{if(!Gs(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 dn=".comet/config.yaml";function fN(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Us(t,e={}){return(await na(t,e)).document}async function dN(t){try{return(await wi(t,dn,Xr,{label:dn})).bytes}catch(e){if(fN(e))return null;throw e}}function hN(t){return t?{exists:!0,sha256:uN("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function na(t,e={}){let i=await dN(t);return{document:i?Zr(i.toString("utf8"),e):null,identity:hN(i)}}var lP=16*1024;import{promises as yi}from"fs";import W from"path";import wN from"os";var ra=".comet/config.yaml";async function Xs(t){try{return await yi.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function yN(t){try{let e=await yi.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function hn(t,e){let i=W.relative(t,e);return i===""||!W.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${W.sep}`)}async function pn(t){let e=[],i=t;for(;!await Xs(i);){let r=W.dirname(i);if(r===i)break;e.push(W.basename(i)),i=r}let n=await yi.realpath(i);return W.resolve(n,...e.reverse())}async function Nd(t){try{return(await yi.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function aa(t){let e=W.resolve(t);try{(await yi.stat(e)).isDirectory()||(e=W.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let i=e,n=W.resolve(wN.homedir());for(;;){if(!(e===n&&i!==n)){let o=W.join(e,...ra.split("/")),s=e===i||await yN(o);if(await Xs(o)&&s)return e}if(await Xs(W.join(e,".git")))return e;let a=W.dirname(e);if(a===e)return i;e=a}}function oa(t){return Vt(t)}async function NN(t,e){let i=oa(e),n=W.resolve(t,...i.split("/")),r=await yi.realpath(t),a=await pn(n);if(!hn(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function Qs(t,e){let i=oa(e),n=await NN(t,i),r=W.join(n,"comet");if(await Nd(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([pn(n),pn(r)]);if(!hn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:W.resolve(t),configFile:W.join(t,...ra.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:W.join(r,"specs"),changesDir:W.join(r,"changes"),archiveDir:W.join(r,"archive"),runtimeDir:W.join(r,"runtime"),locksDir:W.join(r,"runtime","locks"),transactionsDir:W.join(r,"runtime","transactions")}}function J(t,e){return hn(W.resolve(t),W.resolve(e))}async function M(t,e){let i=W.resolve(t),n=W.resolve(e);if(!hn(i,n))throw new Error(`Path is outside the Native root: ${e}`);if(await Nd(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[r,a]=await Promise.all([pn(i),pn(n)]);if(!hn(r,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}var Zs=pe;var sa=Qr;function SN(t="docs",e="en"){return Js(t,e)}async function Wt(t){let e=(await Us(t))?.config??null;return e?.native?e:null}async function mn(t){let e=await Wt(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 bd(t){let e=await aa(t.startPath),i=await Wt(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${ra} 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?oa(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??SN(n??"docs"),a=await Qs(e,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as QN}from"fs";import ZN from"path";import{AsyncLocalStorage as kN}from"async_hooks";import{randomUUID as Ed}from"crypto";import{promises as Ee}from"fs";import Cd from"os";import ue from"path";var Sd=16*1024,Rd=".coordinator",EN=5e3,kd=new kN,ca=new Map;function CN(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function RN(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 Pd(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 ec(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)?H(i,n):H(i,n)&&t.size===e.size}function tc(t,e){return ec(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 gi(t,Sd,{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 ${Sd} 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:RN(JSON.parse(e.toString("utf8")),t),identity:Pd(i)}}async function PN(t){return(await tt(t))?.owner??null}function Ad(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==Cd.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=ON(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function AN(t,e){try{await Ee.lstat(e);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Ee.rename(t,e)}catch(i){if(i.code!=="ENOENT")throw i}}async function ic(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(!tc(i.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await Ee.mkdir(e,{recursive:!0});let n=ue.join(e,`${ue.basename(t.file)}.${t.owner.id}.${Ed()}.removed`);try{await Ee.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||!ec(r.identity,t.identity))throw await AN(n,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await Ee.rm(n,{force:!0}),"removed"}function xd(t){return{id:Ed(),pid:process.pid,hostname:Cd.hostname(),createdAt:new Date().toISOString(),operation:t}}async function Td(t,e){let i;try{i=await Ee.open(t,"wx")}catch(n){if(n.code==="EEXIST"){let r=await PN(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(),Pd(await i.stat({bigint:!0}))}finally{await i.close()}}async function xN(t,e){let i=await M(t.nativeRoot,t.locksDir);await Ee.mkdir(i,{recursive:!0});let n=await M(t.nativeRoot,ue.join(i,Rd));await Ee.mkdir(n,{recursive:!0});let r=xd(e),a=ue.join(n,`.${r.id}.tmp`),o=ue.join(n,`${r.id}.claim`);try{let s=await Td(a,r);await Ee.rename(a,o);let c=await tt(o);if(!c||!ec(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 Ee.rm(a,{force:!0})}}async function TN(t){let e=ue.dirname(t.file),i=!1,n=ue.basename(t.file);for(let r of await Ee.readdir(e,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=ue.join(e,r.name);if(ue.resolve(a)!==ue.resolve(t.file))try{let o=await tt(a),s=Ad(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ic(o,e);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function Id(t){let e=await tt(t.file);if(e){if(e.owner.id!==t.owner.id||!tc(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await ic(e,ue.dirname(t.file))}}async function IN(t,e){let i=Date.now()+EN;for(;;){let n=await xN(t,e);if(!await TN(n))return n;if(await Id(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 _N(t){let e=ca.get(t)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=e.then(()=>n);return ca.set(t,r),await e,()=>{i(),ca.get(t)===r&&ca.delete(t)}}async function _d(t,e,i){let n=ue.resolve(t.locksDir),r=kd.getStore();if(r?.has(n))return i();let a=await _N(n);try{let o=await IN(t,e),s=new Map(r??[]);return s.set(n,o),await kd.run(s,async()=>{try{return await i()}finally{await Id(o)}})}finally{a()}}async function vn(t,e,i){return _d(t,`acquire ${e}`,async()=>{let n=await M(t.nativeRoot,t.locksDir);await Ee.mkdir(n,{recursive:!0});let r=await M(t.nativeRoot,ue.join(n,CN(e))),a=xd(i),o=await Td(r,a);return{file:r,nativeRoot:t.nativeRoot,locksDir:n,owner:a,identity:o}})}async function gn(t){await tt(t.file)&&await _d(t,`release ${ue.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(!tc(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let i=ue.join(t.locksDir,Rd);await ic(e,i)})}function ON(t){try{return process.kill(t,0),!0}catch(e){let i=e.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Od(t){return Ad(await tt(t))}import nt from"path";import{TextDecoder as qN}from"util";import{createHash as jN}from"node:crypto";import{constants as la,promises as He}from"node:fs";import $e from"node:path";import{TextDecoder as HN}from"node:util";function fa(t,e){let i=$e.relative(t,e);return i===""||!$e.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${$e.sep}`)}function $N(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function LN(t,e){return H({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function MN(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function ua(t,e){return H({...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 nc(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 FN(t,e,i){let n=$e.resolve(t),r=$e.resolve(e);if(!fa(n,r))throw new Error(`${i} is outside its managed root`);let a=[await nc(n,i)],o=n;for(let s of $e.relative(n,r).split($e.sep).filter(Boolean)){await Jt(a,i),o=$e.join(o,s);let c=await nc(o,i);if(!fa(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()||!LN(i,n)||await He.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function DN(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=$N(t.maxBytes),i=$e.resolve(t.file),n=await FN(t.root,$e.dirname(i),t.label),r=await Promise.all((t.forbiddenRoots??[]).map(f=>nc($e.resolve(f),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=MN(a),s=await He.realpath(i);if(!fa(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(r.some(f=>fa(f.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?la.O_RDONLY:la.O_RDONLY|la.O_NOFOLLOW|la.O_NONBLOCK,l=await He.open(i,c);try{let f=await l.stat();await t.hooks?.afterOpen?.();let[u,d]=await Promise.all([He.lstat(i),He.realpath(i)]);if(await Jt(n,t.label),await Jt(r,t.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!ua(o,f)||!ua(o,u))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let p=await DN(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||!ua(o,m)||!ua(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:p,hash:jN("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function jd(t){let e=await it(t),i;try{i=new HN("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 VN=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),zN=new Set(["id","type","source","target","staged","backup"]),WN=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),JN=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Ld=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var KN=256*1024,ZP=1024*1024,eA=16*1024;var tA=64*1024*1024;var GN=new qN("utf-8",{fatal:!0});function ha(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function pa(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 Md(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function rc(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 da(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function Hd(t,e){if(rc(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 UN(t,e){let i=ha(t,`transaction operations[${e}]`);if(pa(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`);rc(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&rc(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 Fd(t){let e=ha(t,"Native Archive transaction journal");if(pa(e,WN,"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"||!Ld.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(!Md(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(da(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=ha(s,`Archive transaction operations[${c}]`);if(pa(l,JN,`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`);Hd(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Hd(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&da(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(da(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`);da(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 YN(t){let e=ha(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return Fd(e);if(pa(e,VN,"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"||!Ld.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(!Md(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(UN),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 XN(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 Dd(t,e){let i=XN(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 oc(t,e){let i=Dd(t,e);return await Promise.all(Object.values(i).map(n=>M(t.nativeRoot,n))),i}async function sc(t,e,i={}){let n=await oc(t,e),r=await it({root:t.nativeRoot,file:n.journal,maxBytes:KN,label:`Native transaction journal ${e}`,hooks:i.hooks}),a=JSON.parse(GN.decode(r.bytes)),o=YN(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function eb(t,e){let i;try{i=await QN.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 sc(t,n.name);if(r.id!==e&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function tb(t,e){let i=Date.now()+5e3,n=ZN.join(t.locksDir,"root-move.lock");for(;;)try{return await vn(t,"root-move",e)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await Od(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 tb(t,e);try{if(await mn(t.projectRoot),await eb(t,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await gn(r)}}function Bd(t){return Number.isSafeInteger(t)&&t>=1}async function qd(t){if(!Bd(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(!Bd(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 wa}from"crypto";import{spawn as Zd}from"node:child_process";import{promises as X}from"fs";import B from"path";import{createHash as ib}from"crypto";function G(t){return ib("sha256").update(t).digest("hex")}var ma={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},eh=1e3,nb=8*1024*1024,rb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ab=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),ob=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),sb=new Set(["schema","include","exclude","hash"]),cb=new Set(["provider","gitSelection","physicalSelection","projection"]),lb=new Set(["provider","selection"]),ub=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),fb=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),db=new Set(["schema","status","before","after"]),hb=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),pb=new Set(["path","hash","size","type","gitObjectId"]),mb=new Set(["path","size","type","reason"]),vb=new Set(["ref","hash","count"]),gb=new Set(["change-created","legacy-migration","explicit"]),wb=new Set(["file","directory","other"]),yb=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"]),ya=/^[a-f0-9]{64}$/u,th=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Nb=new Set(["EACCES","EPERM"]),Si=64*1024,hc=64*1024,bb=6e4,Sb=1e3,kb=2,ih={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Eb={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Cb(t){let e=t.deadlineMs??bb;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 _(t){return Le(t)>=1}function cc(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 wn(t){return t.code==="GIT_SNAPSHOT_TIMEOUT"}function Rb(t){let e={...Eb,...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 Pb(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&&B.win32.isAbsolute(n)?B.win32.resolve(n):"C:\\Windows",a=B.win32.join(r,"System32","taskkill.exe");if(!B.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,f=null,u=(d,p=!1)=>{c||(c=!0,f&&clearTimeout(f),p&&l?.kill("SIGKILL"),s(d))};try{l=Zd(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>u(!1)),l.once("close",d=>u(d===0)),f=setTimeout(()=>u(!1,!0),Sb),f.unref()}catch{u(!1)}});for(let s=0;s<kb;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 mc(t,e,i,n){let r=Le(t);if(r<1)throw cc();let a=t.gitProcess,o=Zd(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 f=new Promise(p=>{o.once("close",p)}),u=setTimeout(()=>{c=!0,l=Pb(o,a).then(()=>({error:null}),p=>({error:p}))},r);u.unref();let d=f.then(async p=>{if(clearTimeout(u),c){let m=await l;throw m?.error?cc(m.error):cc()}return{code:p,spawnError:s}});return{child:o,completion:d}}function Ab(t){let e={...ih,...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 va(t,e,i,n=hc){let{child:r,completion:a}=mc(t,e,i,!1),o=[],s=[],c=0,l=0,f=!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&&(f=!0)}),r.stderr.on("data",p=>{if(c>=Si)return;let m=Si-c,h=Buffer.from(p).subarray(0,m);s.push(h),c+=h.byteLength});let{code:u,spawnError:d}=await a;if(u===0&&d===null&&!f)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 lc(t){return{hash:t.digest,recordCount:t.recordCount,storedRecordCount:t.records.length,stdoutBytes:t.stdoutBytes,overflow:t.overflow}}function uc(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}=mc(t,e,i,n.stdin!==void 0),c=[],l=wa("sha256"),f=[],u=0,d=0,p=0,m=0,h=Buffer.alloc(0),v=!1,N=!1,b=!1,y=w=>{let k=0;for(;k<w.byteLength;){let g=w.indexOf(0,k),E=g<0?w.byteLength:g,S=w.subarray(k,E);if(!v&&S.byteLength>0&&(h.byteLength+S.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,N=!0):h=Buffer.concat([h,S])),g<0)break;m+=1,h.byteLength===0&&!v&&(b=!0);let C=h.byteLength+1;!v&&m<=n.maxRecords&&p+C<=n.maxBytes?(c.push(h),p+=C):N=!0,h=Buffer.alloc(0),v=!1,k=g+1}};o.stdout.on("data",w=>{l.update(w),d+=w.byteLength,d>n.maxBytes&&(N=!0);let k=n.outputChunkBytes;if(k===void 0){y(w);return}for(let g=0;g<w.byteLength;g+=k)y(w.subarray(g,Math.min(w.byteLength,g+k)))}),o.stderr.on("data",w=>{if(u>=Si)return;let k=Si-u,g=Buffer.from(w).subarray(0,k);f.push(g),u+=g.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:w,spawnError:k})=>{let g=n.acceptedExitCodes??[0];if(w!==null&&g.includes(w)&&k===null&&!b&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:N,recordCount:m,stdoutBytes:d});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:b||h.byteLength>0||v?": malformed NUL-delimited output":f.length>0?`: ${Buffer.concat(f).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function Vd(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 xb(t,e,i){let{child:n,completion:r}=mc(t,e,i,!1),a=[],o=0,s=!1;n.stdout.on("data",f=>{f.byteLength>0&&(s=!0)}),n.stderr.on("data",f=>{if(o>=Si)return;let u=Si-o,d=Buffer.from(f).subarray(0,u);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 ga(t){let e=t.endsWith("/")?t.slice(0,-1):t;return e.length===0||e.includes("\\")||B.posix.isAbsolute(e)||/^[A-Za-z]:/u.test(e)||B.posix.normalize(e)!==e||e===".."||e.startsWith("../")||e.includes("\0")?null:e}function Tb(t,e){return t.map(i=>{let n=ga(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${e} path`);return n})}async function Ib(t){let e=B.resolve(t);for(;;){try{return await X.lstat(B.join(e,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=B.dirname(e);if(i===e)return!1;e=i}}async function nh(t,e,i,n={}){let r={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},a=await uc(t,e,["ls-files","--stage","-z"],r);await n.afterStageBefore?.();let o=await uc(t,e,["ls-files","--cached","--others","--exclude-standard","-z"],r);await n.afterCombined?.();let s=await uc(t,e,["ls-files","--stage","-z"],r);return{stagedBefore:a,combined:o,stagedAfter:s}}function rh(t){return{stageBefore:lc(t.stagedBefore),combined:lc(t.combined),stageAfter:lc(t.stagedAfter)}}async function _b(t,e,i=ih,n={}){if(!await Ib(e))return null;let r;try{r=await va(t,e,["rev-parse","--is-inside-work-tree"])}catch(N){throw wn(N)?N:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:N})}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 nh(t,e,i,n)}catch(N){throw wn(N)?N:new Error("Native Git snapshot provider failed after repository detection",{cause:N})}let{stagedBefore:o,combined:s,stagedAfter:c}=a,l=new Set,f=new Map,u=new Set,d=N=>{for(let b of N){let y=Vd(b),w=y.indexOf(" ");if(w<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let k=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(y.slice(0,w))?.groups;if(!k)throw new Error("Native Git snapshot provider returned a malformed staged header");let g=ga(y.slice(w+1));if(g===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");l.add(g),k.stage==="0"&&f.set(g,k.objectId),k.mode==="160000"&&k.stage==="0"&&u.add(g)}};d(o.records),d(c.records);let p=s.records.map(Vd),m=Tb(p,"combined"),h=new Set(m.filter(N=>!l.has(N))),v=new Set(m.filter((N,b)=>!l.has(N)&&p[b].endsWith("/")));for(let N of u)v.delete(N);return{tracked:l,trackedObjectIds:f,untracked:h,gitlinks:u,nestedRepositories:v,omissions:[],overflow:null,evidence:null,initialFence:rh(a)}}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 zd(t){return t.stageBefore.overflow||t.combined.overflow||t.stageAfter.overflow}function Ob(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 jb(t,e,i,n,r){let a;try{a=await nh(t,e,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(f){throw wn(f)?f:new Error("Native Git snapshot provider failed during its final selection fence",{cause:f})}let o=n.initialFence,s=rh(a),c=zd(o)||zd(s),l=Ob(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
|
|
146
|
-
${JSON.stringify({maxNodes:t.limits.maxNodes,maxBytes:t.limits.maxBytes,maxPathBytes:t.limits.maxPathBytes})}`):
|
|
147
|
-
${JSON.stringify({visitedNodeCount:l,recordCount:f,encodedBytes:u,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
|
|
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=Zr(e),n=yi(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=Zr(e),n=yi(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())}}};gd.Parser=Ys});var kd=R(dn=>{"use strict";var wd=Fs(),Xy=nn(),fn=on(),Qy=Ho(),Zy=$(),eN=Us(),yd=Xs();function Nd(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new eN.LineCounter||null,prettyErrors:e}}function tN(t,e={}){let{lineCounter:i,prettyErrors:n}=Nd(e),r=new yd.Parser(i?.addNewLine),a=new wd.Composer(e),o=Array.from(a.compose(r.parse(t)));if(n&&i)for(let s of o)s.errors.forEach(fn.prettifyError(t,i)),s.warnings.forEach(fn.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function bd(t,e={}){let{lineCounter:i,prettyErrors:n}=Nd(e),r=new yd.Parser(i?.addNewLine),a=new wd.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 fn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(fn.prettifyError(t,i)),o.warnings.forEach(fn.prettifyError(t,i))),o}function iN(t,e,i){let n;typeof e=="function"?n=e:i===void 0&&e&&typeof e=="object"&&(i=e);let r=bd(t,i);if(!r)return null;if(r.warnings.forEach(a=>Qy.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 nN(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 Zy.isDocument(t)&&!n?t.toString(i):new Xy.Document(t,n,i).toString(i)}dn.parse=iN;dn.parseAllDocuments=tN;dn.parseDocument=bd;dn.stringify=nN});var ia=R(D=>{"use strict";var rN=Fs(),aN=nn(),oN=gs(),Qs=on(),sN=Bi(),kt=$(),cN=gt(),lN=ie(),uN=yt(),fN=Nt(),dN=Xr(),hN=Gs(),pN=Us(),mN=Xs(),ta=kd(),Sd=$i();D.Composer=rN.Composer;D.Document=aN.Document;D.Schema=oN.Schema;D.YAMLError=Qs.YAMLError;D.YAMLParseError=Qs.YAMLParseError;D.YAMLWarning=Qs.YAMLWarning;D.Alias=sN.Alias;D.isAlias=kt.isAlias;D.isCollection=kt.isCollection;D.isDocument=kt.isDocument;D.isMap=kt.isMap;D.isNode=kt.isNode;D.isPair=kt.isPair;D.isScalar=kt.isScalar;D.isSeq=kt.isSeq;D.Pair=cN.Pair;D.Scalar=lN.Scalar;D.YAMLMap=uN.YAMLMap;D.YAMLSeq=fN.YAMLSeq;D.CST=dN;D.Lexer=hN.Lexer;D.LineCounter=pN.LineCounter;D.Parser=mN.Parser;D.parse=ta.parse;D.parseAllDocuments=ta.parseAllDocuments;D.parseDocument=ta.parseDocument;D.stringify=ta.stringify;D.visit=Sd.visit;D.visitAsync=Sd.visitAsync});import{promises as IE}from"fs";var Da=wo(ia(),1);import{promises as Wh}from"fs";import ot from"path";import{createHash as yN}from"node:crypto";import{promises as je}from"node:fs";import Ee from"node:path";import{TextDecoder as NN}from"node:util";import Zs from"path";var vN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),gN=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function wN(t){return t.toLowerCase().startsWith(".env")}function it(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>wN(n))?"environment-file":i.some(n=>gN.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>vN.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Ed(t,e){let i=it(e);if(i)return i;let n=Zs.resolve(t.projectRoot,...e.split("/")),r=Zs.relative(t.projectRoot,t.nativeRoot).replaceAll("\\","/"),a=e.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===Zs.resolve(t.configFile)?"native-runtime":null}function St(t){return t!==0&&t!==0n&&t!=="0"}function le(t,e){return St(t.dev)&&St(e.dev)&&St(t.ino)&&St(e.ino)}function j(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 ra=1024*1024;function ec(t,e){let i=Ee.relative(t,e);return i===""||!Ee.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ee.sep}`)}function bN(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=it(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 kN(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function SN(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function na(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return le(i,n)?j(i,n):j(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Cd(t){let e=await je.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await je.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function EN(t,e){let i=Ee.resolve(t),n=Ee.resolve(e);if(!ec(i,n))throw new Error("Native artifact path is outside its root");let r=[await Cd(i)],a=i;for(let o of Ee.relative(i,n).split(Ee.sep).filter(Boolean)){a=Ee.join(a,o);let s=await Cd(a);if(!ec(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Rd(t){for(let e of t){let i=await je.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!SN(e,i)||await je.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function Ke(t){let e=bN(t.ref),i=kN(t.maxBytes??ra),n=Ee.resolve(t.root,...e.split("/")),r=await EN(t.root,Ee.dirname(n));await t.hooks?.afterParentChainCaptured?.();let a=await je.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 je.realpath(n);if(!ec(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await je.open(n,"r");try{let[c,l,f]=await Promise.all([s.stat(),je.lstat(n),je.realpath(n)]);if(await Rd(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!na(a,c)||!na(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let y=i+1-d,w=await s.read(p,0,Math.min(p.length,y),null);if(w.bytesRead===0)break;if(d+=w.bytesRead,d>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);u.push(Buffer.from(p.subarray(0,w.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),je.lstat(n),je.realpath(n)]);if(await Rd(r),!h.isFile()||h.isSymbolicLink()||v!==o||!na(c,m)||!na(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let b=Buffer.concat(u,d),N;try{N=new NN("utf-8",{fatal:!0}).decode(b)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:y})}return{ref:e,size:d,hash:yN("sha256").update(b).digest("hex"),text:N}}finally{await s.close()}}import{randomUUID as CN}from"crypto";import{promises as ue}from"fs";import He from"path";function ic(t,e){let i=He.relative(t,e);return i===""||!He.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${He.sep}`)}function RN(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function tc(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return le(i,n)?j(i,n):j(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Pd(t){let e=await ue.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 ue.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function hn(t){for(let e of t){let i=await ue.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!RN(e,i)||await ue.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function PN(t,e){let i=He.resolve(t),n=He.resolve(e);if(!ic(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let r=[await Pd(i)],a=He.relative(i,n).split(He.sep).filter(Boolean),o=i;for(let s of a){await hn(r),o=He.join(o,s);try{await ue.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Pd(o);if(!ic(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await hn(r),r}async function AN(t){let e;try{e=await ue.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 xN(t,e,i={}){let n=He.dirname(t),r=i.containedRoot?await PN(i.containedRoot,n):null;r||await ue.mkdir(n,{recursive:!0});let a=He.join(n,`.${He.basename(t)}.${CN()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await ue.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([ue.lstat(a),ue.realpath(a)]);if(await hn(r),!c.isFile()||c.isSymbolicLink()||!tc(s,c)||!ic(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(),!tc(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 hn(r);let c=await ue.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!tc(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await ue.link(a,t),await ue.unlink(a)):await ue.rename(a,t),await AN(n)}catch(c){if(await o?.close(),!r)await ue.rm(a,{force:!0});else try{await hn(r),await ue.rm(a,{force:!0})}catch{}throw c}}async function Wt(t,e,i={}){await xN(t,e,i)}async function Ce(t,e,i={}){await Wt(t,JSON.stringify(e,null,2)+`
|
|
143
|
+
`,i)}var rc=wo(ia(),1);import aa from"path";var mn=64*1024,oa=1024,sa=64,ac=5,TN=[".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/**"],ge={include:["**/*"],exclude:[...TN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function IN(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||aa.posix.isAbsolute(i)||aa.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 zt(t){let e=IN(t,"native.artifact_root");return e.length===0?".":e.join("/")}function xd(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 oc(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||aa.posix.isAbsolute(n)||aa.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 pn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Td(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 ca(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>oa)throw new Error(`${e} exceeds ${oa} 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>sa)throw new Error(`${e} contains more than ${sa} wildcard tokens`);return t}function Ad(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=>ca(n,e)))].sort((n,r)=>n.localeCompare(r,"en"))}function nc(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 _N(t){if(t===void 0)return{...ge,include:[...ge.include],exclude:[...ge.exclude]};let e=pn(t,"native.snapshot");return{include:Ad(e.include,"native.snapshot.include",ge.include),exclude:Ad(e.exclude,"native.snapshot.exclude",ge.exclude),max_files:nc(e.max_files,ge.max_files,"native.snapshot.max_files"),max_total_bytes:nc(e.max_total_bytes,ge.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:nc(e.max_duration_ms,ge.max_duration_ms,"native.snapshot.max_duration_ms")}}function ON(t){if(t===void 0)return;let e=pn(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=pn(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=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 f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:i,fromArtifactRoot:zt(n),toArtifactRoot:zt(r),stage:a,...o?{cleanup:o}:{}}}function jN(t,e={}){let i=pn(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??ac;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=ON(i.pending_root_move);return{artifact_root:zt(n),language:Td(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:_N(i.snapshot),...s?{pending_root_move:s}:{}}}function HN(t){let e=pn(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:xd(e.artifact_layout),language:Td(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function $N(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function FN(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 vn(t,e={}){let i=(0,rc.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=$N(r.ambient_resume),o=r.native===void 0?void 0:jN(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=r.classic===void 0?void 0:HN(r.classic),c=FN(r,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function la(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:zt(t),language:e,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:ac,snapshot:{...ge,include:[...ge.include],exclude:[...ge.exclude]}}}}import{createHash as MN}from"crypto";import{promises as da}from"fs";import Et from"path";import{constants as ua,promises as Jt}from"fs";var $e=class extends Error{reason;constructor(e,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=e}};function sc(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Id(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function gn(t){return{dev:t.dev,ino:t.ino,birthtime:sc(t)}}function fa(t,e){let i=gn(t),n=gn(e);return le(i,n)?j(i,n):j(i,n)&&sc(t)===sc(e)&&Id(t)===Id(e)&&t.size===e.size}async function Ni(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 Jt.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 Jt.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:gn(a)});let s=process.platform==="win32"?ua.O_RDONLY:ua.O_RDONLY|ua.O_NOFOLLOW|ua.O_NONBLOCK,c;try{c=await Jt.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,f,u]=await Promise.all([c.stat({bigint:r}),Jt.lstat(t,{bigint:r}),Jt.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!fa(a,l)||!fa(a,f))throw new $e("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:u,identity:gn(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:y}=await c.read(m,0,Math.min(m.length,N),null);if(y===0)break;if(p+=y,p>e)throw new $e("too-large",`${n} exceeds ${e} bytes`);d.push(Buffer.from(m.subarray(0,y)))}await i.hooks?.beforeFinalCheck?.();let[h,v,b]=await Promise.all([c.stat({bigint:r}),Jt.lstat(t,{bigint:r}),Jt.realpath(t)]);if(!v.isFile()||v.isSymbolicLink()||b!==o||!fa(a,h)||!fa(a,v))throw new $e("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:gn(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:b}}finally{await c.close()}}function LN(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function cc(t,e){let i=Et.relative(t,e);return i===""||!Et.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Et.sep}`)}async function _d(t,e){let i=Et.resolve(t),n=await da.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return da.realpath(i)}async function Od(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 da.lstat(r)}catch(f){if(LN(f))return{exists:!1,kind:"missing"};throw f}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 da.realpath(r);if(!cc(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 wn(t,e,i){let n=oc(e,i.label),r=Et.resolve(t),a=await _d(r,i.label),o=n.split("/"),s=Et.resolve(r,...o);if(!cc(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Od(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Gt(t,e,i,n){let r=await wn(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 _d(r.projectRoot,n.label);return Ni(r.target,i,{...n,verify:async(o,s)=>{if(!cc(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Od(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var yn=".comet/config.yaml";function BN(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function lc(t,e={}){return(await ha(t,e)).document}async function DN(t){try{return(await Gt(t,yn,mn,{label:yn})).bytes}catch(e){if(BN(e))return null;throw e}}function qN(t){return t?{exists:!0,sha256:MN("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function ha(t,e={}){let i=await DN(t);return{document:i?vn(i.toString("utf8"),e):null,identity:qN(i)}}var eA=16*1024;import{promises as bi}from"fs";import W from"path";import GN from"os";var ma=".comet/config.yaml";async function dc(t){try{return await bi.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function KN(t){try{let e=await bi.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Nn(t,e){let i=W.relative(t,e);return i===""||!W.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${W.sep}`)}async function bn(t){let e=[],i=t;for(;!await dc(i);){let r=W.dirname(i);if(r===i)break;e.push(W.basename(i)),i=r}let n=await bi.realpath(i);return W.resolve(n,...e.reverse())}async function Hd(t){try{return(await bi.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function va(t){let e=W.resolve(t);try{(await bi.stat(e)).isDirectory()||(e=W.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let i=e,n=W.resolve(GN.homedir());for(;;){if(!(e===n&&i!==n)){let o=W.join(e,...ma.split("/")),s=e===i||await KN(o);if(await dc(o)&&s)return e}if(await dc(W.join(e,".git")))return e;let a=W.dirname(e);if(a===e)return i;e=a}}function ga(t){return zt(t)}async function UN(t,e){let i=ga(e),n=W.resolve(t,...i.split("/")),r=await bi.realpath(t),a=await bn(n);if(!Nn(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function hc(t,e){let i=ga(e),n=await UN(t,i),r=W.join(n,"comet");if(await Hd(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([bn(n),bn(r)]);if(!Nn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:W.resolve(t),configFile:W.join(t,...ma.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:W.join(r,"specs"),changesDir:W.join(r,"changes"),archiveDir:W.join(r,"archive"),runtimeDir:W.join(r,"runtime"),locksDir:W.join(r,"runtime","locks"),transactionsDir:W.join(r,"runtime","transactions")}}function z(t,e){return Nn(W.resolve(t),W.resolve(e))}async function F(t,e){let i=W.resolve(t),n=W.resolve(e);if(!Nn(i,n))throw new Error(`Path is outside the Native root: ${e}`);if(await Hd(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[r,a]=await Promise.all([bn(i),bn(n)]);if(!Nn(r,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}var pc=ge;var wa=ca;function XN(t="docs",e="en"){return la(t,e)}async function Kt(t){let e=(await lc(t))?.config??null;return e?.native?e:null}async function kn(t){let e=await Kt(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 va(t.startPath),i=await Kt(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${ma} 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?ga(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??XN(n??"docs"),a=await hc(e,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as Pb}from"fs";import Ab from"path";import{AsyncLocalStorage as QN}from"async_hooks";import{randomUUID as Md}from"crypto";import{promises as Re}from"fs";import Bd from"os";import he from"path";var Fd=16*1024,Dd=".coordinator",ZN=5e3,Ld=new QN,ya=new Map;function eb(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function tb(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 mc(t,e){let i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},n={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return le(i,n)?j(i,n):j(i,n)&&t.size===e.size}function vc(t,e){return mc(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function nt(t){let e,i;try{let n=await Ni(t,Fd,{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 ${Fd} 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:tb(JSON.parse(e.toString("utf8")),t),identity:qd(i)}}async function ib(t){return(await nt(t))?.owner??null}function Vd(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==Bd.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=cb(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function nb(t,e){try{await Re.lstat(e);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Re.rename(t,e)}catch(i){if(i.code!=="ENOENT")throw i}}async function gc(t,e){let i=await nt(t.file);if(!i)return"missing";if(i.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!vc(i.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await Re.mkdir(e,{recursive:!0});let n=he.join(e,`${he.basename(t.file)}.${t.owner.id}.${Md()}.removed`);try{await Re.rename(t.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await nt(n);if(!r||r.owner.id!==t.owner.id||!mc(r.identity,t.identity))throw await nb(n,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await Re.rm(n,{force:!0}),"removed"}function Wd(t){return{id:Md(),pid:process.pid,hostname:Bd.hostname(),createdAt:new Date().toISOString(),operation:t}}async function zd(t,e){let i;try{i=await Re.open(t,"wx")}catch(n){if(n.code==="EEXIST"){let r=await ib(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 rb(t,e){let i=await F(t.nativeRoot,t.locksDir);await Re.mkdir(i,{recursive:!0});let n=await F(t.nativeRoot,he.join(i,Dd));await Re.mkdir(n,{recursive:!0});let r=Wd(e),a=he.join(n,`.${r.id}.tmp`),o=he.join(n,`${r.id}.claim`);try{let s=await zd(a,r);await Re.rename(a,o);let c=await nt(o);if(!c||!mc(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 Re.rm(a,{force:!0})}}async function ab(t){let e=he.dirname(t.file),i=!1,n=he.basename(t.file);for(let r of await Re.readdir(e,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=he.join(e,r.name);if(he.resolve(a)!==he.resolve(t.file))try{let o=await nt(a),s=Vd(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await gc(o,e);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function Jd(t){let e=await nt(t.file);if(e){if(e.owner.id!==t.owner.id||!vc(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await gc(e,he.dirname(t.file))}}async function ob(t,e){let i=Date.now()+ZN;for(;;){let n=await rb(t,e);if(!await ab(n))return n;if(await Jd(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 sb(t){let e=ya.get(t)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=e.then(()=>n);return ya.set(t,r),await e,()=>{i(),ya.get(t)===r&&ya.delete(t)}}async function Gd(t,e,i){let n=he.resolve(t.locksDir),r=Ld.getStore();if(r?.has(n))return i();let a=await sb(n);try{let o=await ob(t,e),s=new Map(r??[]);return s.set(n,o),await Ld.run(s,async()=>{try{return await i()}finally{await Jd(o)}})}finally{a()}}async function Sn(t,e,i){return Gd(t,`acquire ${e}`,async()=>{let n=await F(t.nativeRoot,t.locksDir);await Re.mkdir(n,{recursive:!0});let r=await F(t.nativeRoot,he.join(n,eb(e))),a=Wd(i),o=await zd(r,a);return{file:r,nativeRoot:t.nativeRoot,locksDir:n,owner:a,identity:o}})}async function En(t){await nt(t.file)&&await Gd(t,`release ${he.basename(t.file)}`,async()=>{let e=await nt(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!vc(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let i=he.join(t.locksDir,Dd);await gc(e,i)})}function cb(t){try{return process.kill(t,0),!0}catch(e){let i=e.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Kd(t){return Vd(await nt(t))}import at from"path";import{TextDecoder as gb}from"util";import{createHash as lb}from"node:crypto";import{constants as Na,promises as Fe}from"node:fs";import Le from"node:path";import{TextDecoder as ub}from"node:util";function ka(t,e){let i=Le.relative(t,e);return i===""||!Le.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Le.sep}`)}function fb(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function db(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function hb(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function ba(t,e){return j({...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 wc(t,e){let i=await Fe.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await Fe.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function pb(t,e,i){let n=Le.resolve(t),r=Le.resolve(e);if(!ka(n,r))throw new Error(`${i} is outside its managed root`);let a=[await wc(n,i)],o=n;for(let s of Le.relative(n,r).split(Le.sep).filter(Boolean)){await Ut(a,i),o=Le.join(o,s);let c=await wc(o,i);if(!ka(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ut(a,i),a}async function Ut(t,e){for(let i of t){let n=await Fe.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!db(i,n)||await Fe.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function mb(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 rt(t){let e=fb(t.maxBytes),i=Le.resolve(t.file),n=await pb(t.root,Le.dirname(i),t.label),r=await Promise.all((t.forbiddenRoots??[]).map(f=>wc(Le.resolve(f),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Ut(n,t.label);let a=await Fe.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=hb(a),s=await Fe.realpath(i);if(!ka(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(r.some(f=>ka(f.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?Na.O_RDONLY:Na.O_RDONLY|Na.O_NOFOLLOW|Na.O_NONBLOCK,l=await Fe.open(i,c);try{let f=await l.stat();await t.hooks?.afterOpen?.();let[u,d]=await Promise.all([Fe.lstat(i),Fe.realpath(i)]);if(await Ut(n,t.label),await Ut(r,t.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!ba(o,f)||!ba(o,u))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let p=await mb(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),Fe.lstat(i),Fe.realpath(i)]);if(await Ut(n,t.label),await Ut(r,t.label),!h.isFile()||h.isSymbolicLink()||v!==s||!ba(o,m)||!ba(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:p,hash:lb("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Ud(t){let e=await rt(t),i;try{i=new ub("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 wb=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),yb=new Set(["id","type","source","target","staged","backup"]),Nb=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),bb=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Qd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var kb=256*1024,WA=1024*1024,zA=16*1024;var JA=64*1024*1024;var Sb=new gb("utf-8",{fatal:!0});function Ea(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Ca(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 Zd(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function yc(t,e){if(typeof t!="string"||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 root`)}function Sa(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function Yd(t,e){if(yc(t,e),t.includes("\\")||t!==at.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 Eb(t,e){let i=Ea(t,`transaction operations[${e}]`);if(Ca(i,yb,`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`);yc(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&yc(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 eh(t){let e=Ea(t,"Native Archive transaction journal");if(Ca(e,Nb,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!Qd.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!Zd(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Sa(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=e.operations.map((s,c)=>{let l=Ea(s,`Archive transaction operations[${c}]`);if(Ca(l,bb,`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`);Yd(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Yd(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&Sa(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Sa(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Sa(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=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 Cb(t){let e=Ea(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return eh(e);if(Ca(e,wb,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!Qd.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!at.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!at.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!Zd(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let i=e.operations.map(Eb),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 Rb(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return at.join(t.transactionsDir,e)}function th(t,e){let i=Rb(t,e);return{directory:i,journal:at.join(i,"transaction.json"),events:at.join(i,"events.jsonl"),staged:at.join(i,"staged"),backups:at.join(i,"backups")}}async function bc(t,e){let i=th(t,e);return await Promise.all(Object.values(i).map(n=>F(t.nativeRoot,n))),i}async function kc(t,e,i={}){let n=await bc(t,e),r=await rt({root:t.nativeRoot,file:n.journal,maxBytes:kb,label:`Native transaction journal ${e}`,hooks:i.hooks}),a=JSON.parse(Sb.decode(r.bytes)),o=Cb(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function xb(t,e){let i;try{i=await Pb.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 kc(t,n.name);if(r.id!==e&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function Tb(t,e){let i=Date.now()+5e3,n=Ab.join(t.locksDir,"root-move.lock");for(;;)try{return await Sn(t,"root-move",e)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await Kd(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 Ue(t,e,i,n){let r=await Tb(t,e);try{if(await kn(t.projectRoot),await xb(t,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await En(r)}}function ih(t){return Number.isSafeInteger(t)&&t>=1}async function nh(t){if(!ih(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(!ih(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 xa}from"crypto";import{spawn as hh}from"node:child_process";import{promises as X}from"fs";import H from"path";import{createHash as Ib}from"crypto";function K(t){return Ib("sha256").update(t).digest("hex")}var Ra={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},ph=1e3,_b=8*1024*1024,Ob=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jb=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),Hb=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),$b=new Set(["schema","include","exclude","hash"]),Fb=new Set(["provider","gitSelection","physicalSelection","projection"]),Lb=new Set(["provider","selection"]),Mb=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Bb=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),Db=new Set(["schema","status","before","after"]),qb=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Vb=new Set(["path","hash","size","type","gitObjectId"]),Wb=new Set(["path","size","type","reason"]),zb=new Set(["ref","hash","count"]),Jb=new Set(["change-created","legacy-migration","explicit"]),Gb=new Set(["file","directory","other"]),Kb=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"]),Ta=/^[a-f0-9]{64}$/u,mh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Ub=new Set(["EACCES","EPERM"]),Ri=64*1024,Pc=64*1024,Yb=6e4,Xb=1e3,Qb=2,vh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Zb={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function ek(t){let e=t.deadlineMs??Yb;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 I(t){return Me(t)>=1}function Sc(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 Ei(t){return t.code==="GIT_SNAPSHOT_TIMEOUT"}function tk(t){let e={...Zb,...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 ik(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&&H.win32.isAbsolute(n)?H.win32.resolve(n):"C:\\Windows",a=H.win32.join(r,"System32","taskkill.exe");if(!H.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,f=null,u=(d,p=!1)=>{c||(c=!0,f&&clearTimeout(f),p&&l?.kill("SIGKILL"),s(d))};try{l=hh(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>u(!1)),l.once("close",d=>u(d===0)),f=setTimeout(()=>u(!1,!0),Xb),f.unref()}catch{u(!1)}});for(let s=0;s<Qb;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 Tc(t,e,i,n){let r=Me(t);if(r<1)throw Sc();let a=t.gitProcess,o=hh(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 f=new Promise(p=>{o.once("close",p)}),u=setTimeout(()=>{c=!0,l=ik(o,a).then(()=>({error:null}),p=>({error:p}))},r);u.unref();let d=f.then(async p=>{if(clearTimeout(u),c){let m=await l;throw m?.error?Sc(m.error):Sc()}return{code:p,spawnError:s}});return{child:o,completion:d}}function nk(t){let e={...vh,...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 Aa(t,e,i,n=Pc){let{child:r,completion:a}=Tc(t,e,i,!1),o=[],s=[],c=0,l=0,f=!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&&(f=!0)}),r.stderr.on("data",p=>{if(c>=Ri)return;let m=Ri-c,h=Buffer.from(p).subarray(0,m);s.push(h),c+=h.byteLength});let{code:u,spawnError:d}=await a;if(u===0&&d===null&&!f)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 Ec(t){return{hash:t.digest,recordCount:t.recordCount,storedRecordCount:t.records.length,stdoutBytes:t.stdoutBytes,overflow:t.overflow}}function Pa(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}=Tc(t,e,i,n.stdin!==void 0),c=[],l=xa("sha256"),f=[],u=0,d=0,p=0,m=0,h=Buffer.alloc(0),v=!1,b=!1,N=!1,y=w=>{let E=0;for(;E<w.byteLength;){let g=w.indexOf(0,E),S=g<0?w.byteLength:g,k=w.subarray(E,S);if(!v&&k.byteLength>0&&(h.byteLength+k.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,b=!0):h=Buffer.concat([h,k])),g<0)break;m+=1,h.byteLength===0&&!v&&(N=!0);let C=h.byteLength+1;!v&&m<=n.maxRecords&&p+C<=n.maxBytes?(c.push(h),p+=C):b=!0,h=Buffer.alloc(0),v=!1,E=g+1}};o.stdout.on("data",w=>{l.update(w),d+=w.byteLength,d>n.maxBytes&&(b=!0);let E=n.outputChunkBytes;if(E===void 0){y(w);return}for(let g=0;g<w.byteLength;g+=E)y(w.subarray(g,Math.min(w.byteLength,g+E)))}),o.stderr.on("data",w=>{if(u>=Ri)return;let E=Ri-u,g=Buffer.from(w).subarray(0,E);f.push(g),u+=g.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:w,spawnError:E})=>{let g=n.acceptedExitCodes??[0];if(w!==null&&g.includes(w)&&E===null&&!N&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:b,recordCount:m,stdoutBytes:d});return}a(new Error(`git ${i.join(" ")} failed${E?`: ${E.message}`:N||h.byteLength>0||v?": malformed NUL-delimited output":f.length>0?`: ${Buffer.concat(f).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function Ac(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 rk(t,e,i){let{child:n,completion:r}=Tc(t,e,i,!1),a=[],o=0,s=!1;n.stdout.on("data",f=>{f.byteLength>0&&(s=!0)}),n.stderr.on("data",f=>{if(o>=Ri)return;let u=Ri-o,d=Buffer.from(f).subarray(0,u);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 Ci(t){let e=t.endsWith("/")?t.slice(0,-1):t;return e.length===0||e.includes("\\")||H.posix.isAbsolute(e)||/^[A-Za-z]:/u.test(e)||H.posix.normalize(e)!==e||e===".."||e.startsWith("../")||e.includes("\0")?null:e}function ak(t,e){return t.map(i=>{let n=Ci(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${e} path`);return n})}async function ok(t){let e=H.resolve(t);for(;;){try{return await X.lstat(H.join(e,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=H.dirname(e);if(i===e)return!1;e=i}}async function gh(t,e,i,n={}){let r=H.resolve(e.projectRoot),a=H.join(r,".comet","current-change.json"),s=["--",".",...[e.nativeRoot,e.configFile,a].map(d=>{let p=H.relative(r,H.resolve(d)).replaceAll("\\","/"),m=Ci(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 Pa(t,r,["ls-files","--stage","-z",...s],c);await n.afterStageBefore?.();let f=await Pa(t,r,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await n.afterCombined?.();let u=await Pa(t,r,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:f,stagedAfter:u}}function wh(t){return{stageBefore:Ec(t.stagedBefore),combined:Ec(t.combined),stageAfter:Ec(t.stagedAfter)}}async function sk(t,e,i=vh,n={}){let r=H.resolve(e.projectRoot);if(!await ok(r))return null;let a;try{a=await Aa(t,r,["rev-parse","--is-inside-work-tree"])}catch(N){throw Ei(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 gh(t,e,i,n)}catch(N){throw Ei(N)?N:new Error("Native Git snapshot provider failed after repository detection",{cause:N})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,f=new Set,u=new Map,d=new Set,p=N=>{for(let y of N){let w=Ac(y),E=w.indexOf(" ");if(E<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(w.slice(0,E))?.groups;if(!g)throw new Error("Native Git snapshot provider returned a malformed staged header");let S=Ci(w.slice(E+1));if(S===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");f.add(S),g.stage==="0"&&u.set(S,g.objectId),g.mode==="160000"&&g.stage==="0"&&d.add(S)}};p(s.records),p(l.records);let m=c.records.map(Ac),h=ak(m,"combined"),v=new Set(h.filter(N=>!f.has(N))),b=new Set(h.filter((N,y)=>!f.has(N)&&m[y].endsWith("/")));for(let N of d)b.delete(N);return{tracked:f,trackedObjectIds:u,untracked:v,gitlinks:d,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:wh(o)}}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 rh(t){return t.stageBefore.overflow||t.combined.overflow||t.stageAfter.overflow}function ck(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 lk(t,e,i,n,r){let a;try{a=await gh(t,e,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(f){throw Ei(f)?f:new Error("Native Git snapshot provider failed during its final selection fence",{cause:f})}let o=n.initialFence,s=wh(a),c=rh(o)||rh(s),l=ck(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:K(`comet.native.git-selection-overflow.v2
|
|
145
|
+
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var uk=(1n<<256n)-1n;function fk(t){return t.isFile()?"file":t.isDirectory()?"directory":t.isSymbolicLink()?"symlink":"other"}async function ah(t){let e=H.resolve(t.paths.projectRoot),i=H.resolve(t.paths.nativeRoot),n=H.resolve(t.paths.configFile),r=H.join(e,".comet","current-change.json"),a=[],o=[],s=Buffer.alloc(32),c=0n,l=0,f=0,u=0,d=!1,p=!1,m=!1,h=()=>Me(t.execution)>=1?!0:(d=!0,m=!0,!1),v=y=>{let w=Buffer.from(`${y.type}\0${y.path}`,"utf8"),E=xa("sha256").update("comet.native.physical-selection-record.v1\0").update(w).digest();for(let g=0;g<s.length;g+=1)s[g]^=E[g];if(c=c+BigInt(`0x${E.toString("hex")}`)&uk,f+=1,u+=w.byteLength,Buffer.byteLength(y.path,"utf8")>t.limits.maxPathBytes||u>t.limits.maxBytes){d=!0,m=!0;return}a.push(y)},b=async y=>{if(m||!h())return;let w;try{w=await X.opendir(y)}catch(C){if(!h())return;if(!re(C)&&!ne(C)||y===e&&re(C))throw C;p||=ne(C),d||=re(C),m=!0;return}if(!h()){try{await w.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let E=!1,g;try{for(;!m&&h();){let C;try{C=await w.read()}catch(U){if(!h())break;if(!re(U)&&!ne(U)||y===e&&re(U))throw U;p||=ne(U),d||=re(U),m=!0;break}if(!h()||C===null)break;if(l+=1,l>t.limits.maxNodes){d=!0,m=!0;break}let B=H.join(y,C.name),G=mk(e,B);if(B===n||B===r||Pt(i,B)||t.denylist.some(U=>Pt(U,B))||it(G)!==null)continue;if(!h())break;let M;try{M=await X.lstat(B)}catch(U){if(!h())break;if(!re(U)&&!ne(U))throw U;if(p=!0,v({path:G,type:"other"}),o.push({path:G,size:null,type:"file",reason:re(U)?"unreadable":"changed-during-read"}),await t.hooks?.afterNode?.(G),m||!h())break;continue}if(!h())break;let V=fk(M);if(V==="directory"){if(yk(t.policy,G))continue;if(!h())break;let U;try{U=await X.realpath(B)}catch(We){if(!h())break;if(!re(We)&&!ne(We))throw We;if(p=!0,v({path:G,type:V}),o.push({path:G,size:null,type:"directory",reason:re(We)?"unreadable":"changed-during-read"}),await t.hooks?.afterNode?.(G),m||!h())break;continue}if(!h())break;if(!z(t.physicalProjectRoot,U)||Pt(t.physicalNativeRoot,U))continue;if(v({path:G,type:V}),await t.hooks?.afterNode?.(G),!h()||(await b(B),m))break;continue}if(v({path:G,type:V}),await t.hooks?.afterNode?.(G),!h()||m)break}}catch(C){E=!0,g=C}let S;try{await w.close()}catch(C){S=C}let k=h();if(E)throw g;if(k&&S!==void 0&&S.code!=="ERR_DIR_CLOSED")throw S};await b(e),h(),d?(a.length=0,f=0,u=0):(a.sort((y,w)=>y.path.localeCompare(w.path,"en")),o.sort((y,w)=>y.path.localeCompare(w.path,"en")));let N=d?K(`comet.native.physical-selection-incomplete.v1
|
|
146
|
+
${JSON.stringify({maxNodes:t.limits.maxNodes,maxBytes:t.limits.maxBytes,maxPathBytes:t.limits.maxPathBytes})}`):K(`comet.native.physical-selection.v1
|
|
147
|
+
${JSON.stringify({visitedNodeCount:l,recordCount:f,encodedBytes:u,xor:s.toString("hex"),sum:c.toString(16).padStart(64,"0")})}`);return{records:a,omissions:o,evidence:{hash:N,visitedNodeCount:l,recordCount:f,storedRecordCount:a.length,encodedBytes:u,overflow:d,unstable:p}}}function yh(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 dk(t,e){let i=t.overflow||e.overflow,n=t.unstable||e.unstable||!yh(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 hk(t){return[...new Set([...t.tracked,...t.untracked])].sort((e,i)=>e.localeCompare(i,"en"))}async function oh(t,e){let n=(await Aa(t,e,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!mh.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return K(`gitlink:${n}`)}async function sh(t,e){let i=await oh(t,e),n=await rk(t,e,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await oh(t,e);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function pk(t,e){if(it(e)!==null)return!1;let i=H.resolve(t.projectRoot,...e.split("/"));return!Pt(H.resolve(t.nativeRoot),i)}function mk(t,e){return H.relative(t,e).split(H.sep).join("/")}function vk(t,e){return e.map(i=>H.resolve(t,...i.split(/[\\/]/u)))}function Pt(t,e){let i=H.resolve(t),n=H.resolve(e);return n===i||z(i,n)}function re(t){return Ub.has(t.code??"")}function ne(t){return t.code==="ENOENT"}function Nh(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
148
|
+
`)}function gk(t,e){return K(`comet.native.snapshot-policy.v1
|
|
149
|
+
${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function Cc(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 wk(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function ch(t){let e=wa(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?wk(r):void 0;if(a&&!a())return!1;let o=Cc(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 f=i[l];f&&(f.kind==="literal"&&f.value===s||f.kind==="question"&&s!=="/"?c.add(l+1):f.kind==="star"&&s!=="/"||f.kind==="globstar"?c.add(l):f.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Cc(i,c,a),o===null||o.size===0)return!1}return Cc(i,o,a)?.has(i.length)??!1}}function bh(t){if(t===void 0)return;let e=[...new Set(t.include.map(r=>wa(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(t.exclude.map(r=>wa(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=gk(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(ch),excludeMatchers:i.map(ch),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 yk(t,e){return t?.excludedDirectoryPrefixes.includes(e)??!1}function lh(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 Rc(t,e,i){let n=JSON.stringify(i);return K(`${t}
|
|
150
150
|
${Buffer.byteLength(e)}:${e}
|
|
151
|
-
${Buffer.byteLength(n)}:${n}`)}function pc(t){return t.reason==="git-enumeration-limit"||t.reason==="git-selection-changed"||t.reason==="physical-enumeration-limit"||t.reason==="physical-selection-changed"}function Yd(t){for(let e=t.length-1;e>=0;e-=1){let i=t[e];if(!pc(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)?H(i,n):H(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Wb(t,e,i,n){if(!_(n))return{status:"budget-exhausted"};let r;try{r=await X.open(t,"r")}catch(c){if(!_(n))return{status:"budget-exhausted"};throw c}if(!_(n))return await r.close(),{status:"budget-exhausted"};let a=wa("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 f=await r.read(o,0,Math.min(o.length,l),null);if(!_(n))return{status:"budget-exhausted"};if(f.bytesRead===0){if(!_(n))return{status:"budget-exhausted"};let u=await r.stat();return _(n)?!u.isFile()||!Et(c,u)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:u}:{status:"budget-exhausted"}}if(s+f.bytesRead>e)return{status:"changed"};a.update(o.subarray(0,f.bytesRead)),s+=f.bytesRead}}finally{await r.close()}}function Ce(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 bi(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 ch(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=B.posix.normalize(t);if(i!==t||B.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function Jb(t,e){let i=Ce(t,`Native snapshot entry ${e}`);Re(i,pb,`Native snapshot entry ${e}`);let n=ch(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!ya.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"||!th.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function Kb(t,e){let i=Ce(t,`Native snapshot omission ${e}`);if(Re(i,mb,`Native snapshot omission ${e}`),!wb.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!yb.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:ch(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 Gb(t){let e=Ce(t,"Native snapshot omission overflow");if(Re(e,vb,"Native snapshot omission overflow"),typeof e.hash!="string"||!ya.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:bi(e.count,"Native snapshot omission overflow count")}}function Ni(t,e){let i=Ce(t,e);if(Re(i,fb,e),typeof i.hash!="string"||!ya.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 Xd(t){let e=Ce(t,"Native Git selection evidence");if(Re(e,ub,"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=Ni(e.stageBefore,"Native Git selection stageBefore"),n=Ni(e.combined,"Native Git selection combined"),r=Ni(e.stageAfter,"Native Git selection stageAfter"),a=Ni(e.finalStageBefore,"Native Git selection finalStageBefore"),o=Ni(e.finalCombined,"Native Git selection finalCombined"),s=Ni(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(u=>u.overflow),l=!Ct(i,r)||!Ct(r,a)||!Ct(n,o)||!Ct(a,s),f=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!==f)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:f,stageBefore:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Qd(t,e){let i=Ce(t,e);if(Re(i,hb,e),typeof i.hash!="string"||!ya.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 Ub(t){let e=Ce(t,"Native physical selection evidence");if(Re(e,db,"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=Qd(e.before,"Native physical selection before"),n=Qd(e.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!ah(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=Ce(t,"Native content snapshot manifest");if(Re(e,ab,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!gb.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let g=Ce(e.capture,"Native content snapshot capture");if(Re(g,cb,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let E=g.gitSelection===void 0?void 0:Xd(g.gitSelection),S=g.physicalSelection===void 0?void 0:Ub(g.physicalSelection),C=null;if(g.projection!==void 0){let D=Ce(g.projection,"Native content snapshot projection");if(Re(D,lb,"Native content snapshot projection"),D.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");C={provider:"git",...D.selection===void 0?{}:{selection:Xd(D.selection)}}}if(g.provider==="git"){if(S||C)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...E?{gitSelection:E}:{}}}else{if(E)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(S&&C)throw new Error("Native physical-tree capture cannot combine selection and projection");i=C?{provider:"physical-tree",projection:C}:{provider:"physical-tree",...S?{physicalSelection:S}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=Ce(e.limits,"Native content snapshot limits");Re(n,ob,"Native content snapshot limits");let r={maxFiles:bi(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:bi(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:bi(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:bi(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:bi(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let g=Ce(e.policy,"Native snapshot policy");if(Re(g,sb,"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=sh({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(Jb),s=e.omitted.map(Kb),c=Je(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:Gb(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,E)=>g+E.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 f=c-s.length;if(f===0&&l||f>0&&l?.count!==f)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 u=s.filter(g=>g.reason==="git-enumeration-limit"),d=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...u,...d])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(u.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!==(u.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"),N=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...v,...N])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||N.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=i?.physicalSelection,y=b?.status==="overflow"||b?.status==="overflow-and-changed",w=b?.status==="changed"||b?.status==="overflow-and-changed";if(y!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(w!==(N.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(oh(k)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}function Yb(t,e){if(!rb.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=B.join(t.changesDir,e);if(!J(t.changesDir,i))throw new Error("Native change path escaped");return B.join(i,"runtime","baseline-manifest.json")}async function lh(t,e={}){let i={maxFiles:e.limits?.maxFiles??ma.maxFiles,maxFileBytes:e.limits?.maxFileBytes??ma.maxFileBytes,maxTotalBytes:e.limits?.maxTotalBytes??ma.maxTotalBytes,maxManifestBytes:e.limits?.maxManifestBytes??ma.maxManifestBytes,...e.limits?.maxDurationMs===void 0?{}:{maxDurationMs:e.limits.maxDurationMs}},n=sh(e.policy),r=Cb({...e,deadlineMs:e.deadlineMs??i.maxDurationMs}),a=Ab(e.gitSelectionLimits),o=Rb(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=B.resolve(t.projectRoot),c=await X.realpath(s),l=B.resolve(t.nativeRoot),f=await X.realpath(l),u=B.resolve(t.configFile),d=B.join(s,".comet","current-change.json"),p=Bb(s,e.denylist??[]),m=[],h=[],v=new Map,N=new Map,b=0,y=0,w=G("comet.native.snapshot-omission-overflow.v1"),k=0,g=!1,E=null,S=P=>{y+=1,w=dc(w,"omission",P)},C=P=>{if(b+=1,h.length<eh){h.push(P);return}if(pc(P)){let A=Yd(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");S(A),h.push(P);return}S(P)},D=P=>{b+=P.count,y+=P.count,w=dc(w,"git-selection",{source:"git-selection",...P})},K=P=>{y+=1,w=dc(w,"manifest-entry",{reason:"manifest-size",entry:P})},F=async(P,A)=>{m.push(P),k+=P.size,v.set(P.path,A),g||(g=!0,await e.gitSelectionHooks?.afterFirstEntryCaptured?.(P.path))},z=(P,A)=>{let T=m.findIndex(Q=>Q.path===P);if(T<0)return;let[j]=m.splice(T,1);k-=j.size,v.delete(P),C(A)},Y=async(P,A,T,j)=>{if(!T.isFile()||T.isSymbolicLink()||!_(r))return;let Q;try{Q=await X.realpath(P)}catch(I){if(!_(r))return;if(!ie(I)&&!te(I))throw I;C({path:A,size:T.size,type:"file",reason:te(I)?"changed-during-read":"unreadable"});return}if(!_(r)||!J(c,Q)||Rt(f,Q))return;if(m.length>=i.maxFiles){C({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){C({path:A,size:T.size,type:"file",reason:"file-size"});return}if(k+T.size>i.maxTotalBytes){C({path:A,size:T.size,type:"file",reason:"total-size"});return}let L,O,x;try{if(L=await Wb(Q,T.size,T,r),L.status==="budget-exhausted"||!_(r))return;if(L.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!_(r)||(x=await X.realpath(P),!_(r)))return;O=await X.lstat(P)}catch(I){if(!_(r))return;if(!ie(I)&&!te(I))throw I;C({path:A,size:T.size,type:"file",reason:te(I)?"changed-during-read":"unreadable"});return}if(_(r)){if(L.bytes!==T.size||x!==Q||!Et(T,L.finalStat)||!Et(L.finalStat,O)||!O.isFile()||O.isSymbolicLink()||O.size!==T.size||O.mtimeMs!==T.mtimeMs||O.ctimeMs!==T.ctimeMs){C({path:A,size:O.isFile()?O.size:null,type:O.isFile()?"file":"other",reason:"changed-during-read"});return}_(r)&&await F({path:A,hash:L.hash,size:O.size,type:"file",...j===void 0?{}:{gitObjectId:j}},{kind:"file",target:P,realTarget:Q,stat:O})}},qe=async(P,A,T)=>{if(!_(r))return;let j,Q,L;try{if(j=await X.readlink(P,{encoding:"buffer"}),!_(r)||(L=await X.lstat(P),!_(r)))return;Q=await X.readlink(P,{encoding:"buffer"})}catch(I){if(!_(r))return;if(!ie(I)&&!te(I))throw I;C({path:A,size:null,type:"other",reason:te(I)?"changed-during-read":"unreadable"});return}if(!_(r))return;if(!L.isSymbolicLink()||!Et(T,L)||L.mtimeMs!==T.mtimeMs||L.ctimeMs!==T.ctimeMs||!j.equals(Q)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let O=j.byteLength;if(m.length>=i.maxFiles){C({path:A,size:O,type:"other",reason:"file-count"});return}if(O>i.maxFileBytes){C({path:A,size:O,type:"other",reason:"file-size"});return}if(k+O>i.maxTotalBytes){C({path:A,size:O,type:"other",reason:"total-size"});return}let x=wa("sha256").update("symlink\0").update(j).digest("hex");_(r)&&await F({path:A,hash:x,size:O,type:"file"},{kind:"symlink",target:P,rawTarget:j,stat:L})},Ve=async()=>{for(let[P,A]of[...v]){if(!_(r))return;if(A.kind==="file"){let O,x;try{if(O=await X.realpath(A.target),!_(r))return;x=await X.lstat(A.target)}catch(I){if(!_(r))return;if(!ie(I)&&!te(I))throw I;z(P,{path:P,size:null,type:"file",reason:ie(I)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(O!==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)&&z(P,{path:P,size:x.isFile()?x.size:null,type:x.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let O,x;try{if(O=await X.lstat(A.target),!_(r))return;x=await X.readlink(A.target,{encoding:"buffer"})}catch(I){if(!_(r))return;if(!ie(I)&&!te(I))throw I;z(P,{path:P,size:null,type:"other",reason:ie(I)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(!O.isSymbolicLink()||!Et(A.stat,O)||O.mtimeMs!==A.stat.mtimeMs||O.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(x))&&z(P,{path:P,size:null,type:"other",reason:"changed-during-read"});continue}let T,j;try{if(T=await X.realpath(A.target),!_(r))return;j=await X.lstat(A.target)}catch{if(!_(r))return;z(P,{path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;if(!(T===A.realTarget&&j.isDirectory()&&!j.isSymbolicLink()&&Et(A.stat,j)&&J(c,T)&&!Rt(f,T))){z(P,{path:P,size:null,type:"directory",reason:"gitlink-changed"});continue}let L;try{if(!_(r))return;L=await Kd(r,T)}catch(O){if(wn(O))throw O;z(P,{path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;L.dirty?z(P,{path:P,size:null,type:"directory",reason:"gitlink-dirty"}):L.hash!==A.hash&&z(P,{path:P,size:null,type:"directory",reason:"gitlink-changed"})}for(let[P,A]of N){if(!_(r))return;try{let T=await X.lstat(A);if(!_(r))return;C({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(te(T))continue;if(!ie(T))throw T;C({path:P,size:null,type:"file",reason:"unreadable"})}}},ve=await _b(r,s,a,e.gitSelectionHooks);if(ve===null){let P=await Wd({execution:r,paths:t,physicalProjectRoot:c,physicalNativeRoot:f,denylist:p,policy:n,limits:o,hooks:e.physicalSelectionHooks});await e.physicalSelectionHooks?.afterInitialSelection?.();for(let j of P.records){if(j.type!=="file"&&j.type!=="symlink"||v.has(j.path))continue;if(Le(r)<1)break;if(!Ud(n,j.path,r))continue;if(Le(r)<1)break;let Q=B.resolve(s,...j.path.split("/")),L;try{L=await X.lstat(Q)}catch(O){if(!_(r))break;if(!ie(O)&&!te(O))throw O;C({path:j.path,size:null,type:"file",reason:te(O)?"changed-during-read":"unreadable"});continue}if(Le(r)<1)break;if(j.type==="symlink"&&L.isSymbolicLink()){if(await qe(Q,j.path,L),Le(r)<1)break;continue}if(j.type!=="file"||!L.isFile()||L.isSymbolicLink()){C({path:j.path,size:L.isFile()?L.size:null,type:L.isDirectory()?"directory":L.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Y(Q,j.path,L),Le(r)<1)break}Le(r)>=1&&await Ve();let A=await Wd({execution:r,paths:t,physicalProjectRoot:c,physicalNativeRoot:f,denylist:p,policy:n,limits:o}),T=Lb(P.evidence,A.evidence);E=T.evidence;for(let j of[...P.omissions,...A.omissions,...T.omissions])h.some(Q=>Q.path===j.path&&Q.reason===j.reason)||C(j)}else{await e.gitSelectionHooks?.afterInitialSelection?.();let P=e.incrementalBaseline,A=new Map,T=!1;if(P){let x=yn(P);for(let I of x.entries)I.gitObjectId!==void 0&&A.set(I.path,I);T=A.size>0}let j=new Set,Q=!0;try{let x=await va(r,s,["ls-files","--modified","-z"],hc);for(let I of x.toString("utf8").split("\0")){let ae=ga(I);ae!==null&&j.add(ae)}}catch{T=!1,Q=!1,A.clear()}let L=new Set,O=new Set;for(let x of Mb(ve)){if(v.has(x)||!Fb(t,x))continue;if(Le(r)<1)break;if(!Ud(n,x,r))continue;if(Le(r)<1)break;let I=B.resolve(s,...x.split("/"));if(I===u||I===d||p.some(we=>Rt(we,I)))continue;if(ve.gitlinks.has(x)){if(m.length>=i.maxFiles){C({path:x,size:0,type:"file",reason:"file-count"});continue}let we,Jn;try{[we,Jn]=await Promise.all([X.realpath(I),X.lstat(I)])}catch{C({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Jn.isSymbolicLink()||!Jn.isDirectory()||!J(c,we)||Rt(f,we)){C({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let ai=await Kd(r,we);if(ai.dirty){C({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await F({path:x,hash:ai.hash,size:0,type:"file"},{kind:"gitlink",target:I,realTarget:we,stat:Jn,hash:ai.hash})}catch(ai){if(wn(ai))throw ai;C({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ae;try{ae=await X.lstat(I)}catch(we){if(te(we)&&ve.tracked.has(x)){N.set(x,I);continue}if(!ie(we)&&!te(we))throw we;C({path:x,size:null,type:"file",reason:te(we)?"changed-during-read":"unreadable"});continue}if(ae.isSymbolicLink()){await qe(I,x,ae);continue}if(!ae.isFile()){ve.nestedRepositories.has(x)||C({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let xe=ve.trackedObjectIds.get(x),ge=xe?A.get(x):void 0;if(T&&ge?.gitObjectId!==void 0&&ge.gitObjectId===xe&&!j.has(x)){if(m.length>=i.maxFiles){C({path:x,size:ge.size,type:"file",reason:"file-count"});continue}if(ge.size>i.maxFileBytes){C({path:x,size:ge.size,type:"file",reason:"file-size"});continue}if(k+ge.size>i.maxTotalBytes){C({path:x,size:ge.size,type:"file",reason:"total-size"});continue}m.push({...ge}),k+=ge.size,L.add(x);continue}let ml=Q&&!j.has(x)?xe:void 0;await Y(I,x,ae,ml),ml!==void 0&&O.add(x)}if(await Ve(),await e.gitSelectionHooks?.afterContentRevalidation?.(),await jb(r,s,a,ve,e.gitSelectionHooks?.outputChunkBytes),L.size>0||T&&O.size>0){let x=await va(r,s,["ls-files","--modified","-z"],hc),I=new Set;for(let ae of x.toString("utf8").split("\0")){let xe=ga(ae);xe!==null&&I.add(xe)}for(let ae of L){if(!I.has(ae))continue;let xe=m.find(ge=>ge.path===ae);z(ae,{path:ae,size:xe?.size??null,type:"file",reason:"changed-during-read"})}for(let ae of O){if(!I.has(ae))continue;let xe=m.find(ge=>ge.path===ae);xe&&delete xe.gitObjectId}}for(let x of ve.omissions)C(x);ve.overflow&&D(ve.overflow)}m.sort((P,A)=>P.path.localeCompare(A.path,"en")),h.sort((P,A)=>P.path.localeCompare(A.path,"en"));let sm=ve===null?{provider:"physical-tree",...E?{physicalSelection:E}:{}}:{provider:"git",...ve.evidence?{gitSelection:ve.evidence}:{}},pl=()=>({schema:"comet.native.content-snapshot.v1",origin:e.origin??"explicit",capture:sm,createdAt:(e.now??new Date).toISOString(),complete:b===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:b,...y>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${w}`,hash:w,count:y}}:{}}),to=pl();for(;oh(to)>i.maxManifestBytes;){if(h.filter(A=>!pc(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let j=Yd(h);if(j===null)break;S(j)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))b+=1,K(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");to=pl()}return to}async function Na(t,e,i={}){let r=(await Wt(t.projectRoot))?.native.snapshot??Zs;return lh(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 uh(t,e){let i=Yb(t,e);await M(t.nativeRoot,i);try{let n=await jd({root:t.nativeRoot,file:i,maxBytes:nb,label:"Native baseline snapshot manifest"});return yn(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as hS}from"crypto";import bc 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 fe}from"node:fs";import Ne from"node:path";import{TextDecoder as sS}from"node:util";import nS from"path";var fh=(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(nS.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 rS(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 dh(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"),f=Number(t.iteration);if(!Number.isInteger(f)||f<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:fh(t,"current_step"),iteration:f,pending:fh(t,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:rS(t)}}var mx=256*1024;var aS=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function oS(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=dh(e);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function ba(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=>!aS.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 oS(e)}var ye={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 kn(t,e){let i=Ne.relative(t,e);return i===""||!Ne.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ne.sep}`)}function ph(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function Sn(t,e){return H({...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 cS(t,e){return H({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function ki(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=Ne.resolve(t),a=Ne.resolve(r,...n.split("/"));if(!kn(r,a))throw new Error("Native Run path must stay inside its change");return a}async function hh(t){let e=await fe.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native Run 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 vc(t,e){let i=Ne.resolve(t),n=Ne.resolve(e);if(!kn(i,n))throw new Error("Native Run path is outside its change");let r=[await hh(i)],a=i;for(let o of Ne.relative(i,n).split(Ne.sep).filter(Boolean)){a=Ne.join(a,o);let s;try{s=await hh(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!kn(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function ka(t){for(let e of t){let i=await fe.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!cS(e,i)||await fe.realpath(e.path)!==e.realPath)throw new Error(`Native Run parent changed during I/O: ${e.path}`)}}async function lS(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 vc(t,Ne.dirname(e));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await fe.lstat(e)}catch(u){if(u.code==="ENOENT")return null;throw u}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=ph(o),c=await fe.realpath(e);if(!kn(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,f;try{f=await fe.open(e,l)}catch(u){throw new Error(`${n} changed while opening`,{cause:u})}try{let[u,d,p]=await Promise.all([f.stat(),fe.lstat(e),fe.realpath(e)]);if(await ka(a),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==c||!Sn(s,u)||!Sn(s,d))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await lS(f,i,n);await r?.beforeFinalCheck?.();let[h,v,N]=await Promise.all([f.stat(),fe.lstat(e),fe.realpath(e)]);if(await ka(a),!v.isFile()||v.isSymbolicLink()||N!==c||!Sn(s,h)||!Sn(s,v))throw new Error(`${n} changed while reading`);let b;try{b=new sS("utf-8",{fatal:!0}).decode(m)}catch(y){throw new Error(`${n} is not valid UTF-8`,{cause:y})}return{text:b,target:{exists:!0,identity:s,realPath:c}}}finally{await f.close()}}async function uS(t,e,i){let n=await vc(t,Ne.dirname(e));if(!n)return{exists:!1};let r;try{r=await fe.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 fe.realpath(e);if(!kn(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await ka(n),{exists:!0,identity:ph(r),realPath:a}}async function fS(t,e,i,n){let r=await vc(t,Ne.dirname(e));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await fe.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()||!Sn(i.identity,a)||await fe.realpath(e)!==i.realPath)throw new Error(`${n} changed before commit`);await ka(r)}async function gc(t){if(Buffer.byteLength(t.content,"utf8")>t.maxBytes)throw new Error(`${t.label} exceeds ${t.maxBytes} bytes`);let i=t.expected??await uS(t.changeDir,t.file,t.label);if(i.exists&&i.identity.size>t.maxBytes)throw new Error(`${t.label} exceeds ${t.maxBytes} bytes`);await qt(t.file,t.content,{containedRoot:t.changeDir,beforeCommit:async()=>{await t.hooks?.beforeCommit?.(),await fS(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 dS(t,e){try{return JSON.parse(t)}catch(i){throw new Error(`${e} contains invalid JSON`,{cause:i})}}function mh(t){return`${JSON.stringify(t,null,2)}
|
|
152
|
-
`}function
|
|
153
|
-
`;if(Buffer.byteLength(a,"utf8")>
|
|
154
|
-
`)])}catch(u){if(!
|
|
155
|
-
`);function Tn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function kh(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 Rc(t){if(!Sh.test(t))throw new Error(`Invalid Native change name: ${t}`)}function AS(t){if(!Sh.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function Eh(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 xS(t,e){let i=Tn(t,`spec_changes[${e}]`);if(kh(i,kS,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(AS(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"&&Eh(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"||!Cc.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"||!Cc.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 TS(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 Pc(t,e){if(kh(t,e,At),typeof t.name!="string")throw new Error("Native change name is required");if(Rc(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"||!ES.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&&!CS.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(xS),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"||!RS.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"&&Eh(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!TS(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 In(t){let e=Tn(t,At);if(e.schema!==Gt)throw new Error(`Expected ${Gt}`);return{schema:Gt,...Pc(e,bS)}}function xn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function kc(t,e,i){if(t===null)return null;let n=typeof t=="string"?PS.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 IS(t){if(t==null)return null;if(typeof t!="string"||!Cc.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function _S(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 _n(t){let e=Tn(t,At);if(e.schema!==Kt)throw new Error(`Expected ${Kt}`);if(xn(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Kt} minimum_runtime_version must be 2`);return{schema:Kt,minimum_runtime_version:2,revision:xn(e.revision,"Native v2 revision"),...Pc(e,bh)}}function ot(t){let e=Tn(t,At);if(e.schema!==Pt){if(e.schema===Gt||e.schema===Kt){let o=e.schema===Gt?In(e):_n(e);throw new Pn(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=xn(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=xn(e.revision,"Native revision"),r=Pc(e,SS),a=IS(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:_S(e.verification_protocol),...r,approved_contract_hash:a,implementation_scope:kc(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:kc(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:kc(e.partial_allowance,"Native partial_allowance","allowances")}}function OS(t){let e=Tn(t,At);if(e.schema===Gt){let r=In(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Pt}`}}if(e.schema===Kt){let r=_n(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 Ut(typeof e.schema=="string"?e.schema:"(missing)",r).message}}let i=xn(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 Ec(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 U(t,e){Rc(e);let i=at.join(t.changesDir,e);if(!J(t.changesDir,i))throw new Error("Native change path escaped");return i}async function On(t,e){let i=at.join(U(t,e),"runtime","schema-migration.json");await M(t.nativeRoot,i);try{return await yh.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Ch(t,e){let i=at.join(U(t,e),"runtime","checkpoint-journal.json");await M(t.nativeRoot,i);try{return await yh.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var jS=256*1024;async function Rh(t,e=at.dirname(t)){let i=at.relative(e,t).split(at.sep).join("/"),n=await et({root:e,ref:i,maxBytes:jS}),r=(0,Ra.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 HS(t,e){let i=at.join(U(t,e),At);await M(t.nativeRoot,i);let n=OS(await Rh(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 $S(t,n.state),n)}async function $S(t,e){if(await uh(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function Pe(t,e){let i=await HS(t,e);if(i.status==="migration-required")throw new Pn(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Ut(i.schema,i.minimumRuntimeVersion);return i.state}async function LS(t,e,i){let n={...e,schema:Pt,minimum_runtime_version:3,revision:i+1},r=await qd({expectedRevision:i,next:n,read:async()=>{let a=ot(await Rh(t));if(a.name!==e.name)throw new Error(`Native change file/name mismatch: ${e.name}`);return a},write:a=>qt(t,(0,Ra.stringify)(Ec(a))),equals:(a,o)=>JSON.stringify(Ec(a))===JSON.stringify(Ec(o)),conflict:a=>new An(e.name,i,a)});return Object.assign(e,r),r}async function Pa(t,e,i,n){if(await mn(t.projectRoot),await On(t,e.name))throw new Pn(e.name,e.schema);if(!n?.allowPendingCheckpointRecovery&&await Ch(t,e.name))throw new Error(`Native progress checkpoint recovery is required for ${e.name} before another state write`);if((await Pe(t,e.name)).verification_protocol!==e.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Ea(t,e.name);let a=at.join(U(t,e.name),At);return await M(t.nativeRoot,a),LS(a,e,i)}import jn from"path";var MS=/\b(Bearer|Basic)\s+[^\s"']+/giu,FS=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,DS=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,BS=/\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,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)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,VS=/(["'])((?:[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 Ge(t){return t.replace(MS,"$1 [REDACTED]").replace(FS,"[REDACTED PRIVATE KEY]").replace(DS,"$1[REDACTED]@").replace(BS,"[REDACTED TOKEN]").replace(qS,'$1"[REDACTED]"').replace(VS,"$1$2$1$3$4[REDACTED]$4").replace(zS,"$1$2[REDACTED]")}var Aa={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Pi=/^[a-f0-9]{64}$/u;function xa(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Ta(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 Ph(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ac(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function WS(t){let e=t.trim().replaceAll("\\","/");if(e.length===0||jn.isAbsolute(e)||/^(?:[A-Za-z]:|~|\/)/u.test(e)||e.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${t}`);let i=jn.posix.normalize(e);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${t}`);return i}function JS(t,e){return jn.join(U(t,e),"runtime","checkpoints","progress.json")}function xc(t,e){return jn.join(U(t,e),"runtime","checkpoint-journal.json")}function Ah(t,e,i){if(!Pi.test(i))throw new Error("Native checkpoint manifest hash is invalid");return jn.join(U(t,e),"runtime","checkpoints","manifests",`${i}.json`)}function KS(t){if(!Pi.test(t))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${t}.json`}async function xh(t,e,i){let n=await it({root:t,file:e,maxBytes:Aa.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function GS(t,e){let i=xa(t,`checkpoint manifest artifact ${e}`);Ta(i,["path","hash","size"],`checkpoint manifest artifact ${e}`);let n=WS(xt(i.path,`checkpoint artifact ${e} path`,4096)),r=Ze(n);if(r)throw new Error(`checkpoint artifact ${e} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!Pi.test(i.hash))throw new Error(`checkpoint artifact ${e} hash is invalid`);return{path:n,hash:i.hash,size:Ac(i.size,`checkpoint artifact ${e} size`)}}function Ia(t,e){let i=xa(t,"Native checkpoint manifest");if(Ta(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>Aa.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(GS),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=Ac(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>Aa.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 Tc(t){return G(JSON.stringify(Ia(t,t.change)))}function Th(t,e){let i=xa(t,"Native progress checkpoint");if(Ta(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=Ph(i.previousRevision,"Native checkpoint previousRevision"),a=Ph(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(!Pi.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=KS(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(!Pi.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 f=Ac(i.artifactCount,"Native checkpoint artifactCount");if(f>Aa.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let u=xt(i.summary,"Native checkpoint summary"),d=xt(i.nextAction,"Native checkpoint nextAction");if(Ge(u)!==u||Ge(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:u,nextAction:d,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:f,createdAt:l}}function US(t,e){let i=xa(t,"Native checkpoint journal");if(Ta(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=Th(i.checkpoint,e),o=Ia(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(!Pi.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!==Tc(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 Ih(t,e,i){let n=Ah(t,e,i);await M(t.nativeRoot,n);let r=await xh(t.nativeRoot,n,"Native checkpoint manifest"),a=Ia(r,e);if(Ic(t,a),Tc(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function _h(t,e){let i=xc(t,e);await M(t.nativeRoot,i);try{let n=US(await xh(t.nativeRoot,i,"Native checkpoint journal"),e);return Ic(t,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Oh(t,e,i,n){let r=Ia(i,e);Ic(t,r);let a=Tc(r),o=Ah(t,e,a);await M(t.nativeRoot,o);try{let s=await Ih(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 ke(o,r,{containedRoot:t.nativeRoot,beforeCommit:n?.beforeCommit}),a}function Ic(t,e){for(let i of e.artifacts){let n=sd(t,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function jh(t,e){let i=Th(e,e.change),n=await Ih(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=JS(t,e.change);await M(t.nativeRoot,a),await ke(a,i,{containedRoot:t.nativeRoot})}import{promises as Tk}from"fs";import Ik from"path";import{isDeepStrictEqual as Uc}from"util";import{createHash as YS}from"crypto";function Me(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function XS(t,e){e.has(t)&&Me("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)||Me("sparse arrays are not supported");return(i.length!==t.length||i.some((n,r)=>n!==String(r)))&&Me("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&Me("symbol properties are not supported"),`[${t.map(n=>_c(n,e)).join(",")}]`}finally{e.delete(t)}}function QS(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&Me("only plain objects are supported"),e.has(t)&&Me("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&Me("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))&&Me("accessor properties are not supported"),`${JSON.stringify(o)}:${_c(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function _c(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)||Me("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?XS(t,e):QS(t,e);case"bigint":case"function":case"symbol":case"undefined":return Me(`${typeof t} values are not supported`)}return Me("unsupported value type")}function _a(t){return _c(t,new Set)}function V(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 YS("sha256").update(`${t}
|
|
156
|
-
${
|
|
157
|
-
|
|
158
|
-
${
|
|
159
|
-
|
|
160
|
-
`);let i=0;Jh(t.baseline,t.current,r=>{if(i>=t.detailedChangeCount){Tt(e,"change",r);let a=0;for(let o of t.declaredArtifacts)$a(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 Uh(t,e,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=gk(t,e,r,i.gitChangedPaths),s=V(Hn,t),c=V(Hn,e),l=[];for(let[g,E]of[["baseline",t],["current",e]])for(let S of E.omitted){if(l.length>=ok)break;l.push(st({kind:"snapshot-omission",source:g,path:S.path,evidence:{reason:S.reason,size:S.size,type:S.type}},`${g} snapshot omitted ${S.path}: ${S.reason}`))}let f=t.omitted.length+e.omitted.length,u=[...Mh("baseline",t),...Mh("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(E=>g.has(E)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(E=>!g.has(E))}},p=g=>{let E=o.candidates.slice(0,g.detailedChangeCount),S=E.filter(Ve=>Ve.attributedTo.length===0),C=o.totalChanges-E.length,D=o.totalUnattributed-S.length,K=f-g.detailedOmissionCount,F=D+K,z=[...S.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),...u,...C>0||F>0?[Gh(g.overflowHash,{changes:C,unattributed:D,unresolved:F})]:[]],Y=mk(z),qe=g.includeGitAdvisory?d():void 0;return{schema:jc,contractHash:n,baselineProjectionRef:Hc(s),baselineProjectionHash:s,currentProjectionRef:Hc(c),currentProjectionHash:c,complete:Y.length===0,declaredArtifacts:r,changes:E,unattributed:S,unresolvedScopes:Y,noCodeReason:a,...qe?{gitAdvisory:qe}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,N="0".repeat(64);for(;;){let g=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:N});if($n({...g,scopeHash:N})<=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 y=o.totalChanges>m||f>h?yk({baseline:t,current:e,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):N,w=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:y}),k={...w,scopeHash:V(zh,w)};if($n(k)>Xt)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return k}function La(t){let e=$c(t.baseline),i=$c(t.current),n=Kh(t);return{authority:n,baseline:e,current:i,scope:Uh(e,i,n)}}var Nk=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"||!Mc.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function Fh(t,e,i){let n=Hc(e);if(t!==n)throw new Error(`${i} ref/hash mismatch`);return n}function ja(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!==Vh)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=$c(n);if(V(Hn,i)!==V(Hn,r))throw new Error("Native snapshot projection is not canonical");let a=V(Hn,r);if(e!==void 0&&Yt(e,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function Fc(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:It(i.path,`Declared artifact ${e} path`),kind:i.kind}}function Dh(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:Ai(i.size,`${e} size`)}}function Bh(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(Fc),r=Ha(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${e} attribution must be sorted and unique`);let a=Dh(i.before,`Implementation change ${e} before`),o=Dh(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 bk(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"?Wh(i.path,`Unresolved scope ${e} path`):It(i.path,`Unresolved scope ${e} path`),reason:i.reason}}function Oa(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(le);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${e} must be sorted and unique`);return i}function Ma(t){let e=ct(t,"Native implementation scope"),i=[...Nk].filter(E=>E!=="gitAdvisory");if(lt(e,i,["gitAdvisory"],"Native implementation scope"),e.schema!==jc)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=Fh(e.baselineProjectionRef,r,"Implementation scope baseline projection"),o=Yt(e.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Fh(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(Fc);if(JSON.stringify(c)!==JSON.stringify(Ha(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=e.changes.map(Bh),f=[...l].sort((E,S)=>le(E.path,S.path));if(JSON.stringify(l)!==JSON.stringify(f)||new Set(l.map(E=>E.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let u=new Set(c.map(E=>`${E.kind}:${E.path}`));if(l.some(E=>E.attributedTo.some(S=>!u.has(`${S.kind}:${S.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(E=>JSON.stringify(E.attributedTo)!==JSON.stringify(c.filter(S=>$a(S,E.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=e.unattributed.map(Bh),p=l.filter(E=>E.attributedTo.length===0);if(JSON.stringify(d)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=e.unresolvedScopes.map(bk),h=m.filter(E=>E.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:wk(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 N=e.noCodeReason,b=[...p.map(E=>st({kind:"unattributed-change",source:"implementation-scope",path:E.path,evidence:{after:E.after,before:E.before,changeKind:E.kind}},`Changed path is not covered by a declared artifact: ${E.path}`)),...l.length+(v?.changes??0)===0&&N===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")]:[]],y=m.filter(E=>E.kind==="unattributed-change"||E.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Lc))||new Set(m.map(E=>E.id)).size!==m.length||JSON.stringify(y)!==JSON.stringify(b.sort(Lc))||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 w;if(e.gitAdvisory!==void 0){let E=ct(e.gitAdvisory,"Implementation scope Git advisory");if(lt(E,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),E.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let S=Oa(E.changedPaths,"Git changed paths"),C=Oa(E.pathsPresentInSnapshotChanges,"Git present paths"),D=Oa(E.pathsAbsentFromSnapshotChanges,"Git absent paths"),K=[...C,...D].sort(le),F=new Set(l.map(z=>z.path));if(JSON.stringify(K)!==JSON.stringify(S)||(v?.changes??0)===0&&C.some(z=>!F.has(z))||D.some(z=>F.has(z)))throw new Error("Implementation scope Git advisory partition is invalid");w={advisoryOnly:!0,changedPaths:S,pathsPresentInSnapshotChanges:C,pathsAbsentFromSnapshotChanges:D}}let k={schema:jc,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:e.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:m,noCodeReason:N,...w?{gitAdvisory:w}:{}},g=Yt(e.scopeHash,"Implementation scope scopeHash");if(V(zh,k)!==g)throw new Error("Implementation scope content hash mismatch");return{...k,scopeHash:g}}function Sk(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(Fc);if(JSON.stringify(i)!==JSON.stringify(Ha(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=Oa(e.gitChangedPaths,"Native implementation scope authority Git paths"));let r=Kh({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 Fa(t){let e=ct(t,"Native implementation scope bundle");lt(e,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=Sk(e.authority),n=ja(e.baseline),r=ja(e.current),a=Ma(e.scope),o=Uh(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 Yh(t){let e=Ma(t.scope);return Fa({authority:{contractHash:e.contractHash,declaredArtifacts:e.declaredArtifacts,noCodeReason:e.noCodeReason,...e.gitAdvisory?{gitChangedPaths:e.gitAdvisory.changedPaths}:{}},baseline:t.baseline,current:t.current,scope:e})}function Dc(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 Ek=/^[a-f0-9]{64}$/u;var Xh=["disposition","overrideSummaryHash","signatureHash"],Ck=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"];function qc(t,e){return t<e?-1:t>e?1:0}function Rk(t,e,i){let n=Object.keys(t).sort(qc);if(n.length!==e.length||n.some((r,a)=>r!==e[a]))throw new Error(`${i} fields are invalid`)}function Pk(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 Bc(t,e){if(typeof t!="string"||!Ek.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function Ak(t){if(!Array.isArray(t)||t.length>Oc.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(qc)}function Qh(t){let e=Pk(t,"Native repair trajectory projection"),i=Object.keys(e).sort(qc),n=i.length===Xh.length&&i.every((l,f)=>l===Xh[f]);n||Rk(e,Ck,"Native repair trajectory projection");let r=Bc(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:Bc(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=Bc(e.contractHash,"Native repair trajectory contract hash"),s=Ak(e.failedAcceptanceIds),c=Hh(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 xi={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:[]},Vc=G("comet-native-runtime:v3:semantic-repair-budget"),xk=[{skillVersion:"2",skillHash:G("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:G("comet-native-runtime:v1")}];function Zh(t){return t.skillVersion===xi.definition.metadata.version&&t.skillHash===Vc||xk.some(e=>e.skillVersion===t.skillVersion&&e.skillHash===t.skillHash)}async function Da(t){let i={sequence:(await Ei(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 gh(t.changeDir,t.run.trajectoryRef,i),i}async function zc(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 wh(t.changeDir,t.run.checkpointRef,e),e}function ep(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"],_k=new Set(cp),lp=new Set([...cp,"minimum_runtime_version","revision"]),Ok=new Set([...lp,"operation"]),jk=512*1024,Jc=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Hk=new Set([...Jc,"implementationScopeHash","repairScopeHash","repairStagnation"]),Kc=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 Yc(t,e){return Ik.join(U(t,e),"runtime","transition.json")}function $k(t){return`transition-${t}`}async function Lk(t,e,i){let n=$k(e);return vn(t,n,i)}async function Ln(t,e,i,n){let r=await Lk(t,e,i);try{return await n()}finally{await gn(r)}}function qa(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native transition journal must be an object");return t}function Xc(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 Ba(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ue(t,e){return Uc(t,e)}function Gc(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(f=>!Hk.has(f)),a=[...Jc].find(f=>!Object.hasOwn(i,f)),o=Jc.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(Dc(i.summary,"Native transition journal event summary"),Ge(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(f=>typeof f!="string"||f.length===0||Buffer.byteLength(f,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Dc(i.noCodeReason,"Native transition journal event no-code reason"),Ge(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")?Qh(i.repairStagnation):null;if(c){let f=c.overrideSummaryHash===null;if(f&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!f&&(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 Mk(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 Gc({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},e)}return Gc(t,e)}function Qc(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?Mk(t.eventData,t.evidenceHash):Gc(t.eventData,t.evidenceHash),r=wc(t.nextRun),a=t.previousRun===null?null:wc(t.previousRun);return{id:t.id,evidenceHash:t.evidenceHash,createdAt:t.createdAt,previousRun:a,nextRun:r,eventData:n}}function tp(t,e,i=!1){if(t.skill!==xi.definition.metadata.name||(i?!Zh(t):t.skillVersion!==xi.definition.metadata.version||t.skillHash!==Vc)||t.orchestration!==xi.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 ip(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 np(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 Zc(t,e,i,n=!1){let{previousRun:r,nextRun:a}=i;if(tp(a,"next Run",n||r!==null),np(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(tp(r,"previous Run",!0),np(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(!Uc(ip(r),ip(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function Fk(t,e,i){return G(JSON.stringify({operation:"spec-rebase",change:t,summary:e,specChanges:i}))}function up(t,e,i){return t.phase!=="shape"&&e.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function rp(t){return"implementation_scope"in t?{implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance}:null}function el(t,e,i,n,r=!1){let a=i.eventData,o=rp(t),s=rp(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&&Uc(t.spec_changes,e.spec_changes),l=ep({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=Fk(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 Dk(t,e){let i=qa(t);if(Xc(i,Ok),i.schema!==Ci)throw new Error(`Expected Native transition schema ${Ci}`);let n=Ba(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 ${Ci} minimum_runtime_version must be ${3}`);let r=Ba(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=Qc(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(el(o,s,a,i.operation),Zc(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Ci,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 Bk(t,e){let i=qa(t);if(Xc(i,_k),i.schema!==Rn)throw new Error(`Expected Native transition schema ${Rn}`);let n=Qc(i,e,!0),r=In(i.previousState),a=In(i.nextState);if(r.name!==e||a.name!==e)throw new Error("Native transition journal state mismatch");return el(r,a,n,up(r,a,n.eventData),!0),Zc(r,a,n,!0),{schema:Rn,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 qk(t,e){let i=qa(t);if(Xc(i,lp),i.schema!==Ri)throw new Error(`Expected Native transition schema ${Ri}`);if(Ba(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Ri} minimum_runtime_version must be 2`);let r=Ba(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Qc(i,e,!0),o=_n(i.previousState),s=_n(i.nextState);if(o.name!==e||s.name!==e)throw new Error("Native v2 transition journal state mismatch");if(el(o,s,a,up(o,s,a.eventData),!0),Zc(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Ri,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 Vk(t,e){let i=qa(t);if(i.schema===Ci)return{status:"current",journal:Dk(i,e)};if(i.schema===Rn)return{status:"migration-required",journal:Bk(i,e)};if(i.schema===Ri)return{status:"migration-required",journal:qk(i,e)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function zk(t,e){let i=Yc(t,e);await M(t.nativeRoot,i);try{let n=await it({root:t.nativeRoot,file:i,maxBytes:jk,label:`Native transition journal ${e}`});return Vk(JSON.parse(n.bytes.toString("utf8")),e)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Wc(t,e){let i=await zk(t,e);if(!i)return null;if(i.status==="migration-required")throw new Kc(e);return i.journal}function ap(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 op(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 Wk(t){let{journal:e}=t;return fp({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 fp(t){return{sequence:t.sequence,timestamp:t.timestamp,type:t.type,runId:t.runId,data:t.data}}function sp(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=Wk({sequence:a.index+1,journal:e,type:a.event.type});if(!Ue(fp(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 tl(t,e,i){if(await On(t,e))throw new Error(`Native schema migration is incomplete for ${e}; run doctor --repair`);await Ea(t,e);let n=await Wc(t,e);if(!n)return null;let r=U(t,e),a=sp(await Ei(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([Cn(r),Pe(t,e)]),c=ap(o,n),l=op(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 yc(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!Ue(await Cn(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 Pa(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 Pe(t,e),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let f=await Wc(t,e);if(!f||!Ue(f,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let u=sp(await Ei(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(u.started||await Da({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=u.transitioned;d||(d=await Da({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await zc({changeDir:r,run:n.nextRun,trajectoryOffset:d.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([Cn(r),Pe(t,e)]);ap(p,{...n,previousRun:n.nextRun}),op(m,{...n,previousState:n.nextState});let h=await Wc(t,e);if(!h||!Ue(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await Tk.rm(Yc(t,e),{force:!0}),n.nextState}async function dp(t,e,i){let n=await _h(t,e);if(!n)return null;if(await Oh(t,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Pa(t,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await jh(t,n.checkpoint),await i?.afterProgressWritten?.(n),await Jk.rm(xc(t,e),{force:!0}),n}async function Va(t,e){await tl(t,e),await dp(t,e)}import{createHash as DE}from"node:crypto";import{constants as hl,promises as Be}from"node:fs";import ri from"node:path";import{TextDecoder as BE}from"node:util";import hp from"node:path";var za="comet.native.check-receipt.v1",vp="comet.native.check-receipt.v1",_t="scoped-text-safety",Mn=1,ne=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),Kk=/^[a-f0-9]{64}$/u,Gk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Uk="comet.native.checker-policy.v1",Yk="comet.native.check-input.v1",Xk=2048,Wa=V(Uk,{policy:_t,version:Mn,limits:ne,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),Qk=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),pp=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],gp=["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"],Zk=new Set(gp);function Zt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ei(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 ut(t,e){if(typeof t!="string"||!Kk.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function Qt(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function wp(t,e){let i=Qt(t,e);if(i<1)throw new Error(`${e} must be a positive integer`);return i}function mp(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let i=new Date(t);if(!Number.isFinite(i.getTime())||i.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function eE(t,e){if(typeof t!="string"||t.length===0||Buffer.byteLength(t,"utf8")>Xk||t.includes("\\")||t.includes("\0")||t.endsWith("/")||/^[a-zA-Z]:/u.test(t))throw new Error(`${e} must be a bounded normalized project-relative path`);let i=hp.posix.normalize(t);if(i!==t||i==="."||i===".."||i.startsWith("../")||hp.posix.isAbsolute(i))throw new Error(`${e} must stay inside the project root`);return t}function tE(t){let e=Zt(t,"Native check receipt checker");ei(e,["policy","version","hash","limits"],"Native check receipt checker");let i=Zt(e.limits,"Native check receipt limits");if(ei(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),e.policy!==_t||e.version!==Mn||e.hash!==Wa||i.maxFiles!==ne.maxFiles||i.maxFileBytes!==ne.maxFileBytes||i.maxTotalBytes!==ne.maxTotalBytes||i.maxIssues!==ne.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:_t,version:Mn,hash:Wa,limits:{...ne}}}function iE(t){let e=Zt(t,"Native check receipt contract");return ei(e,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:ut(e.expectedHash,"Native check expected contract hash"),beforeHash:ut(e.beforeHash,"Native check before contract hash"),afterHash:ut(e.afterHash,"Native check after contract hash")}}function nE(t){let e=Zt(t,"Native check receipt implementation");return ei(e,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:ut(e.scopeHash,"Native check scope hash"),expectedSnapshotHash:ut(e.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:ut(e.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:ut(e.afterSnapshotHash,"Native check after snapshot hash")}}function rE(t){let e=Zt(t,"Native check receipt counts");ei(e,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:Qt(e.filesSelected,"Native check filesSelected"),filesScanned:Qt(e.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Qt(e.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Qt(e.bytesScanned,"Native check bytesScanned"),issueCount:Qt(e.issueCount,"Native check issueCount"),recordedIssueCount:Qt(e.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>ne.maxFiles||i.bytesScanned>ne.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>ne.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function aE(t,e){return t.path.localeCompare(e.path,"en")||t.line-e.line||pp.indexOf(t.kind)-pp.indexOf(e.kind)}function oE(t){if(!Array.isArray(t)||t.length>ne.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let e=t.map((n,r)=>{let a=Zt(n,`Native check issue ${r}`);if(ei(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!Qk.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:eE(a.path,`Native check issue ${r} path`),line:wp(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...e].sort(aE);if(JSON.stringify(i)!==JSON.stringify(e))throw new Error("Native check receipt issues must be canonical");return e}function sE(t){if(!Array.isArray(t)||t.some(n=>typeof n!="string"||!Zk.has(n)))throw new Error("Native check receipt stale reasons are invalid");let e=t,i=gp.filter(n=>e.includes(n));if(new Set(e).size!==e.length||JSON.stringify(i)!==JSON.stringify(e))throw new Error("Native check receipt stale reasons must be canonical");return[...e]}function yp(t){return V(Yk,t)}function ti(t){let e=Zt(t,"Native check receipt");if(ei(e,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),e.schema!==za)throw new Error("Native check receipt schema is invalid");if(typeof e.change!="string"||Buffer.byteLength(e.change,"utf8")>128||!Gk.test(e.change))throw new Error("Native check receipt change name is invalid");let i=wp(e.sourceRevision,"Native check source revision"),n=tE(e.checker),r=iE(e.contract),a=nE(e.implementation),o=yp({change:e.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(ut(e.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(e.status!=="passed"&&e.status!=="failed")throw new Error("Native check receipt status is invalid");let s=mp(e.startedAt,"Native check receipt startedAt"),c=mp(e.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=rE(e.counts),f=oE(e.issues);if(l.recordedIssueCount!==f.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof e.issuesTruncated!="boolean"||e.issuesTruncated!==l.issueCount>f.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let u=sE(e.staleReasons);if(typeof e.stale!="boolean"||e.stale!==u.length>0)throw new Error("Native check receipt stale flag is inconsistent");let d=l.issueCount===0&&!e.stale?"passed":"failed";if(e.status!==d)throw new Error("Native check receipt status is inconsistent with its evidence");if(e.status==="passed"&&(l.filesSelected>ne.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>ne.maxFiles&&!f.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:za,change:e.change,sourceRevision:i,checker:n,inputHash:o,status:e.status,startedAt:s,endedAt:c,contract:r,implementation:a,counts:l,issues:f,issuesTruncated:e.issuesTruncated,stale:e.stale,staleReasons:u},m=ut(e.receiptHash,"Native check receipt content hash");if(V(vp,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}function Np(t){let e={policy:_t,version:Mn,hash:Wa,limits:{...ne}},i={schema:za,...t,checker:e,inputHash:yp({change:t.change,sourceRevision:t.sourceRevision,checkerHash:e.hash,contractHash:t.contract.expectedHash,scopeHash:t.implementation.scopeHash,snapshotHash:t.implementation.expectedSnapshotHash})};return ti({...i,receiptHash:V(vp,i)})}import{constants as il,promises as Ae}from"node:fs";import ii from"node:path";var cE=/^[a-f0-9]{64}$/u,lE=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,ni=512*1024;function uE(t,e){return H({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Ja(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?H(i,n):H(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function fE(t,e){let i=ii.resolve(t),n=ii.resolve(e);if(!J(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...ii.relative(i,n).split(ii.sep).filter(Boolean)]){o&&(a=ii.join(a,o));let s=await Ae.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ae.realpath(a);if(r.length>0&&!J(r[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return r}async function bp(t){for(let e of t){let i=await Ae.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!uE(e,i)||await Ae.realpath(e.path)!==e.realPath)throw new Error(`Native check receipt parent changed while reading: ${e.path}`)}}function Sp(t){if(!cE.test(t))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${t}.json`}function dE(t){let e=lE.exec(t);if(!e)throw new Error("Native check receipt ref is invalid");return e[1]}function kp(t,e,i){return ii.join(U(t,e),...Sp(i).split("/"))}async function hE(t,e,i){let n=await fE(i,ii.dirname(t)),r=await Ae.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>ni)throw new Error(`Native check receipt exceeds ${ni} bytes`);let[a,o]=await Promise.all([Ae.realpath(e),Ae.realpath(t)]);if(!J(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":il.O_RDONLY|il.O_NOFOLLOW|il.O_NONBLOCK,c=await Ae.open(t,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,f,u]=await Promise.all([c.stat(),Ae.lstat(t),Ae.realpath(t)]);if(await bp(n),!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!Ja(r,l)||!Ja(l,f))throw new Error("Native check receipt changed while opening");let d=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let b=ni+1-p,y=await c.read(m,0,Math.min(m.length,b),null);if(y.bytesRead===0)break;if(p+=y.bytesRead,p>ni)throw new Error(`Native check receipt exceeds ${ni} bytes`);d.push(Buffer.from(m.subarray(0,y.bytesRead)))}let[h,v,N]=await Promise.all([c.stat(),Ae.lstat(t),Ae.realpath(t)]);if(await bp(n),!v.isFile()||v.isSymbolicLink()||N!==o||!J(a,N)||!Ja(l,h)||!Ja(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(d,p).toString("utf8"))}finally{await c.close()}}async function nl(t,e,i){let n=dE(i),r=U(t,e),a=kp(t,e,n);await M(t.nativeRoot,a);let o=ti(await hE(a,r,t.nativeRoot));if(o.change!==e||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}async function Ep(t){let e=ti(t.receipt);if(e.change!==t.name)throw new Error("Native check receipt change mismatch");let i=Sp(e.receiptHash),n=kp(t.paths,t.name,e.receiptHash);if(Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
161
|
-
`,"utf8")>ni)throw new Error(`Native check receipt exceeds ${ni} bytes`);await M(t.paths.nativeRoot,n);try{let o=await nl(t.paths,t.name,i);if(JSON.stringify(o)!==JSON.stringify(e))throw new Error(`Native check receipt hash collision for ${e.receiptHash}`);return i}catch(o){if(o.code!=="ENOENT")throw o}await ke(n,e,{containedRoot:t.paths.nativeRoot});let a=await nl(t.paths,t.name,i);if(JSON.stringify(a)!==JSON.stringify(e))throw new Error("Native check receipt changed while being persisted");return i}import xp from"node:path";var pE="comet.native.acceptance.v1";var BI=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Dn=Object.freeze({maxCriteria:1024});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 Cp(t){return t.includes("-->")||t.includes("--!>")}function*Fn(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 xc(t){return t.reason==="git-enumeration-limit"||t.reason==="git-selection-changed"||t.reason==="physical-enumeration-limit"||t.reason==="physical-selection-changed"}function uh(t){for(let e=t.length-1;e>=0;e-=1){let i=t[e];if(!xc(i))return t.splice(e,1),i}return null}function Ct(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return le(i,n)?j(i,n):j(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Nk(t,e,i,n){if(!I(n))return{status:"budget-exhausted"};let r;try{r=await X.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=xa("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()||!Ct(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 f=await r.read(o,0,Math.min(o.length,l),null);if(!I(n))return{status:"budget-exhausted"};if(f.bytesRead===0){if(!I(n))return{status:"budget-exhausted"};let u=await r.stat();return I(n)?!u.isFile()||!Ct(c,u)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:u}:{status:"budget-exhausted"}}if(s+f.bytesRead>e)return{status:"changed"};a.update(o.subarray(0,f.bytesRead)),s+=f.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 Si(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ye(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function kh(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=H.posix.normalize(t);if(i!==t||H.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function bk(t,e){let i=Pe(t,`Native snapshot entry ${e}`);Ae(i,Vb,`Native snapshot entry ${e}`);let n=kh(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!Ta.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:Ye(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!mh.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function kk(t,e){let i=Pe(t,`Native snapshot omission ${e}`);if(Ae(i,Wb,`Native snapshot omission ${e}`),!Gb.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!Kb.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:kh(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:Ye(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function Sk(t){let e=Pe(t,"Native snapshot omission overflow");if(Ae(e,zb,"Native snapshot omission overflow"),typeof e.hash!="string"||!Ta.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:Si(e.count,"Native snapshot omission overflow count")}}function ki(t,e){let i=Pe(t,e);if(Ae(i,Bb,e),typeof i.hash!="string"||!Ta.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=Ye(i.recordCount,`${e} recordCount`),r=Ye(i.storedRecordCount,`${e} storedRecordCount`),a=Ye(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 fh(t){let e=Pe(t,"Native Git selection evidence");if(Ae(e,Mb,"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=ki(e.stageBefore,"Native Git selection stageBefore"),n=ki(e.combined,"Native Git selection combined"),r=ki(e.stageAfter,"Native Git selection stageAfter"),a=ki(e.finalStageBefore,"Native Git selection finalStageBefore"),o=ki(e.finalCombined,"Native Git selection finalCombined"),s=ki(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(u=>u.overflow),l=!Rt(i,r)||!Rt(r,a)||!Rt(n,o)||!Rt(a,s),f=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!==f)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:f,stageBefore:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function dh(t,e){let i=Pe(t,e);if(Ae(i,qb,e),typeof i.hash!="string"||!Ta.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=Ye(i.visitedNodeCount,`${e} visitedNodeCount`),r=Ye(i.recordCount,`${e} recordCount`),a=Ye(i.storedRecordCount,`${e} storedRecordCount`),o=Ye(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 Ek(t){let e=Pe(t,"Native physical selection evidence");if(Ae(e,Db,"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=dh(e.before,"Native physical selection before"),n=dh(e.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!yh(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 Cn(t){let e=Pe(t,"Native content snapshot manifest");if(Ae(e,jb,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Jb.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,Fb,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let S=g.gitSelection===void 0?void 0:fh(g.gitSelection),k=g.physicalSelection===void 0?void 0:Ek(g.physicalSelection),C=null;if(g.projection!==void 0){let B=Pe(g.projection,"Native content snapshot projection");if(Ae(B,Lb,"Native content snapshot projection"),B.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");C={provider:"git",...B.selection===void 0?{}:{selection:fh(B.selection)}}}if(g.provider==="git"){if(k||C)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...S?{gitSelection:S}:{}}}else{if(S)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&C)throw new Error("Native physical-tree capture cannot combine selection and projection");i=C?{provider:"physical-tree",projection:C}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}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,Hb,"Native content snapshot limits");let r={maxFiles:Si(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Si(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Si(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Si(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:Si(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let g=Pe(e.policy,"Native snapshot policy");if(Ae(g,$b,"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=bh({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(bk),s=e.omitted.map(kk),c=Ye(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:Sk(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,S)=>g+S.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>ph||c<s.length)throw new Error("Native content snapshot omission count is invalid");let f=c-s.length;if(f===0&&l||f>0&&l?.count!==f)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 u=s.filter(g=>g.reason==="git-enumeration-limit"),d=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...u,...d])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(u.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!==(u.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"),b=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...v,...b])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||b.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=i?.physicalSelection,y=N?.status==="overflow"||N?.status==="overflow-and-changed",w=N?.status==="changed"||N?.status==="overflow-and-changed";if(y!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(w!==(b.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:e.origin,...i?{capture:i}:{},createdAt:e.createdAt,complete:e.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Nh(E)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function Ck(t,e){if(!Ob.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=H.join(t.changesDir,e);if(!z(t.changesDir,i))throw new Error("Native change path escaped");return H.join(i,"runtime","baseline-manifest.json")}async function Sh(t,e={}){let i={maxFiles:e.limits?.maxFiles??Ra.maxFiles,maxFileBytes:e.limits?.maxFileBytes??Ra.maxFileBytes,maxTotalBytes:e.limits?.maxTotalBytes??Ra.maxTotalBytes,maxManifestBytes:e.limits?.maxManifestBytes??Ra.maxManifestBytes,...e.limits?.maxDurationMs===void 0?{}:{maxDurationMs:e.limits.maxDurationMs}},n=bh(e.policy),r=ek({...e,deadlineMs:e.deadlineMs??i.maxDurationMs}),a=nk(e.gitSelectionLimits),o=tk(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=H.resolve(t.projectRoot),c=await X.realpath(s),l=H.resolve(t.nativeRoot),f=await X.realpath(l),u=H.resolve(t.configFile),d=H.join(s,".comet","current-change.json"),p=vk(s,e.denylist??[]),m=[],h=[],v=new Map,b=new Map,N=0,y=0,w=K("comet.native.snapshot-omission-overflow.v1"),E=0,g=!1,S=null,k=x=>{y+=1,w=Rc(w,"omission",x)},C=x=>{if(N+=1,h.length<ph){h.push(x);return}if(xc(x)){let A=uh(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");k(A),h.push(x);return}k(x)},B=x=>{N+=x.count,y+=x.count,w=Rc(w,"git-selection",{source:"git-selection",...x})},G=x=>{y+=1,w=Rc(w,"manifest-entry",{reason:"manifest-size",entry:x})},M=async(x,A)=>{m.push(x),E+=x.size,v.set(x.path,A),g||(g=!0,await e.gitSelectionHooks?.afterFirstEntryCaptured?.(x.path))},V=(x,A)=>{let T=m.findIndex(Y=>Y.path===x);if(T<0)return;let[O]=m.splice(T,1);E-=O.size,v.delete(x),C(A)},U=async(x,A,T,O)=>{if(!T.isFile()||T.isSymbolicLink()||!I(r))return;let Y;try{Y=await X.realpath(x)}catch(P){if(!I(r))return;if(!re(P)&&!ne(P))throw P;C({path:A,size:T.size,type:"file",reason:ne(P)?"changed-during-read":"unreadable"});return}if(!I(r)||!z(c,Y)||Pt(f,Y))return;if(m.length>=i.maxFiles){C({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){C({path:A,size:T.size,type:"file",reason:"file-size"});return}if(E+T.size>i.maxTotalBytes){C({path:A,size:T.size,type:"file",reason:"total-size"});return}let L,_,Q;try{if(L=await Nk(Y,T.size,T,r),L.status==="budget-exhausted"||!I(r))return;if(L.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!I(r)||(Q=await X.realpath(x),!I(r)))return;_=await X.lstat(x)}catch(P){if(!I(r))return;if(!re(P)&&!ne(P))throw P;C({path:A,size:T.size,type:"file",reason:ne(P)?"changed-during-read":"unreadable"});return}if(I(r)){if(L.bytes!==T.size||Q!==Y||!Ct(T,L.finalStat)||!Ct(L.finalStat,_)||!_.isFile()||_.isSymbolicLink()||_.size!==T.size||_.mtimeMs!==T.mtimeMs||_.ctimeMs!==T.ctimeMs){C({path:A,size:_.isFile()?_.size:null,type:_.isFile()?"file":"other",reason:"changed-during-read"});return}I(r)&&await M({path:A,hash:L.hash,size:_.size,type:"file",...O===void 0?{}:{gitObjectId:O}},{kind:"file",target:x,realTarget:Y,stat:_})}},We=async(x,A,T)=>{if(!I(r))return;let O,Y,L;try{if(O=await X.readlink(x,{encoding:"buffer"}),!I(r)||(L=await X.lstat(x),!I(r)))return;Y=await X.readlink(x,{encoding:"buffer"})}catch(P){if(!I(r))return;if(!re(P)&&!ne(P))throw P;C({path:A,size:null,type:"other",reason:ne(P)?"changed-during-read":"unreadable"});return}if(!I(r))return;if(!L.isSymbolicLink()||!Ct(T,L)||L.mtimeMs!==T.mtimeMs||L.ctimeMs!==T.ctimeMs||!O.equals(Y)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let _=O.byteLength;if(m.length>=i.maxFiles){C({path:A,size:_,type:"other",reason:"file-count"});return}if(_>i.maxFileBytes){C({path:A,size:_,type:"other",reason:"file-size"});return}if(E+_>i.maxTotalBytes){C({path:A,size:_,type:"other",reason:"total-size"});return}let Q=xa("sha256").update("symlink\0").update(O).digest("hex");I(r)&&await M({path:A,hash:Q,size:_,type:"file"},{kind:"symlink",target:x,rawTarget:O,stat:L})},ze=async()=>{for(let[x,A]of[...v]){if(!I(r))return;if(A.kind==="file"){let _,Q;try{if(_=await X.realpath(A.target),!I(r))return;Q=await X.lstat(A.target)}catch(P){if(!I(r))return;if(!re(P)&&!ne(P))throw P;V(x,{path:x,size:null,type:"file",reason:re(P)?"unreadable":"changed-during-read"});continue}if(!I(r))return;(_!==A.realTarget||!Q.isFile()||Q.isSymbolicLink()||!Ct(A.stat,Q)||Q.size!==A.stat.size||Q.mtimeMs!==A.stat.mtimeMs||Q.ctimeMs!==A.stat.ctimeMs)&&V(x,{path:x,size:Q.isFile()?Q.size:null,type:Q.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let _,Q;try{if(_=await X.lstat(A.target),!I(r))return;Q=await X.readlink(A.target,{encoding:"buffer"})}catch(P){if(!I(r))return;if(!re(P)&&!ne(P))throw P;V(x,{path:x,size:null,type:"other",reason:re(P)?"unreadable":"changed-during-read"});continue}if(!I(r))return;(!_.isSymbolicLink()||!Ct(A.stat,_)||_.mtimeMs!==A.stat.mtimeMs||_.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(Q))&&V(x,{path:x,size:null,type:"other",reason:"changed-during-read"});continue}let T,O;try{if(T=await X.realpath(A.target),!I(r))return;O=await X.lstat(A.target)}catch{if(!I(r))return;V(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!I(r))return;if(!(T===A.realTarget&&O.isDirectory()&&!O.isSymbolicLink()&&Ct(A.stat,O)&&z(c,T)&&!Pt(f,T))){V(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"});continue}let L;try{if(!I(r))return;L=await sh(r,T)}catch(_){if(Ei(_))throw _;V(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!I(r))return;L.dirty?V(x,{path:x,size:null,type:"directory",reason:"gitlink-dirty"}):L.hash!==A.hash&&V(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"})}for(let[x,A]of b){if(!I(r))return;try{let T=await X.lstat(A);if(!I(r))return;C({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(ne(T))continue;if(!re(T))throw T;C({path:x,size:null,type:"file",reason:"unreadable"})}}},ye=await sk(r,t,a,e.gitSelectionHooks);if(ye===null){let x=await ah({execution:r,paths:t,physicalProjectRoot:c,physicalNativeRoot:f,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(Me(r)<1)break;if(!lh(n,O.path,r))continue;if(Me(r)<1)break;let Y=H.resolve(s,...O.path.split("/")),L;try{L=await X.lstat(Y)}catch(_){if(!I(r))break;if(!re(_)&&!ne(_))throw _;C({path:O.path,size:null,type:"file",reason:ne(_)?"changed-during-read":"unreadable"});continue}if(Me(r)<1)break;if(O.type==="symlink"&&L.isSymbolicLink()){if(await We(Y,O.path,L),Me(r)<1)break;continue}if(O.type!=="file"||!L.isFile()||L.isSymbolicLink()){C({path:O.path,size:L.isFile()?L.size:null,type:L.isDirectory()?"directory":L.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await U(Y,O.path,L),Me(r)<1)break}Me(r)>=1&&await ze();let A=await ah({execution:r,paths:t,physicalProjectRoot:c,physicalNativeRoot:f,denylist:p,policy:n,limits:o}),T=dk(x.evidence,A.evidence);S=T.evidence;for(let O of[...x.omissions,...A.omissions,...T.omissions])h.some(Y=>Y.path===O.path&&Y.reason===O.reason)||C(O)}else{await e.gitSelectionHooks?.afterInitialSelection?.();let x=e.incrementalBaseline,A=new Map,T=!1;if(x){let P=Cn(x);for(let Z of P.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);T=A.size>0}let O=new Set,Y=!0;try{let P=await Pa(r,s,["ls-files","-v","-z"],{...a,...e.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:e.gitSelectionHooks.outputChunkBytes}});if(P.overflow)T=!1,Y=!1,A.clear();else for(let Z of P.records){let ee=Ac(Z),de=ee.indexOf(" "),ce=de<0?null:Ci(ee.slice(de+1));if(de!==1||ce===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ee[0]!=="H"&&O.add(ce)}}catch(P){if(Ei(P))throw P;T=!1,Y=!1,A.clear()}let L=new Set;try{let P=await Aa(r,s,["ls-files","--modified","-z"],Pc);for(let Z of P.toString("utf8").split("\0")){let ee=Ci(Z);ee!==null&&L.add(ee)}}catch{T=!1,Y=!1,A.clear()}let _=new Set,Q=new Set;for(let P of hk(ye)){if(v.has(P)||!pk(t,P))continue;if(Me(r)<1)break;if(!lh(n,P,r))continue;if(Me(r)<1)break;let Z=H.resolve(s,...P.split("/"));if(Z===u||Z===d||p.some(Ne=>Pt(Ne,Z)))continue;if(ye.gitlinks.has(P)){if(m.length>=i.maxFiles){C({path:P,size:0,type:"file",reason:"file-count"});continue}let Ne,ir;try{[Ne,ir]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(ir.isSymbolicLink()||!ir.isDirectory()||!z(c,Ne)||Pt(f,Ne)){C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let ci=await sh(r,Ne);if(ci.dirty){C({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await M({path:P,hash:ci.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:Ne,stat:ir,hash:ci.hash})}catch(ci){if(Ei(ci))throw ci;C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ee;try{ee=await X.lstat(Z)}catch(Ne){if(ne(Ne)&&ye.tracked.has(P)){b.set(P,Z);continue}if(!re(Ne)&&!ne(Ne))throw Ne;C({path:P,size:null,type:"file",reason:ne(Ne)?"changed-during-read":"unreadable"});continue}if(ee.isSymbolicLink()){await We(Z,P,ee);continue}if(!ee.isFile()){ye.nestedRepositories.has(P)||C({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let de=ye.trackedObjectIds.get(P),ce=de?A.get(P):void 0;if(T&&ce?.gitObjectId!==void 0&&ce.gitObjectId===de&&!O.has(P)&&!L.has(P)){if(m.length>=i.maxFiles){C({path:P,size:ce.size,type:"file",reason:"file-count"});continue}if(ce.size>i.maxFileBytes){C({path:P,size:ce.size,type:"file",reason:"file-size"});continue}if(E+ce.size>i.maxTotalBytes){C({path:P,size:ce.size,type:"file",reason:"total-size"});continue}m.push({...ce}),E+=ce.size,_.add(P);continue}let Ol=Y&&!O.has(P)&&!L.has(P)?de:void 0;await U(Z,P,ee,Ol),Ol!==void 0&&Q.add(P)}if(await ze(),await e.gitSelectionHooks?.afterContentRevalidation?.(),await lk(r,t,a,ye,e.gitSelectionHooks?.outputChunkBytes),_.size>0||T&&Q.size>0){let P=await Aa(r,s,["ls-files","--modified","-z"],Pc),Z=new Set;for(let ee of P.toString("utf8").split("\0")){let de=Ci(ee);de!==null&&Z.add(de)}for(let ee of _){if(!Z.has(ee))continue;let de=m.find(ce=>ce.path===ee);V(ee,{path:ee,size:de?.size??null,type:"file",reason:"changed-during-read"})}for(let ee of Q){if(!Z.has(ee))continue;let de=m.find(ce=>ce.path===ee);de&&delete de.gitObjectId}}for(let P of ye.omissions)C(P);ye.overflow&&B(ye.overflow)}m.sort((x,A)=>x.path.localeCompare(A.path,"en")),h.sort((x,A)=>x.path.localeCompare(A.path,"en"));let $m=ye===null?{provider:"physical-tree",...S?{physicalSelection:S}:{}}:{provider:"git",...ye.evidence?{gitSelection:ye.evidence}:{}},_l=()=>({schema:"comet.native.content-snapshot.v1",origin:e.origin??"explicit",capture:$m,createdAt:(e.now??new Date).toISOString(),complete:N===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:N,...y>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${w}`,hash:w,count:y}}:{}}),go=_l();for(;Nh(go)>i.maxManifestBytes;){if(h.filter(A=>!xc(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let O=uh(h);if(O===null)break;k(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,G(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");go=_l()}return go}async function Rn(t,e,i={}){let r=(await Kt(t.projectRoot))?.native.snapshot??pc;return Sh(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 Eh(t,e){let i=Ck(t,e);await F(t.nativeRoot,i);try{let n=await Ud({root:t.nativeRoot,file:i,maxBytes:_b,label:"Native baseline snapshot manifest"});return Cn(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as Vk}from"crypto";import $c from"path";var Xe=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 _a,promises as pe}from"node:fs";import ke from"node:path";import{TextDecoder as Fk}from"node:util";import Ok from"path";var Ik=wo(ia(),1);var Ch=(t,e)=>{let i=t[e];return i==null?null:String(i)};function An(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=An(t,e);if(Ok.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 jk(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 Rh(t){if(!t.run_id)return null;let e=An(t,"run_id"),i=An(t,"skill"),n=An(t,"skill_version"),r=An(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"),f=Number(t.iteration);if(!Number.isInteger(f)||f<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:Ch(t,"current_step"),iteration:f,pending:Ch(t,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:jk(t)}}var gT=256*1024;var Hk=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function $k(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=Rh(e);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Ia(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=>!Hk.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 $k(e)}var be={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 Tn(t,e){let i=ke.relative(t,e);return i===""||!ke.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ke.sep}`)}function Ah(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function xn(t,e){return j({...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 Lk(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Pi(t,e,i){let n=Xe[e];if(i!==void 0&&i!==n)throw new Error(`Native Run ${e} ref must be ${n}`);let r=ke.resolve(t),a=ke.resolve(r,...n.split("/"));if(!Tn(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Ph(t){let e=await pe.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${t}`);return{path:t,realPath:await pe.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Ic(t,e){let i=ke.resolve(t),n=ke.resolve(e);if(!Tn(i,n))throw new Error("Native Run path is outside its change");let r=[await Ph(i)],a=i;for(let o of ke.relative(i,n).split(ke.sep).filter(Boolean)){a=ke.join(a,o);let s;try{s=await Ph(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Tn(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function Oa(t){for(let e of t){let i=await pe.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Lk(e,i)||await pe.realpath(e.path)!==e.realPath)throw new Error(`Native Run parent changed during I/O: ${e.path}`)}}async function Mk(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 In(t,e,i,n,r){let a=await Ic(t,ke.dirname(e));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await pe.lstat(e)}catch(u){if(u.code==="ENOENT")return null;throw u}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=Ah(o),c=await pe.realpath(e);if(!Tn(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?_a.O_RDONLY:_a.O_RDONLY|_a.O_NOFOLLOW|_a.O_NONBLOCK,f;try{f=await pe.open(e,l)}catch(u){throw new Error(`${n} changed while opening`,{cause:u})}try{let[u,d,p]=await Promise.all([f.stat(),pe.lstat(e),pe.realpath(e)]);if(await Oa(a),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==c||!xn(s,u)||!xn(s,d))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await Mk(f,i,n);await r?.beforeFinalCheck?.();let[h,v,b]=await Promise.all([f.stat(),pe.lstat(e),pe.realpath(e)]);if(await Oa(a),!v.isFile()||v.isSymbolicLink()||b!==c||!xn(s,h)||!xn(s,v))throw new Error(`${n} changed while reading`);let N;try{N=new Fk("utf-8",{fatal:!0}).decode(m)}catch(y){throw new Error(`${n} is not valid UTF-8`,{cause:y})}return{text:N,target:{exists:!0,identity:s,realPath:c}}}finally{await f.close()}}async function Bk(t,e,i){let n=await Ic(t,ke.dirname(e));if(!n)return{exists:!1};let r;try{r=await pe.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 pe.realpath(e);if(!Tn(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Oa(n),{exists:!0,identity:Ah(r),realPath:a}}async function Dk(t,e,i,n){let r=await Ic(t,ke.dirname(e));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await pe.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()||!xn(i.identity,a)||await pe.realpath(e)!==i.realPath)throw new Error(`${n} changed before commit`);await Oa(r)}async function _c(t){if(Buffer.byteLength(t.content,"utf8")>t.maxBytes)throw new Error(`${t.label} exceeds ${t.maxBytes} bytes`);let i=t.expected??await Bk(t.changeDir,t.file,t.label);if(i.exists&&i.identity.size>t.maxBytes)throw new Error(`${t.label} exceeds ${t.maxBytes} bytes`);await Wt(t.file,t.content,{containedRoot:t.changeDir,beforeCommit:async()=>{await t.hooks?.beforeCommit?.(),await Dk(t.changeDir,t.file,i,t.label)}});let n=await In(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 qk(t,e){try{return JSON.parse(t)}catch(i){throw new Error(`${e} contains invalid JSON`,{cause:i})}}function xh(t){return`${JSON.stringify(t,null,2)}
|
|
152
|
+
`}function Oc(t){return Ia(t)}async function _n(t,e){let i=Pi(t,"stateRef"),n=await In(t,i,be.runStateBytes,"Native Run state",e);return n?Ia(qk(n.text,"Native Run state")):null}async function jc(t,e,i){let n=Ia(e);await _c({changeDir:t,file:Pi(t,"stateRef"),content:xh(n),maxBytes:be.runStateBytes,label:"Native Run state",hooks:i})}async function Ai(t,e,i){let n=Pi(t,"trajectoryRef",e),r=await In(t,n,be.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>be.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${be.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 Th(t,e,i){return(await In(t,Pi(t,"trajectoryRef",e),be.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Ih(t,e,i,n){let r=Pi(t,"trajectoryRef",e),a=`${JSON.stringify(i)}
|
|
153
|
+
`;if(Buffer.byteLength(a,"utf8")>be.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${be.trajectoryEventBytes} bytes`);let o=await In(t,r,be.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=be.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${be.trajectoryEvents} events`);await _c({changeDir:t,file:r,content:`${o?.text??""}${a}`,maxBytes:be.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function _h(t,e,i,n){await _c({changeDir:t,file:Pi(t,"checkpointRef",e),content:xh(i),maxBytes:be.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var Wk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Fc=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 Hc(t){return Vk("sha256").update(t).digest("hex")}function zk(t,e){if(!Wk.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=$c.join(t.changesDir,e);if(!z(t.changesDir,i))throw new Error("Native change path escaped");return $c.join(i,"runtime","trajectory.jsonl")}function Jk(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 Gk(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 Kk(t,e){let i=e.lastIndexOf(10),n=e.subarray(0,i+1),r=Jk(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(u){if(!Gk(u,o))return{status:"invalid",file:t,line:s,message:u.message};c="incomplete-json",l=n}return{inspection:{status:"repairable",file:t,reason:c,line:s,originalHash:Hc(e),targetHash:Hc(l),tailHash:Hc(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Uk(t,e){let i=zk(t,e);await F(t.nativeRoot,i);let n=$c.join(t.changesDir,e),r=await Th(n,Xe.trajectoryRef);return r===null?{status:"clean",file:i}:Kk(i,Buffer.from(r))}async function Yk(t,e){let i=await Uk(t,e);return"inspection"in i?i.inspection:i}async function ja(t,e){let i=await Yk(t,e);if(i.status!=="clean")throw new Fc(i)}import{createHash as Zk}from"node:crypto";import{promises as $a}from"node:fs";import At from"node:path";import{execFileSync as Xk}from"child_process";import Ha from"path";function Lc(t,e){return Xk("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Qk(t,e){let i=Ha.normalize(t),n=Ha.normalize(e);return process.platform==="win32"?i.toLowerCase()===n.toLowerCase():i===n}function Oh(t){try{let e=Ha.resolve(Lc(t,["rev-parse","--show-toplevel"])),n=Lc(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),r=n?Ha.resolve(n.slice(9)):e,a=null;try{a=Lc(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Qk(e,r),currentWorktreeRoot:e,primaryWorktreeRoot:r,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}var On=/^[a-f0-9]{64}$/u,eS=16*1024,Mc=process.platform;function Fh(t,e){let i=At.relative(t,e);return At.isAbsolute(i)||i===".."||i.startsWith(`..${At.sep}`)?null:i.replaceAll("\\","/")||"."}function Lh(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function Mh(t,e){if(t.length===0||Lh(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 Bc(t,e){return Zk("sha256").update(`${t}
|
|
155
|
+
${e}`).digest("hex")}async function jh(t,e){let i=await $a.realpath(e),n=await $a.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Mc==="win32"?At.normalize(i).toLowerCase():i;return Bc(t,`${r}
|
|
156
|
+
${n.dev}
|
|
157
|
+
${n.ino}
|
|
158
|
+
${n.birthtimeMs}`)}async function Hh(t,e){let i=await $a.realpath(e),n=await $a.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Mc==="win32"?At.normalize(i).toLowerCase():i;return Bc(t,r)}function tS(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 $h(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||Lh(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function Bh(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if($h(t.changeBranch,"Native workspace change branch"),$h(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 Fa(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"||!On.test(String(e.projectRootId))||!On.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");tS(e.capturedAt),Mh(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&&!On.test(String(e.projectRootPathId))||a&&!On.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!On.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(Bh(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 iS(t,e){return At.join(t.changesDir,e,"runtime","workspace.json")}function nS(t,e){let i=Fh(t.nativeRoot,iS(t,e));if(!i||i===".")throw new Error("Native workspace file escaped its root");return Mh(i,"Native workspace file ref")}async function rS(t,e){try{let i=await Ke({root:t.nativeRoot,ref:nS(t,e),maxBytes:eS});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function aS(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=Fh(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([jh("comet.native.workspace-project-root.v2",t.paths.projectRoot),jh("comet.native.workspace-native-root.v2",t.paths.nativeRoot),Hh("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),Hh("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&&Bh(t.binding);let s={capturedAt:o,capturedRevision:t.revision,nativeRootRef:e,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...t.sessionId?{sessionHash:Bc("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 Fa(c),c}async function La(t,e){let i=await rS(t,e);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Fa(i),i)}async function Dh(t){Fa(t.identity);let e=await aS({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")),Mc==="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(Fa(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 Dh(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Oh(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 Vh(t,e){let i=await La(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",Yt="comet.native.v2",Xt="comet.native.v1",xi="comet.native.transition.v3",Ti="comet.native.transition.v2",jn="comet.native.transition.v1";var zh=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],oS=new Set(zh),Jh=new Set([...zh,"minimum_runtime_version","revision"]),sS=new Set([...Jh,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),cS=new Set(["capability","operation","source","base_hash"]),lS=new Set(["shape","build","verify","archive"]),uS=new Set(["implicit","confirmed"]),fS=new Set(["pending","pass","fail"]),Tt="comet-state.yaml",Vc=/^[a-f0-9]{64}$/u,Gh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dS=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Hn=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"},Qt=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"},$n=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"},Ma=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"},Ba=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"},wI=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
161
|
+
`);function Ln(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Kh(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 Wc(t){if(!Gh.test(t))throw new Error(`Invalid Native change name: ${t}`)}function hS(t){if(!Gh.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function Uh(t,e){if(t.length===0||ot.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function pS(t,e){let i=Ln(t,`spec_changes[${e}]`);if(Kh(i,cS,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(hS(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"&&Uh(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"||!Vc.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"||!Vc.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 mS(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 zc(t,e){if(Kh(t,e,Tt),typeof t.name!="string")throw new Error("Native change name is required");if(Wc(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!lS.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!uS.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(pS),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"||!fS.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"&&Uh(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!mS(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 Mn(t){let e=Ln(t,Tt);if(e.schema!==Xt)throw new Error(`Expected ${Xt}`);return{schema:Xt,...zc(e,oS)}}function Fn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Dc(t,e,i){if(t===null)return null;let n=typeof t=="string"?dS.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 vS(t){if(t==null)return null;if(typeof t!="string"||!Vc.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function gS(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 Bn(t){let e=Ln(t,Tt);if(e.schema!==Yt)throw new Error(`Expected ${Yt}`);if(Fn(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Yt} minimum_runtime_version must be 2`);return{schema:Yt,minimum_runtime_version:2,revision:Fn(e.revision,"Native v2 revision"),...zc(e,Jh)}}function st(t){let e=Ln(t,Tt);if(e.schema!==xt){if(e.schema===Xt||e.schema===Yt){let o=e.schema===Xt?Mn(e):Bn(e);throw new Hn(o.name,o.schema)}throw new Qt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Fn(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Qt(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=Fn(e.revision,"Native revision"),r=zc(e,sS),a=vS(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:gS(e.verification_protocol),...r,approved_contract_hash:a,implementation_scope:Dc(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Dc(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Dc(e.partial_allowance,"Native partial_allowance","allowances")}}function wS(t){let e=Ln(t,Tt);if(e.schema===Xt){let r=Mn(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${xt}`}}if(e.schema===Yt){let r=Bn(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 Qt(typeof e.schema=="string"?e.schema:"(missing)",r).message}}let i=Fn(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Qt(e.schema,i).message};let n=st(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function qc(t){let e=st(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 J(t,e){Wc(e);let i=ot.join(t.changesDir,e);if(!z(t.changesDir,i))throw new Error("Native change path escaped");return i}async function Dn(t,e){let i=ot.join(J(t,e),"runtime","schema-migration.json");await F(t.nativeRoot,i);try{return await Wh.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Yh(t,e){let i=ot.join(J(t,e),"runtime","checkpoint-journal.json");await F(t.nativeRoot,i);try{return await Wh.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var yS=256*1024;async function Xh(t,e=ot.dirname(t)){let i=ot.relative(e,t).split(ot.sep).join("/"),n=await Ke({root:e,ref:i,maxBytes:yS}),r=(0,Da.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 NS(t,e){let i=ot.join(J(t,e),Tt);await F(t.nativeRoot,i);let n=wS(await Xh(i,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Dn(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 bS(t,n.state),n)}async function bS(t,e){if(await Eh(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function xe(t,e){let i=await NS(t,e);if(i.status==="migration-required")throw new Hn(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Qt(i.schema,i.minimumRuntimeVersion);return await Vh(t,e),i.state}async function kS(t,e,i){let n={...e,schema:xt,minimum_runtime_version:3,revision:i+1},r=await nh({expectedRevision:i,next:n,read:async()=>{let a=st(await Xh(t));if(a.name!==e.name)throw new Error(`Native change file/name mismatch: ${e.name}`);return a},write:a=>Wt(t,(0,Da.stringify)(qc(a))),equals:(a,o)=>JSON.stringify(qc(a))===JSON.stringify(qc(o)),conflict:a=>new $n(e.name,i,a)});return Object.assign(e,r),r}async function qa(t,e,i,n){if(await kn(t.projectRoot),await Dn(t,e.name))throw new Hn(e.name,e.schema);if(!n?.allowPendingCheckpointRecovery&&await Yh(t,e.name))throw new Error(`Native progress checkpoint recovery is required for ${e.name} before another state write`);if((await xe(t,e.name)).verification_protocol!==e.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await ja(t,e.name);let a=ot.join(J(t,e.name),Tt);return await F(t.nativeRoot,a),kS(a,e,i)}import qn from"path";var SS=/\b(Bearer|Basic)\s+[^\s"']+/giu,ES=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,CS=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,RS=/\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,PS=/("(?:[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,AS=/(["'])((?:[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,xS=/\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 Qe(t){return t.replace(SS,"$1 [REDACTED]").replace(ES,"[REDACTED PRIVATE KEY]").replace(CS,"$1[REDACTED]@").replace(RS,"[REDACTED TOKEN]").replace(PS,'$1"[REDACTED]"').replace(AS,"$1$2$1$3$4[REDACTED]$4").replace(xS,"$1$2[REDACTED]")}var Va={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Ii=/^[a-f0-9]{64}$/u;function Wa(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function za(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 Qh(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Jc(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function TS(t){let e=t.trim().replaceAll("\\","/");if(e.length===0||qn.isAbsolute(e)||/^(?:[A-Za-z]:|~|\/)/u.test(e)||e.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${t}`);let i=qn.posix.normalize(e);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${t}`);return i}function IS(t,e){return qn.join(J(t,e),"runtime","checkpoints","progress.json")}function Gc(t,e){return qn.join(J(t,e),"runtime","checkpoint-journal.json")}function Zh(t,e,i){if(!Ii.test(i))throw new Error("Native checkpoint manifest hash is invalid");return qn.join(J(t,e),"runtime","checkpoints","manifests",`${i}.json`)}function _S(t){if(!Ii.test(t))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${t}.json`}async function ep(t,e,i){let n=await rt({root:t,file:e,maxBytes:Va.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function OS(t,e){let i=Wa(t,`checkpoint manifest artifact ${e}`);za(i,["path","hash","size"],`checkpoint manifest artifact ${e}`);let n=TS(It(i.path,`checkpoint artifact ${e} path`,4096)),r=it(n);if(r)throw new Error(`checkpoint artifact ${e} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!Ii.test(i.hash))throw new Error(`checkpoint artifact ${e} hash is invalid`);return{path:n,hash:i.hash,size:Jc(i.size,`checkpoint artifact ${e} size`)}}function Ja(t,e){let i=Wa(t,"Native checkpoint manifest");if(za(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>Va.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(OS),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=Jc(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>Va.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 Kc(t){return K(JSON.stringify(Ja(t,t.change)))}function tp(t,e){let i=Wa(t,"Native progress checkpoint");if(za(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=Qh(i.previousRevision,"Native checkpoint previousRevision"),a=Qh(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(!Ii.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=_S(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(!Ii.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 f=Jc(i.artifactCount,"Native checkpoint artifactCount");if(f>Va.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let u=It(i.summary,"Native checkpoint summary"),d=It(i.nextAction,"Native checkpoint nextAction");if(Qe(u)!==u||Qe(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:u,nextAction:d,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:f,createdAt:l}}function jS(t,e){let i=Wa(t,"Native checkpoint journal");if(za(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=st(i.previousState),r=st(i.nextState),a=tp(i.checkpoint,e),o=Ja(i.manifest,e),s=It(i.inputHash,"Native checkpoint journal inputHash",64),c=K(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Ii.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!==Kc(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 ip(t,e,i){let n=Zh(t,e,i);await F(t.nativeRoot,n);let r=await ep(t.nativeRoot,n,"Native checkpoint manifest"),a=Ja(r,e);if(Uc(t,a),Kc(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function np(t,e){let i=Gc(t,e);await F(t.nativeRoot,i);try{let n=jS(await ep(t.nativeRoot,i,"Native checkpoint journal"),e);return Uc(t,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function rp(t,e,i,n){let r=Ja(i,e);Uc(t,r);let a=Kc(r),o=Zh(t,e,a);await F(t.nativeRoot,o);try{let s=await ip(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 Ce(o,r,{containedRoot:t.nativeRoot,beforeCommit:n?.beforeCommit}),a}function Uc(t,e){for(let i of e.artifacts){let n=Ed(t,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function ap(t,e){let i=tp(e,e.change),n=await ip(t,i.change,i.manifestHash),r=K(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=IS(t,e.change);await F(t.nativeRoot,a),await Ce(a,i,{containedRoot:t.nativeRoot})}import{promises as mE}from"fs";import vE from"path";import{isDeepStrictEqual as hl}from"util";import{createHash as HS}from"crypto";function Be(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function $S(t,e){e.has(t)&&Be("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)||Be("sparse arrays are not supported");return(i.length!==t.length||i.some((n,r)=>n!==String(r)))&&Be("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&Be("symbol properties are not supported"),`[${t.map(n=>Yc(n,e)).join(",")}]`}finally{e.delete(t)}}function FS(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&Be("only plain objects are supported"),e.has(t)&&Be("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&Be("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))&&Be("accessor properties are not supported"),`${JSON.stringify(o)}:${Yc(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Yc(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)||Be("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?$S(t,e):FS(t,e);case"bigint":case"function":case"symbol":case"undefined":return Be(`${typeof t} values are not supported`)}return Be("unsupported value type")}function Ga(t){return Yc(t,new Set)}function q(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 HS("sha256").update(`${t}
|
|
162
|
+
${Ga(e)}`).digest("hex")}var Xc={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var LS=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function MS(t,e){return t<e?-1:t>e?1:0}function BS(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"||!LS.test(a))throw new Error(`${e} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(MS)}function op(t=[]){return BS(t,"Native repair failed check IDs",Xc.maxFailedCheckIds,!0)}import{createHash as hp}from"node:crypto";import sp from"path";var Qc="comet.native.implementation-scope.v2",pp="comet.native.content-snapshot-projection.v1",Vn="comet.native.content-snapshot-projection.v1",mp="comet.native.implementation-scope.v2",DS="comet.native.unresolved-scope-id.v1",qS="comet.native.scope-detail-overflow.v1",VS="comet.native.snapshot-projection-overflow.v2",il=/^[a-f0-9]{64}$/u,ei=1024*1024,WS=128,zS=128;function fe(t,e){return t<e?-1:t>e?1:0}function Zc(t){if(!il.test(t))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${t}.json`}function JS(t,e){return t===e?0:t===null?-1:e===null?1:fe(t,e)}function Ot(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=sp.posix.normalize(t);if(i!==t||i==="."||i===".."||i.startsWith("../")||sp.posix.isAbsolute(i))throw new Error(`${e} must stay inside the project root`);return t}function vp(t,e){return t==="."?t:Ot(t,e)}function _i(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative safe integer`);return t}function GS(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:Ot(t.path,`${e} path`),hash:t.hash,size:_i(t.size,`${e} size`),type:"file"}}function KS(t,e){return{path:vp(t.path,`${e} path`),size:t.size===null?null:_i(t.size,`${e} size`),type:t.type,reason:t.reason}}function US(t,e){return fe(t.path,e.path)||fe(t.hash,e.hash)||t.size-e.size}function YS(t,e){return fe(t.path,e.path)||fe(t.reason,e.reason)||fe(t.type,e.type)||(t.size??-1)-(e.size??-1)}function Wn(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
163
|
+
`,"utf8")}function _t(t,e,i){let n=`${e}
|
|
164
|
+
${Ga(i)}`;t.update(`${Buffer.byteLength(n,"utf8")}:`),t.update(n)}function XS(t){if(Wn(t)<=ei)return t;let e=[...t.entries],i=[...t.omitted],n=t.omittedCount,r=t.omissionOverflow?.count??0,a=hp("sha256");a.update(`${VS}
|
|
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}}),f=l();for(;Wn(f)>ei;){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");f=l()}let u=a.digest("hex");return{...f,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${u}`,hash:u,count:r}}}function el(t){let e=Cn(t),i=e.entries.map((r,a)=>GS(r,`Snapshot entry ${a}`));if(i.sort(US),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)=>KS(r,`Snapshot omission ${a}`));return n.sort(YS),XS({schema:pp,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 Ya(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:Ot(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)=>fe(i.path,n.path)||fe(i.kind,n.kind))}function Xa(t,e){return t.kind==="file"?t.path===e:e===t.path||e.startsWith(`${t.path}/`)}function cp(t){return t?{hash:t.hash,size:t.size}:null}function gp(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:fe(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 f=c?.path??l?.path;f!==void 0&&i({path:f,kind:c?l?"modified":"removed":"added",before:cp(c),after:cp(l)})}}function QS(t,e){return{...t,attributedTo:e.filter(i=>Xa(i,t.path))}}function ct(t,e){return{id:`scope:${q(DS,t)}`,kind:t.kind,source:t.source,path:t.path,reason:e}}function ZS(t,e){let i=e.omitted.map(n=>ct({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(ct({kind:"snapshot-incomplete",source:t,path:null,evidence:{omittedCount:e.omittedCount}},`${t} snapshot is incomplete`)),e.omissionOverflow&&i.push(ct({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 lp(t,e){return ZS(t,{...e,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function tl(t,e){return fe(t.kind,e.kind)||fe(t.source,e.source)||JS(t.path,e.path)||fe(t.id,e.id)}function eE(t){return[...new Map(t.map(i=>[i.id,i])).values()].sort(tl)}function tE(t){return[...new Set(t.map((e,i)=>Ot(e,`Git path ${i}`)))].sort(fe)}function wp(t){if(typeof t.contractHash!="string"||!il.test(t.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:t.contractHash,declaredArtifacts:Ya(t.declaredArtifacts),noCodeReason:t.noCodeReason?.trim()||null,...t.gitChangedPaths===void 0?{}:{gitChangedPaths:tE(t.gitChangedPaths)}}}function iE(t,e,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,f=0;return gp(t,e,u=>{let d=i.some(p=>Xa(p,u.path));if(l+=1,d||(f+=1),a?.has(u.path)&&o.push(u.path),!c&&r.length<WS){let p=QS(u,i),m=Wn(p);s+m<=ei?(r.push(p),s+=m):c=!0}}),{candidates:r,gitPathsPresentInChanges:o,totalChanges:l,totalUnattributed:f}}function yp(t,e){return ct({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 nE(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:_i(Number(e[1]),"Scope overflow change count"),unresolved:_i(Number(e[2]),"Scope overflow unresolved count"),unattributed:_i(Number(e[3]),"Scope overflow unattributed count")},n=Zt(e[4],"Scope detail overflow hash");if(JSON.stringify(t)!==JSON.stringify(yp(n,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:n}}function rE(t){let e=hp("sha256");e.update(`${qS}
|
|
166
|
+
`);let i=0;gp(t.baseline,t.current,r=>{if(i>=t.detailedChangeCount){_t(e,"change",r);let a=0;for(let o of t.declaredArtifacts)Xa(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 Np(t,e,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=iE(t,e,r,i.gitChangedPaths),s=q(Vn,t),c=q(Vn,e),l=[];for(let[g,S]of[["baseline",t],["current",e]])for(let k of S.omitted){if(l.length>=zS)break;l.push(ct({kind:"snapshot-omission",source:g,path:k.path,evidence:{reason:k.reason,size:k.size,type:k.type}},`${g} snapshot omitted ${k.path}: ${k.reason}`))}let f=t.omitted.length+e.omitted.length,u=[...lp("baseline",t),...lp("current",e),...o.totalChanges===0&&a===null?[ct({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(S=>g.has(S)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(S=>!g.has(S))}},p=g=>{let S=o.candidates.slice(0,g.detailedChangeCount),k=S.filter(ze=>ze.attributedTo.length===0),C=o.totalChanges-S.length,B=o.totalUnattributed-k.length,G=f-g.detailedOmissionCount,M=B+G,V=[...k.map(ze=>ct({kind:"unattributed-change",source:"implementation-scope",path:ze.path,evidence:{after:ze.after,before:ze.before,changeKind:ze.kind}},`Changed path is not covered by a declared artifact: ${ze.path}`)),...l.slice(0,g.detailedOmissionCount),...u,...C>0||M>0?[yp(g.overflowHash,{changes:C,unattributed:B,unresolved:M})]:[]],U=eE(V),We=g.includeGitAdvisory?d():void 0;return{schema:Qc,contractHash:n,baselineProjectionRef:Zc(s),baselineProjectionHash:s,currentProjectionRef:Zc(c),currentProjectionHash:c,complete:U.length===0,declaredArtifacts:r,changes:S,unattributed:k,unresolvedScopes:U,noCodeReason:a,...We?{gitAdvisory:We}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let g=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:b});if(Wn({...g,scopeHash:b})<=ei)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 y=o.totalChanges>m||f>h?rE({baseline:t,current:e,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):b,w=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:y}),E={...w,scopeHash:q(mp,w)};if(Wn(E)>ei)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return E}function zn(t){let e=el(t.baseline),i=el(t.current),n=wp(t);return{authority:n,baseline:e,current:i,scope:Np(e,i,n)}}var aE=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function lt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ut(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 Zt(t,e){if(typeof t!="string"||!il.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function up(t,e,i){let n=Zc(e);if(t!==n)throw new Error(`${i} ref/hash mismatch`);return n}function Ua(t,e){let i=lt(t,"Native snapshot projection");if(ut(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==pp)throw new Error("Native snapshot projection schema is invalid");let n=Cn({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=el(n);if(q(Vn,i)!==q(Vn,r))throw new Error("Native snapshot projection is not canonical");let a=q(Vn,r);if(e!==void 0&&Zt(e,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function nl(t,e){let i=lt(t,`Declared artifact ${e}`);if(ut(i,["path","kind"],[],`Declared artifact ${e}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${e} kind is invalid`);return{path:Ot(i.path,`Declared artifact ${e} path`),kind:i.kind}}function fp(t,e){if(t===null)return null;let i=lt(t,e);return ut(i,["hash","size"],[],e),{hash:Zt(i.hash,`${e} hash`),size:_i(i.size,`${e} size`)}}function dp(t,e){let i=lt(t,`Implementation change ${e}`);if(ut(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(nl),r=Ya(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${e} attribution must be sorted and unique`);let a=fp(i.before,`Implementation change ${e} before`),o=fp(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:Ot(i.path,`Implementation change ${e} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function oE(t,e){let i=lt(t,`Unresolved scope ${e}`);ut(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"?vp(i.path,`Unresolved scope ${e} path`):Ot(i.path,`Unresolved scope ${e} path`),reason:i.reason}}function Ka(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)=>Ot(r,`${e} ${a}`)),n=[...new Set(i)].sort(fe);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${e} must be sorted and unique`);return i}function Qa(t){let e=lt(t,"Native implementation scope"),i=[...aE].filter(S=>S!=="gitAdvisory");if(ut(e,i,["gitAdvisory"],"Native implementation scope"),e.schema!==Qc)throw new Error("Native implementation scope schema is invalid");let n=Zt(e.contractHash,"Implementation scope contractHash"),r=Zt(e.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=up(e.baselineProjectionRef,r,"Implementation scope baseline projection"),o=Zt(e.currentProjectionHash,"Implementation scope currentProjectionHash"),s=up(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(nl);if(JSON.stringify(c)!==JSON.stringify(Ya(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=e.changes.map(dp),f=[...l].sort((S,k)=>fe(S.path,k.path));if(JSON.stringify(l)!==JSON.stringify(f)||new Set(l.map(S=>S.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let u=new Set(c.map(S=>`${S.kind}:${S.path}`));if(l.some(S=>S.attributedTo.some(k=>!u.has(`${k.kind}:${k.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(S=>JSON.stringify(S.attributedTo)!==JSON.stringify(c.filter(k=>Xa(k,S.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=e.unattributed.map(dp),p=l.filter(S=>S.attributedTo.length===0);if(JSON.stringify(d)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=e.unresolvedScopes.map(oE),h=m.filter(S=>S.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:nE(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 b=e.noCodeReason,N=[...p.map(S=>ct({kind:"unattributed-change",source:"implementation-scope",path:S.path,evidence:{after:S.after,before:S.before,changeKind:S.kind}},`Changed path is not covered by a declared artifact: ${S.path}`)),...l.length+(v?.changes??0)===0&&b===null?[ct({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")]:[]],y=m.filter(S=>S.kind==="unattributed-change"||S.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(tl))||new Set(m.map(S=>S.id)).size!==m.length||JSON.stringify(y)!==JSON.stringify(N.sort(tl))||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 w;if(e.gitAdvisory!==void 0){let S=lt(e.gitAdvisory,"Implementation scope Git advisory");if(ut(S,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),S.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let k=Ka(S.changedPaths,"Git changed paths"),C=Ka(S.pathsPresentInSnapshotChanges,"Git present paths"),B=Ka(S.pathsAbsentFromSnapshotChanges,"Git absent paths"),G=[...C,...B].sort(fe),M=new Set(l.map(V=>V.path));if(JSON.stringify(G)!==JSON.stringify(k)||(v?.changes??0)===0&&C.some(V=>!M.has(V))||B.some(V=>M.has(V)))throw new Error("Implementation scope Git advisory partition is invalid");w={advisoryOnly:!0,changedPaths:k,pathsPresentInSnapshotChanges:C,pathsAbsentFromSnapshotChanges:B}}let E={schema:Qc,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:e.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:m,noCodeReason:b,...w?{gitAdvisory:w}:{}},g=Zt(e.scopeHash,"Implementation scope scopeHash");if(q(mp,E)!==g)throw new Error("Implementation scope content hash mismatch");return{...E,scopeHash:g}}function sE(t){let e=lt(t,"Native implementation scope authority");if(ut(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(nl);if(JSON.stringify(i)!==JSON.stringify(Ya(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=Ka(e.gitChangedPaths,"Native implementation scope authority Git paths"));let r=wp({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 Za(t){let e=lt(t,"Native implementation scope bundle");ut(e,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=sE(e.authority),n=Ua(e.baseline),r=Ua(e.current),a=Qa(e.scope),o=Np(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 bp(t){let e=Qa(t.scope);return Za({authority:{contractHash:e.contractHash,declaredArtifacts:e.declaredArtifacts,noCodeReason:e.noCodeReason,...e.gitAdvisory?{gitChangedPaths:e.gitAdvisory.changedPaths}:{}},baseline:t.baseline,current:t.current,scope:e})}function rl(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 lE=/^[a-f0-9]{64}$/u;var kp=["disposition","overrideSummaryHash","signatureHash"],uE=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"];function ol(t,e){return t<e?-1:t>e?1:0}function fE(t,e,i){let n=Object.keys(t).sort(ol);if(n.length!==e.length||n.some((r,a)=>r!==e[a]))throw new Error(`${i} fields are invalid`)}function dE(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 al(t,e){if(typeof t!="string"||!lE.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function hE(t){if(!Array.isArray(t)||t.length>Xc.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(ol)}function Sp(t){let e=dE(t,"Native repair trajectory projection"),i=Object.keys(e).sort(ol),n=i.length===kp.length&&i.every((l,f)=>l===kp[f]);n||fE(e,uE,"Native repair trajectory projection");let r=al(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:al(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=al(e.contractHash,"Native repair trajectory contract hash"),s=hE(e.failedAcceptanceIds),c=op(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 Oi={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:[]},sl=K("comet-native-runtime:v3:semantic-repair-budget"),pE=[{skillVersion:"2",skillHash:K("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:K("comet-native-runtime:v1")}];function Ep(t){return t.skillVersion===Oi.definition.metadata.version&&t.skillHash===sl||pE.some(e=>e.skillVersion===t.skillVersion&&e.skillHash===t.skillHash)}async function eo(t){let i={sequence:(await Ai(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 Ih(t.changeDir,t.run.trajectoryRef,i),i}async function cl(t){let e={runId:t.run.runId,stateVersion:t.run.iteration,trajectoryOffset:t.trajectoryOffset,contextHash:null,artifactsHash:K(t.evidenceHash),createdAt:(t.now??new Date).toISOString()};return await _h(t.changeDir,t.run.checkpointRef,e),e}function Cp(t){return K(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 Op=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],gE=new Set(Op),jp=new Set([...Op,"minimum_runtime_version","revision"]),wE=new Set([...jp,"operation"]),yE=512*1024,ul=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),NE=new Set([...ul,"implementationScopeHash","repairScopeHash","repairStagnation"]),fl=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 pl(t,e){return vE.join(J(t,e),"runtime","transition.json")}function bE(t){return`transition-${t}`}async function kE(t,e,i){let n=bE(e);return Sn(t,n,i)}async function Jn(t,e,i,n){let r=await kE(t,e,i);try{return await n()}finally{await En(r)}}function io(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native transition journal must be an object");return t}function ml(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 to(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ze(t,e){return hl(t,e)}function dl(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(f=>!NE.has(f)),a=[...ul].find(f=>!Object.hasOwn(i,f)),o=ul.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(rl(i.summary,"Native transition journal event summary"),Qe(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(f=>typeof f!="string"||f.length===0||Buffer.byteLength(f,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(rl(i.noCodeReason,"Native transition journal event no-code reason"),Qe(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")?Sp(i.repairStagnation):null;if(c){let f=c.overrideSummaryHash===null;if(f&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!f&&(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 SE(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 dl({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},e)}return dl(t,e)}function vl(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?SE(t.eventData,t.evidenceHash):dl(t.eventData,t.evidenceHash),r=Oc(t.nextRun),a=t.previousRun===null?null:Oc(t.previousRun);return{id:t.id,evidenceHash:t.evidenceHash,createdAt:t.createdAt,previousRun:a,nextRun:r,eventData:n}}function Rp(t,e,i=!1){if(t.skill!==Oi.definition.metadata.name||(i?!Ep(t):t.skillVersion!==Oi.definition.metadata.version||t.skillHash!==sl)||t.orchestration!==Oi.definition.orchestration.mode||t.pendingRef!==Xe.pendingRef||t.trajectoryRef!==Xe.trajectoryRef||t.contextRef!==Xe.contextRef||t.artifactsRef!==Xe.artifactsRef||t.checkpointRef!==Xe.checkpointRef)throw new Error(`Native transition journal ${e} metadata or storage refs are invalid`)}function Pp(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 Ap(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 gl(t,e,i,n=!1){let{previousRun:r,nextRun:a}=i;if(Rp(a,"next Run",n||r!==null),Ap(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(Rp(r,"previous Run",!0),Ap(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(!hl(Pp(r),Pp(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function EE(t,e,i){return K(JSON.stringify({operation:"spec-rebase",change:t,summary:e,specChanges:i}))}function Hp(t,e,i){return t.phase!=="shape"&&e.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function xp(t){return"implementation_scope"in t?{implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance}:null}function wl(t,e,i,n,r=!1){let a=i.eventData,o=xp(t),s=xp(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&&hl(t.spec_changes,e.spec_changes),l=Cp({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=EE(t.name,a.summary,e.spec_changes),l=K(`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 CE(t,e){let i=io(t);if(ml(i,wE),i.schema!==xi)throw new Error(`Expected Native transition schema ${xi}`);let n=to(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 ${xi} minimum_runtime_version must be ${3}`);let r=to(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=vl(i,e),o=st(i.previousState),s=st(i.nextState);if(o.name!==e||s.name!==e)throw new Error("Native transition journal state mismatch");if(wl(o,s,a,i.operation),gl(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:xi,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 RE(t,e){let i=io(t);if(ml(i,gE),i.schema!==jn)throw new Error(`Expected Native transition schema ${jn}`);let n=vl(i,e,!0),r=Mn(i.previousState),a=Mn(i.nextState);if(r.name!==e||a.name!==e)throw new Error("Native transition journal state mismatch");return wl(r,a,n,Hp(r,a,n.eventData),!0),gl(r,a,n,!0),{schema:jn,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 PE(t,e){let i=io(t);if(ml(i,jp),i.schema!==Ti)throw new Error(`Expected Native transition schema ${Ti}`);if(to(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Ti} minimum_runtime_version must be 2`);let r=to(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=vl(i,e,!0),o=Bn(i.previousState),s=Bn(i.nextState);if(o.name!==e||s.name!==e)throw new Error("Native v2 transition journal state mismatch");if(wl(o,s,a,Hp(o,s,a.eventData),!0),gl(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Ti,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 AE(t,e){let i=io(t);if(i.schema===xi)return{status:"current",journal:CE(i,e)};if(i.schema===jn)return{status:"migration-required",journal:RE(i,e)};if(i.schema===Ti)return{status:"migration-required",journal:PE(i,e)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function xE(t,e){let i=pl(t,e);await F(t.nativeRoot,i);try{let n=await rt({root:t.nativeRoot,file:i,maxBytes:yE,label:`Native transition journal ${e}`});return AE(JSON.parse(n.bytes.toString("utf8")),e)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ll(t,e){let i=await xE(t,e);if(!i)return null;if(i.status==="migration-required")throw new fl(e);return i.journal}function Tp(t,e){if(Ze(t,e.nextRun))return"next";if(e.previousRun===null){if(t===null)return"previous"}else if(Ze(t,e.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${e.change}; recovery journal was preserved`)}function Ip(t,e){if(Ze(t,e.nextState))return"next";if(Ze(t,e.previousState))return"previous";throw new Error(`Native transition change content changed for ${e.change}; recovery journal was preserved`)}function TE(t){let{journal:e}=t;return $p({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 $p(t){return{sequence:t.sequence,timestamp:t.timestamp,type:t.type,runId:t.runId,data:t.data}}function _p(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=TE({sequence:a.index+1,journal:e,type:a.event.type});if(!Ze($p(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 yl(t,e,i){if(await Dn(t,e))throw new Error(`Native schema migration is incomplete for ${e}; run doctor --repair`);await ja(t,e);let n=await ll(t,e);if(!n)return null;let r=J(t,e),a=_p(await Ai(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([_n(r),xe(t,e)]),c=Tp(o,n),l=Ip(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 jc(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!Ze(await _n(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 qa(t,n.nextState,n.previousState.revision);if(!Ze(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!Ze(await xe(t,e),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let f=await ll(t,e);if(!f||!Ze(f,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let u=_p(await Ai(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(u.started||await eo({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=u.transitioned;d||(d=await eo({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await cl({changeDir:r,run:n.nextRun,trajectoryOffset:d.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([_n(r),xe(t,e)]);Tp(p,{...n,previousRun:n.nextRun}),Ip(m,{...n,previousState:n.nextState});let h=await ll(t,e);if(!h||!Ze(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await mE.rm(pl(t,e),{force:!0}),n.nextState}async function Fp(t,e,i){let n=await np(t,e);if(!n)return null;if(await rp(t,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await qa(t,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await ap(t,n.checkpoint),await i?.afterProgressWritten?.(n),await IE.rm(Gc(t,e),{force:!0}),n}async function no(t,e){await yl(t,e),await Fp(t,e)}import{createHash as CC}from"node:crypto";import{constants as Il,promises as Ve}from"node:fs";import si from"node:path";import{TextDecoder as RC}from"node:util";import Lp from"node:path";var ro="comet.native.check-receipt.v1",Dp="comet.native.check-receipt.v1",jt="scoped-text-safety",Gn=1,ae=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),_E=/^[a-f0-9]{64}$/u,OE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jE="comet.native.checker-policy.v1",HE="comet.native.check-input.v1",$E=2048,ao=q(jE,{policy:jt,version:Gn,limits:ae,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),FE=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),Mp=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],qp=["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"],LE=new Set(qp);function ii(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ni(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 ft(t,e){if(typeof t!="string"||!_E.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function ti(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Vp(t,e){let i=ti(t,e);if(i<1)throw new Error(`${e} must be a positive integer`);return i}function Bp(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let i=new Date(t);if(!Number.isFinite(i.getTime())||i.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function ME(t,e){if(typeof t!="string"||t.length===0||Buffer.byteLength(t,"utf8")>$E||t.includes("\\")||t.includes("\0")||t.endsWith("/")||/^[a-zA-Z]:/u.test(t))throw new Error(`${e} must be a bounded normalized project-relative path`);let i=Lp.posix.normalize(t);if(i!==t||i==="."||i===".."||i.startsWith("../")||Lp.posix.isAbsolute(i))throw new Error(`${e} must stay inside the project root`);return t}function BE(t){let e=ii(t,"Native check receipt checker");ni(e,["policy","version","hash","limits"],"Native check receipt checker");let i=ii(e.limits,"Native check receipt limits");if(ni(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),e.policy!==jt||e.version!==Gn||e.hash!==ao||i.maxFiles!==ae.maxFiles||i.maxFileBytes!==ae.maxFileBytes||i.maxTotalBytes!==ae.maxTotalBytes||i.maxIssues!==ae.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:jt,version:Gn,hash:ao,limits:{...ae}}}function DE(t){let e=ii(t,"Native check receipt contract");return ni(e,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:ft(e.expectedHash,"Native check expected contract hash"),beforeHash:ft(e.beforeHash,"Native check before contract hash"),afterHash:ft(e.afterHash,"Native check after contract hash")}}function qE(t){let e=ii(t,"Native check receipt implementation");return ni(e,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:ft(e.scopeHash,"Native check scope hash"),expectedSnapshotHash:ft(e.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:ft(e.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:ft(e.afterSnapshotHash,"Native check after snapshot hash")}}function VE(t){let e=ii(t,"Native check receipt counts");ni(e,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:ti(e.filesSelected,"Native check filesSelected"),filesScanned:ti(e.filesScanned,"Native check filesScanned"),binaryFilesSkipped:ti(e.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:ti(e.bytesScanned,"Native check bytesScanned"),issueCount:ti(e.issueCount,"Native check issueCount"),recordedIssueCount:ti(e.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>ae.maxFiles||i.bytesScanned>ae.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>ae.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function WE(t,e){return t.path.localeCompare(e.path,"en")||t.line-e.line||Mp.indexOf(t.kind)-Mp.indexOf(e.kind)}function zE(t){if(!Array.isArray(t)||t.length>ae.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let e=t.map((n,r)=>{let a=ii(n,`Native check issue ${r}`);if(ni(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!FE.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:ME(a.path,`Native check issue ${r} path`),line:Vp(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...e].sort(WE);if(JSON.stringify(i)!==JSON.stringify(e))throw new Error("Native check receipt issues must be canonical");return e}function JE(t){if(!Array.isArray(t)||t.some(n=>typeof n!="string"||!LE.has(n)))throw new Error("Native check receipt stale reasons are invalid");let e=t,i=qp.filter(n=>e.includes(n));if(new Set(e).size!==e.length||JSON.stringify(i)!==JSON.stringify(e))throw new Error("Native check receipt stale reasons must be canonical");return[...e]}function Wp(t){return q(HE,t)}function ri(t){let e=ii(t,"Native check receipt");if(ni(e,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),e.schema!==ro)throw new Error("Native check receipt schema is invalid");if(typeof e.change!="string"||Buffer.byteLength(e.change,"utf8")>128||!OE.test(e.change))throw new Error("Native check receipt change name is invalid");let i=Vp(e.sourceRevision,"Native check source revision"),n=BE(e.checker),r=DE(e.contract),a=qE(e.implementation),o=Wp({change:e.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(ft(e.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(e.status!=="passed"&&e.status!=="failed")throw new Error("Native check receipt status is invalid");let s=Bp(e.startedAt,"Native check receipt startedAt"),c=Bp(e.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=VE(e.counts),f=zE(e.issues);if(l.recordedIssueCount!==f.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof e.issuesTruncated!="boolean"||e.issuesTruncated!==l.issueCount>f.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let u=JE(e.staleReasons);if(typeof e.stale!="boolean"||e.stale!==u.length>0)throw new Error("Native check receipt stale flag is inconsistent");let d=l.issueCount===0&&!e.stale?"passed":"failed";if(e.status!==d)throw new Error("Native check receipt status is inconsistent with its evidence");if(e.status==="passed"&&(l.filesSelected>ae.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>ae.maxFiles&&!f.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:ro,change:e.change,sourceRevision:i,checker:n,inputHash:o,status:e.status,startedAt:s,endedAt:c,contract:r,implementation:a,counts:l,issues:f,issuesTruncated:e.issuesTruncated,stale:e.stale,staleReasons:u},m=ft(e.receiptHash,"Native check receipt content hash");if(q(Dp,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}function zp(t){let e={policy:jt,version:Gn,hash:ao,limits:{...ae}},i={schema:ro,...t,checker:e,inputHash:Wp({change:t.change,sourceRevision:t.sourceRevision,checkerHash:e.hash,contractHash:t.contract.expectedHash,scopeHash:t.implementation.scopeHash,snapshotHash:t.implementation.expectedSnapshotHash})};return ri({...i,receiptHash:q(Dp,i)})}import{constants as Nl,promises as Te}from"node:fs";import ai from"node:path";var GE=/^[a-f0-9]{64}$/u,KE=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,oi=512*1024;function UE(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function oo(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return le(i,n)?j(i,n):j(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function YE(t,e){let i=ai.resolve(t),n=ai.resolve(e);if(!z(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...ai.relative(i,n).split(ai.sep).filter(Boolean)]){o&&(a=ai.join(a,o));let s=await Te.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Te.realpath(a);if(r.length>0&&!z(r[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return r}async function Jp(t){for(let e of t){let i=await Te.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!UE(e,i)||await Te.realpath(e.path)!==e.realPath)throw new Error(`Native check receipt parent changed while reading: ${e.path}`)}}function Gp(t){if(!GE.test(t))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${t}.json`}function XE(t){let e=KE.exec(t);if(!e)throw new Error("Native check receipt ref is invalid");return e[1]}function Kp(t,e,i){return ai.join(J(t,e),...Gp(i).split("/"))}async function QE(t,e,i){let n=await YE(i,ai.dirname(t)),r=await Te.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>oi)throw new Error(`Native check receipt exceeds ${oi} bytes`);let[a,o]=await Promise.all([Te.realpath(e),Te.realpath(t)]);if(!z(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Nl.O_RDONLY|Nl.O_NOFOLLOW|Nl.O_NONBLOCK,c=await Te.open(t,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,f,u]=await Promise.all([c.stat(),Te.lstat(t),Te.realpath(t)]);if(await Jp(n),!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!oo(r,l)||!oo(l,f))throw new Error("Native check receipt changed while opening");let d=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let N=oi+1-p,y=await c.read(m,0,Math.min(m.length,N),null);if(y.bytesRead===0)break;if(p+=y.bytesRead,p>oi)throw new Error(`Native check receipt exceeds ${oi} bytes`);d.push(Buffer.from(m.subarray(0,y.bytesRead)))}let[h,v,b]=await Promise.all([c.stat(),Te.lstat(t),Te.realpath(t)]);if(await Jp(n),!v.isFile()||v.isSymbolicLink()||b!==o||!z(a,b)||!oo(l,h)||!oo(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(d,p).toString("utf8"))}finally{await c.close()}}async function so(t,e,i){let n=XE(i),r=J(t,e),a=Kp(t,e,n);await F(t.nativeRoot,a);let o=ri(await QE(a,r,t.nativeRoot));if(o.change!==e||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}async function Up(t){let e=ri(t.receipt);if(e.change!==t.name)throw new Error("Native check receipt change mismatch");let i=Gp(e.receiptHash),n=Kp(t.paths,t.name,e.receiptHash);if(Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
167
|
+
`,"utf8")>oi)throw new Error(`Native check receipt exceeds ${oi} bytes`);await F(t.paths.nativeRoot,n);try{let o=await so(t.paths,t.name,i);if(JSON.stringify(o)!==JSON.stringify(e))throw new Error(`Native check receipt hash collision for ${e.receiptHash}`);return i}catch(o){if(o.code!=="ENOENT")throw o}await Ce(n,e,{containedRoot:t.paths.nativeRoot});let a=await so(t.paths,t.name,i);if(JSON.stringify(a)!==JSON.stringify(e))throw new Error("Native check receipt changed while being persisted");return i}import em from"node:path";var ZE="comet.native.acceptance.v1";var Z_=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Un=Object.freeze({maxCriteria:1024});function Sl(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 bl(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 Yp(t){return t.includes("-->")||t.includes("--!>")}function*Kn(t){let e=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=t.replace(/\r\n?/gu,`
|
|
162
168
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
163
|
-
`,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=
|
|
164
|
-
`))),"Brief")}function
|
|
165
|
-
`),a.context)),a=null}};for(let{line:s,body:c}of
|
|
166
|
-
`))}function wE(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(Tp))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(Tp))throw new Error(`Replace contract ${t.capability} requires a base hash`);let e=Ip(t.source,`Contract source for ${t.capability}`);return{snapshot:{capability:t.capability,operation:t.operation,source:e,baseHash:t.baseHash,contentHash:_p(t.markdown)},markdown:t.markdown}}function yE(t,e){return Op(t.id,e.id)}function Op(t,e){return t<e?-1:t>e?1:0}function jp(t){let e=Ip(t.briefSource??"brief.md","Native brief source"),i=t.specs.map(wE).sort((u,d)=>Op(u.snapshot.capability,d.snapshot.capability)),n=i.map(({snapshot:u})=>u.capability);if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate capabilities");let r=[e,...i.flatMap(({snapshot:u})=>u.source===null?[]:[u.source])];if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate artifact sources");let a=Rp(t.briefMarkdown,e,Bn.maxAcceptanceCriteria);for(let{snapshot:u,markdown:d}of i)d===null||u.source===null||(a.push(...Pp(d,u.source,Bn.maxAcceptanceCriteria-a.length)),a.push(...Ap(d,u.source,Bn.maxAcceptanceCriteria-a.length)));if(a.sort(yE),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Bn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Bn.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:u})=>u);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:e,contentHash:_p(t.briefMarkdown)},c=i.map(({snapshot:u})=>u),l=V(gE,a),f={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...f,contractHash:V(vE,f)}}var Ka={maxSpecs:64,maxFileBytes:Kr,maxTotalBytes:4*1024*1024};async function qn(t){if(t.specChanges.length>Ka.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let e=await et({root:t.changeDir,ref:t.briefRef,maxBytes:Ka.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 et({root:t.changeDir,ref:r.source,maxBytes:Ka.maxFileBytes});if(i+=a.size,i>Ka.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:jp({briefSource:e.ref,briefMarkdown:e.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{promises as De}from"node:fs";import Ye from"node:path";var Ga="comet.native.verification-receipt.v3",Hp=Ga,NE="comet.native.declared-artifacts.v1",bE=/^[a-f0-9]{64}$/u,SE=/^acceptance-[a-f0-9]{64}$/u,kE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,EE=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,CE=4096,RE=256,PE=1024;function Ti(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"||!bE.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function Fe(t,e){if(typeof t!="string")throw new Error(`${e} must be text`);let i=Ge(t).trim();if(!i||i.length>CE||i!==t.trim())throw new Error(`${e} is invalid`);return i}function ll(t,e){let i=Fe(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 Vn(t,e,i=Fe,n=!1,r=RE){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 AE(t,e){if(typeof t!="string"||!SE.test(t))throw new Error(`${e} is invalid`);return t}function xE(t){let e=Ti(t,"Native verification receipt bindings");if(Ot(e,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof e.change!="string"||!kE.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 TE(t){if(typeof t!="string")throw new Error("Native static check receipt ref is invalid");let e=EE.exec(t);if(!e)throw new Error("Native static check receipt ref is invalid");return{ref:t,hash:e[1]}}function IE(t,e,i,n){let r=Ti(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=ll(r.startedAt,"Native automated-check start time"),o=ll(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=Ti(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=Ti(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:Fe(r.executable,"Native automated-check executable"),args:Vn(r.args,"Native automated-check arguments",Fe,!0),cwd:Fe(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:Fe(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:Fe(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=TE(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:Vn(r.subjects,"Native static inspection subjects",Fe,n==="required-check"),rule:Fe(r.rule,"Native static inspection rule"),resultSummary:Fe(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:Vn(r.steps,"Native manual evidence steps"),observations:Vn(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${t}`)}function $p(t){let e=Ti(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=Fe(e.actor,"Native verification receipt actor"),o=Vn(e.acceptanceIds,"Native receipt acceptance IDs",AE,n==="required-check",PE).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:Ga,kind:i,role:n,status:r,bindings:xE(e.bindings),acceptanceIds:o,actor:a,issuedAt:ll(e.issuedAt,"Native verification receipt issue time"),evidence:IE(i,e.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==_t||s.actor!==`native-runtime:${_t}`))throw new Error("Native required check policy identity is invalid");return s}function Lp(t){let e=$p({schema:Ga,...t});return{...e,receiptHash:V(Hp,e)}}function Mp(t){let e=Ti(t,"Native verification receipt");if(Ot(e,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),e.schema!==Ga)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=e,r=$p(n),a=ft(e.receiptHash,"Native verification receipt hash");if(V(Hp,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function ul(t){return V(NE,[...t].map(e=>({path:e.path,kind:e.kind})).sort((e,i)=>e.path.localeCompare(i.path)||e.kind.localeCompare(i.kind)))}var _E=/^[a-f0-9]{64}$/u,jt=Xt,u_=3*jt;function dl(t,e){let i=Ye.relative(t,e);return i===""||!Ye.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ye.sep}`)}function OE(t,e){return H({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Ua(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?H(i,n):H(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Fp(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 jE(t,e){let i=Ye.resolve(t),n=Ye.resolve(e);if(!dl(i,n))throw new Error("Native evidence path is outside its change");let r=[await Fp(i)],a=i;for(let o of Ye.relative(i,n).split(Ye.sep).filter(Boolean)){a=Ye.join(a,o);let s=await Fp(a);if(!dl(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function Dp(t){for(let e of t){let i=await De.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!OE(e,i)||await De.realpath(e.path)!==e.realPath)throw new Error(`Native evidence parent changed while reading: ${e.path}`)}}async function HE(t,e,i={}){let n=await jE(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(!dl(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 Dp(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Ua(s,r)||!Ua(s,c))throw new Error("Native evidence document changed while opening");if(s.size>jt)throw new Error(`Native evidence document exceeds ${jt} bytes`);await i.afterOpen?.();let f=[],u=0,d=Buffer.allocUnsafe(64*1024);for(;;){let v=jt+1-u,N=await o.read(d,0,Math.min(d.length,v),null);if(N.bytesRead===0)break;if(u+=N.bytesRead,u>jt)throw new Error(`Native evidence document exceeds ${jt} bytes`);f.push(Buffer.from(d.subarray(0,N.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),De.lstat(t),De.realpath(t)]);if(await Dp(n),!m.isFile()||m.isSymbolicLink()||h!==a||!Ua(s,p)||!Ua(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(f,u).toString("utf8"))}finally{await o.close()}}function Ya(t,e){if(!_E.test(e))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${t}/${e}.json`}function fl(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 qp(t,e,i,n,r){return Ye.join(r??U(t,e),...Ya(i,n).split("/"))}async function zn(t){let e=t.changeDir??U(t.paths,t.name),i=qp(t.paths,t.name,t.kind,t.hash,e);return await M(t.paths.nativeRoot,i),HE(i,e,t.hooks)}async function $E(t){LE(t.value);let e=qp(t.paths,t.name,t.kind,t.hash);await M(t.paths.nativeRoot,e);try{let n=await zn(t);if(JSON.stringify(n)!==JSON.stringify(t.value))throw new Error(`Native evidence hash collision for ${t.hash}`);return Ya(t.kind,t.hash)}catch(n){if(n.code!=="ENOENT")throw n}await ke(e,t.value,{containedRoot:t.paths.nativeRoot});let i=await zn(t);if(JSON.stringify(i)!==JSON.stringify(t.value))throw new Error(`Native evidence changed during commit for ${t.hash}`);return Ya(t.kind,t.hash)}function LE(t){if(ME(t)>jt)throw new Error(`Native evidence document exceeds ${jt} bytes`)}function ME(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
167
|
-
`,"utf8")}function
|
|
168
|
-
`);for(let r=0;r<n.length;r+=1){let a=n[r].endsWith("\r")?n[r].slice(0,-1):n[r],o=r+1;/^(?:<{7}|={7}|>{7})(?: |$)/u.test(a)&&i({path:t,line:o,kind:"conflict-marker"}),/[ \t]+$/u.test(a)&&i({path:t,line:o,kind:"trailing-whitespace"}),/^ +\t/u.test(a)&&i({path:t,line:o,kind:"space-before-tab"})}}async function Gp(t){if(!t.state.implementation_scope)throw new Error("Native scoped check requires an implementation scope");let e=await Wn(t.paths,t.state.name,t.state.implementation_scope),i=await Wp({paths:t.paths,state:t.state,scope:e}),n=Jp(t.clock,"start"),r=KE(e),a=[],o=0,s=y=>{o+=1,a.length<ne.maxIssues&&a.push(y)},c=r.files,l=r.files.length+r.mismatches.length;if(e.scope.unresolvedScopes.some(y=>y.kind==="scope-detail-overflow")){let y=e.scope.changes.at(-1)?.path??e.current.entries.at(-1)?.path??e.baseline.entries.at(-1)?.path;if(!y)throw new Error("Native implementation scope overflow has no bounded diagnostic path");s({path:y,line:1,kind:"scan-limit"}),c=[]}else if(l>ne.maxFiles){let y=[...r.files.map(w=>w.path),...r.mismatches].sort((w,k)=>w.localeCompare(k,"en"));s({path:y[ne.maxFiles],line:1,kind:"scan-limit"}),c=[]}else{let y=0;for(let w of r.files){if(w.expected.size>ne.maxFileBytes){s({path:w.path,line:1,kind:"scan-limit"}),c=[];break}if(y+=w.expected.size,y>ne.maxTotalBytes){s({path:w.path,line:1,kind:"scan-limit"}),c=[];break}}}for(let y of r.mismatches)s({path:y,line:1,kind:"scope-mismatch"});let u=0,d=0,p=0;for(let y of c)try{let w=await JE({projectRoot:t.paths.projectRoot,file:y});p+=w.bytes,w.text===null?(d+=1,s({path:y.path,line:1,kind:"binary-skipped"})):(u+=1,GE(y.path,w.text,s))}catch(w){if(!(w instanceof Z))throw w;s({path:y.path,line:1,kind:w.kind})}let m=await Wp({paths:t.paths,state:t.state,scope:e}),h=Jp(t.clock,"end"),v=VE(i,m,e);a.sort((y,w)=>y.path.localeCompare(w.path,"en")||y.line-w.line||zp[y.kind]-zp[w.kind]);let N=Np({change:t.state.name,sourceRevision:t.state.revision,status:o===0&&v.length===0?"passed":"failed",startedAt:n,endedAt:h,contract:{expectedHash:e.scope.contractHash,beforeHash:i.contractHash,afterHash:m.contractHash},implementation:{scopeHash:e.scope.scopeHash,expectedSnapshotHash:e.scope.currentProjectionHash,beforeSnapshotHash:i.snapshotHash,afterSnapshotHash:m.snapshotHash},counts:{filesSelected:l,filesScanned:u,binaryFilesSkipped:d,bytesScanned:p,issueCount:o,recordedIssueCount:a.length},issues:a,issuesTruncated:o>a.length,stale:v.length>0,staleReasons:v}),b=await Ep({paths:t.paths,name:t.state.name,receipt:N});return{receipt:ti(N),ref:b}}import{execFile as UE,spawn as T_}from"node:child_process";import{promisify as YE}from"node:util";var z_=64*1024;var W_=3600*1e3;var J_=YE(UE);var K_=["$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("; ");async function XE(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([Wn(t,e.name,e.implementation_scope),qn({changeDir:U(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:ul(i.scope.declaredArtifacts)},acceptanceIds:n.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${r}`,implementationExecutionId:r,scope:i}}async function Up(t){let e=await XE(t.paths,t.state),i=t.checkReceipt.stale||t.checkReceipt.issues.some(o=>["scan-limit","scope-mismatch","unsafe-file","binary-skipped"].includes(o.kind)),n=t.checkReceipt.status==="passed"?"passed":i?"blocked":"failed",r=Lp({kind:"static-inspection",role:"required-check",status:n,bindings:e.bindings,acceptanceIds:[],actor:`native-runtime:${t.checkReceipt.checker.policy}`,issuedAt:t.checkReceipt.endedAt,evidence:{subjects:e.scope.scope.changes.map(o=>o.path).sort(),rule:t.checkReceipt.checker.policy,resultSummary:n==="passed"?"The built-in scoped inspection passed without skipped or blocking input.":`The built-in scoped inspection recorded ${t.checkReceipt.counts.issueCount} blocking issue(s).`,checkReceiptRef:t.checkReceiptRef,checkReceiptHash:t.checkReceipt.receiptHash}}),a=await Vp({paths:t.paths,name:t.state.name,receipt:r});return{receipt:r,ref:a}}async function Yp(t){return rt(t.paths,`check ${t.name}`,()=>Ln(t.paths,t.name,`check ${t.name}`,()=>QE(t)))}async function QE(t){await Va(t.paths,t.name);let e=await Pe(t.paths,t.name);if(e.phase!=="verify")throw new Error(`Native check requires Verify, got ${e.phase}`);if(!e.implementation_scope)throw new Error("Native check requires an implementation scope");let i=await Gp({paths:t.paths,state:e}),n=await Up({paths:t.paths,state:e,checkReceipt:i.receipt,checkReceiptRef:i.ref});return{change:e,receipt:i.receipt,checkRef:i.ref,ref:n.ref}}import oC from"path";var eC=["Outcome","Scope","Non-goals","Acceptance examples"],mO=[...eC,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var tC=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 Qa=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 fj={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var bj=16*1024*1024,Sj=256*1024,kj=16*1024;var Rj=16*1024;var Lj=16*1024;var E0=16*1024*1024,Za=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"},eo=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 O0=10*1024*1024,Ht=class extends Error{};function Xp(t,e){let i=t.flatMap((n,r)=>n===e?[r]:[]);if(i.length>1)throw new Ht(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function Qp(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new Ht(`${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 Ht(`${e} requires a value`);return t.splice(n,2),r}function Zp(t){if(t.length>0)throw new Ht(`Unexpected argument: ${t[0]}`)}function em(t,e){let i=t.shift();if(!i||i.startsWith("--"))throw new Ht(`${e} is required`);return i}async function tm(t){return t?oC.resolve(t):aa(process.cwd())}async function im(t){let e=await bd({startPath:t,allowMissingConfig:!1});return{config:e.config,paths:e.paths}}function nm(t,e){if(e instanceof Ht)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof Za)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 eo)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof An)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 Ca)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 Qa)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",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 rm(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}})+`
|
|
169
|
-
`}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function
|
|
170
|
-
`}}function
|
|
171
|
-
`}}async function
|
|
169
|
+
`,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=bl(l,e);else if(i)Yp(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let u=bl(l,null);if(u!==null)e=u;else{let d=l.trimStart();if(d.startsWith("<!--")&&!Yp(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 kl(t){return t.normalize("NFC").replace(/\s+/gu," ").trim()}function El(t,e,i,n=[]){let r=kl(i),a=e.replaceAll("\\","/").trim(),o=n.map(kl);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-${q(ZE,{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 eC(t){let e=null,i=null,n=0,r=0;for(let{line:a,body:o,index:s}of Kn(t)){r=s+1;let c=o?Sl(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 Xp(t,e="brief.md",i=Un.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=eC(t);if(n===null)return[];let r=null;for(let{line:c,body:l,index:f}of Kn(t)){if(f<n.start||f>=n.end)continue;let u=l?/^( {0,3})[-*+][ \t]+/u.exec(c):null;if(u===null)continue;let d=u[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:f}of Kn(t)){if(f<n.start||f>=n.end)continue;let u=l?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;u&&u[1].length===r?(s(),o=[u[2]]):o!==null&&o.push(c)}return s(),Cl(a.map(c=>El("brief-example",e,c.join(`
|
|
170
|
+
`))),"Brief")}function Qp(t,e="spec.md",i=Un.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(El("spec-scenario",e,[a.title,...a.body].join(`
|
|
171
|
+
`),a.context)),a=null}};for(let{line:s,body:c}of Kn(t)){let l=c?Sl(s):null,f=l?/^Scenario\s*:\s*(.*)$/iu.exec(l.text):null;if(f){for(o();r.at(-1)&&r.at(-1).level>=l.level;)r.pop();let u=kl(f[1]);if(u.length===0)throw new Error("Scenario title must not be empty");a={level:l.level,title:u,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 Zp(t,e="spec.md",i=Un.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(El("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:f}of Kn(t)){let u=f?Sl(l):null;if(u){for(s(),a!==null&&u.level<=a&&(a=null);r.at(-1)&&r.at(-1).level>=u.level;)r.pop();r.push(u),/^Scenario\s*:/iu.test(u.text)&&(a=u.level);continue}let d=l.trim();if(!f||a!==null||c()){s();continue}if(d.length===0||bl(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")}var tC="comet.native.contract.v1",iC="comet.native.acceptance-set.v1",tm=/^[a-f0-9]{64}$/u,Yn={maxAcceptanceCriteria:Un.maxCriteria};function im(t,e){let i=em.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})||em.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 nm(t){return q("comet.native.contract-content.v1",t.replace(/\r\n?/gu,`
|
|
172
|
+
`))}function nC(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(tm))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(tm))throw new Error(`Replace contract ${t.capability} requires a base hash`);let e=im(t.source,`Contract source for ${t.capability}`);return{snapshot:{capability:t.capability,operation:t.operation,source:e,baseHash:t.baseHash,contentHash:nm(t.markdown)},markdown:t.markdown}}function rC(t,e){return rm(t.id,e.id)}function rm(t,e){return t<e?-1:t>e?1:0}function am(t){let e=im(t.briefSource??"brief.md","Native brief source"),i=t.specs.map(nC).sort((u,d)=>rm(u.snapshot.capability,d.snapshot.capability)),n=i.map(({snapshot:u})=>u.capability);if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate capabilities");let r=[e,...i.flatMap(({snapshot:u})=>u.source===null?[]:[u.source])];if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate artifact sources");let a=Xp(t.briefMarkdown,e,Yn.maxAcceptanceCriteria);for(let{snapshot:u,markdown:d}of i)d===null||u.source===null||(a.push(...Qp(d,u.source,Yn.maxAcceptanceCriteria-a.length)),a.push(...Zp(d,u.source,Yn.maxAcceptanceCriteria-a.length)));if(a.sort(rC),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Yn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Yn.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:u})=>u);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:e,contentHash:nm(t.briefMarkdown)},c=i.map(({snapshot:u})=>u),l=q(iC,a),f={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...f,contractHash:q(tC,f)}}var co={maxSpecs:64,maxFileBytes:ra,maxTotalBytes:4*1024*1024};async function Xn(t){if(t.specChanges.length>co.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let e=await Ke({root:t.changeDir,ref:t.briefRef,maxBytes:co.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 Ke({root:t.changeDir,ref:r.source,maxBytes:co.maxFileBytes});if(i+=a.size,i>co.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:am({briefSource:e.ref,briefMarkdown:e.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{promises as Ie}from"node:fs";import qe from"node:path";var lo="comet.native.verification-receipt.v3",om=lo,aC="comet.native.declared-artifacts.v1",oC=/^[a-f0-9]{64}$/u,sC=/^acceptance-[a-f0-9]{64}$/u,cC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lC=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,uC=4096,fC=256,dC=1024;function ji(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 Ht(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 dt(t,e){if(typeof t!="string"||!oC.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=Qe(t).trim();if(!i||i.length>uC||i!==t.trim())throw new Error(`${e} is invalid`);return i}function Rl(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 Qn(t,e,i=De,n=!1,r=fC){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 hC(t,e){if(typeof t!="string"||!sC.test(t))throw new Error(`${e} is invalid`);return t}function pC(t){let e=ji(t,"Native verification receipt bindings");if(Ht(e,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof e.change!="string"||!cC.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:dt(e.contractHash,"Native verification receipt contract hash"),scopeHash:dt(e.scopeHash,"Native verification receipt scope hash"),snapshotHash:dt(e.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:dt(e.artifactHash,"Native verification receipt artifact hash")}}function mC(t){if(typeof t!="string")throw new Error("Native static check receipt ref is invalid");let e=lC.exec(t);if(!e)throw new Error("Native static check receipt ref is invalid");return{ref:t,hash:e[1]}}function vC(t,e,i,n){let r=ji(e,`Native ${t} evidence`);if(t==="automated-check"){if(Ht(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=Rl(r.startedAt,"Native automated-check start time"),o=Rl(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=ji(r.worktree,"Native automated-check worktree");if(Ht(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=ji(r.afterFence,"Native automated-check after fence");if(Ht(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:Qn(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:dt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:dt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:dt(r.outputHash,"Native automated-check output hash"),outputSummary:De(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(t==="static-inspection"){Ht(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=mC(r.checkReceiptRef);if(dt(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",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 Ht(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 sm(t){let e=ji(t,"Native verification receipt");if(Ht(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=Qn(e.acceptanceIds,"Native receipt acceptance IDs",hC,n==="required-check",dC).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:lo,kind:i,role:n,status:r,bindings:pC(e.bindings),acceptanceIds:o,actor:a,issuedAt:Rl(e.issuedAt,"Native verification receipt issue time"),evidence:vC(i,e.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==jt||s.actor!==`native-runtime:${jt}`))throw new Error("Native required check policy identity is invalid");return s}function cm(t){let e=sm({schema:lo,...t});return{...e,receiptHash:q(om,e)}}function Pl(t){let e=ji(t,"Native verification receipt");if(Ht(e,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),e.schema!==lo)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=e,r=sm(n),a=dt(e.receiptHash,"Native verification receipt hash");if(q(om,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function Al(t){return q(aC,[...t].map(e=>({path:e.path,kind:e.kind})).sort((e,i)=>e.path.localeCompare(i.path)||e.kind.localeCompare(i.kind)))}var gC=/^[a-f0-9]{64}$/u,$t=ei,kO=3*$t;function xl(t,e){let i=qe.relative(t,e);return i===""||!qe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${qe.sep}`)}function wC(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function uo(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return le(i,n)?j(i,n):j(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function lm(t){let e=await Ie.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${t}`);return{path:t,realPath:await Ie.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function yC(t,e){let i=qe.resolve(t),n=qe.resolve(e);if(!xl(i,n))throw new Error("Native evidence path is outside its change");let r=[await lm(i)],a=i;for(let o of qe.relative(i,n).split(qe.sep).filter(Boolean)){a=qe.join(a,o);let s=await lm(a);if(!xl(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function um(t){for(let e of t){let i=await Ie.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!wC(e,i)||await Ie.realpath(e.path)!==e.realPath)throw new Error(`Native evidence parent changed while reading: ${e.path}`)}}async function NC(t,e,i={}){let n=await yC(e,qe.dirname(t));await i.afterParentChainCaptured?.();let r=await Ie.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Ie.realpath(t);if(!xl(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Ie.open(t,"r");try{let[s,c,l]=await Promise.all([o.stat(),Ie.lstat(t),Ie.realpath(t)]);if(await um(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!uo(s,r)||!uo(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 f=[],u=0,d=Buffer.allocUnsafe(64*1024);for(;;){let v=$t+1-u,b=await o.read(d,0,Math.min(d.length,v),null);if(b.bytesRead===0)break;if(u+=b.bytesRead,u>$t)throw new Error(`Native evidence document exceeds ${$t} bytes`);f.push(Buffer.from(d.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Ie.lstat(t),Ie.realpath(t)]);if(await um(n),!m.isFile()||m.isSymbolicLink()||h!==a||!uo(s,p)||!uo(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(f,u).toString("utf8"))}finally{await o.close()}}function Zn(t,e){if(!gC.test(e))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${t}/${e}.json`}function fo(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 dm(t,e,i,n,r){return qe.join(r??J(t,e),...Zn(i,n).split("/"))}async function Hi(t){let e=t.changeDir??J(t.paths,t.name),i=dm(t.paths,t.name,t.kind,t.hash,e);return await F(t.paths.nativeRoot,i),NC(i,e,t.hooks)}async function bC(t){kC(t.value);let e=dm(t.paths,t.name,t.kind,t.hash);await F(t.paths.nativeRoot,e);try{let n=await Hi(t);if(JSON.stringify(n)!==JSON.stringify(t.value))throw new Error(`Native evidence hash collision for ${t.hash}`);return Zn(t.kind,t.hash)}catch(n){if(n.code!=="ENOENT")throw n}await Ce(e,t.value,{containedRoot:t.paths.nativeRoot});let i=await Hi(t);if(JSON.stringify(i)!==JSON.stringify(t.value))throw new Error(`Native evidence changed during commit for ${t.hash}`);return Zn(t.kind,t.hash)}function kC(t){if(SC(t)>$t)throw new Error(`Native evidence document exceeds ${$t} bytes`)}function SC(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
173
|
+
`,"utf8")}function fm(t,e){return Ua(t,e)}function EC(t,e){let i=Qa(t);if(i.scopeHash!==e)throw new Error("Native implementation scope ref/hash mismatch");return i}async function er(t,e,i,n,r){let a=fo(i,"scopes"),o=EC(await Hi({paths:t,name:e,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=fo(o.baselineProjectionRef,"snapshots"),c=fo(o.currentProjectionRef,"snapshots"),[l,f]=await Promise.all([Hi({paths:t,name:e,kind:"snapshots",hash:s,changeDir:r}).then(u=>fm(u,s)),Hi({paths:t,name:e,kind:"snapshots",hash:c,changeDir:r}).then(u=>fm(u,c))]);return bp({baseline:l,current:f,scope:o})}async function hm(t){let e=Pl(t.receipt);if(e.bindings.change!==t.name)throw new Error("Native verification receipt change mismatch");return bC({paths:t.paths,name:t.name,kind:"receipts",hash:e.receiptHash,value:e})}async function Tl(t,e,i,n,r){let a=fo(i,"receipts"),o=Pl(await Hi({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 pm(t,e){let i=qe.join(J(t,e),"runtime","evidence","receipts");await F(t.nativeRoot,i);let n;try{n=await Ie.readdir(i,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return n.filter(r=>r.isFile()).map(r=>/^([a-f0-9]{64})\.json$/u.exec(r.name)?.[1]).filter(r=>r!==void 0).sort().map(r=>Zn("receipts",r))}var mm={"conflict-marker":0,"trailing-whitespace":1,"space-before-tab":2,"scope-mismatch":3,"unsafe-file":4,"binary-skipped":5,"scan-limit":6},te=class extends Error{constructor(i,n){super(n);this.kind=i}kind};function PC(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 vm(t){let e=PC(t.scope.baseline),[i,n]=await Promise.all([Xn({changeDir:J(t.paths,t.state.name),briefRef:t.state.brief,specChanges:t.state.spec_changes}),Rn(t.paths,e,{origin:"explicit"})]),r=zn({baseline:e,current:n,contractHash:t.scope.authority.contractHash,declaredArtifacts:t.scope.authority.declaredArtifacts,noCodeReason:t.scope.authority.noCodeReason,...t.scope.authority.gitChangedPaths?{gitChangedPaths:t.scope.authority.gitChangedPaths}:{}});return{contractHash:i.contract.contractHash,snapshotHash:r.scope.currentProjectionHash}}function gm(t,e){let i=(t??(()=>new Date))();if(!(i instanceof Date)||!Number.isFinite(i.getTime()))throw new Error(`Native check ${e} time is invalid`);return i.toISOString()}function AC(t,e,i){let n=[],r=i.scope.contractHash,a=i.scope.currentProjectionHash;return t.contractHash!==r&&n.push("contract-before-does-not-match-scope"),t.snapshotHash!==a&&n.push("implementation-before-does-not-match-scope"),e.contractHash!==t.contractHash&&n.push("contract-changed-during-check"),e.snapshotHash!==t.snapshotHash&&n.push("implementation-changed-during-check"),e.contractHash===t.contractHash&&e.contractHash!==r&&n.push("contract-after-does-not-match-scope"),e.snapshotHash===t.snapshotHash&&e.snapshotHash!==a&&n.push("implementation-after-does-not-match-scope"),n}function xC(t,e){return t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function ho(t,e){return t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size&&j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}async function TC(t,e){let i=si.resolve(t),n=si.resolve(e);if(!z(i,n))throw new te("unsafe-file","Scoped file parent escapes the project root");let r=[],a=i;for(let o of["",...si.relative(i,n).split(si.sep).filter(Boolean)]){o&&(a=si.join(a,o));let s;try{s=await Ve.lstat(a)}catch(l){throw l.code==="ENOENT"?new te("scope-mismatch","Scoped file parent no longer exists"):l}if(!s.isDirectory()||s.isSymbolicLink())throw new te("unsafe-file","Scoped file parent is not a real directory");let c=await Ve.realpath(a);if(r.length>0&&!z(r[0].realPath,c))throw new te("unsafe-file","Scoped file parent resolves outside the project");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs,ctimeMs:s.ctimeMs})}return{physicalRoot:r[0].realPath,chain:r}}async function wm(t){for(let e of t){let i;try{i=await Ve.lstat(e.path)}catch(n){throw n.code==="ENOENT"?new te("unsafe-file","Scoped file parent changed while reading"):n}if(!i.isDirectory()||i.isSymbolicLink()||!xC(e,i)||await Ve.realpath(e.path)!==e.realPath)throw new te("unsafe-file","Scoped file parent changed while reading")}}async function IC(t){let e=si.resolve(t.projectRoot,...t.file.path.split("/"));if(!z(t.projectRoot,e))throw new te("unsafe-file","Scoped file path escapes the project root");let{physicalRoot:i,chain:n}=await TC(t.projectRoot,si.dirname(e)),r;try{r=await Ve.lstat(e)}catch(c){throw c.code==="ENOENT"?new te("scope-mismatch","Scoped file no longer exists"):c}if(!r.isFile()||r.isSymbolicLink())throw new te("unsafe-file","Scoped file is not a real regular file");if(r.size!==t.file.expected.size)throw new te("scope-mismatch","Scoped file size no longer matches its projection");let a=await Ve.realpath(e);if(!z(i,a))throw new te("unsafe-file","Scoped file resolves outside the project root");let o=process.platform==="win32"?"r":Il.O_RDONLY|Il.O_NOFOLLOW|Il.O_NONBLOCK,s=await Ve.open(e,o).catch(c=>{throw c.code==="ENOENT"?new te("scope-mismatch","Scoped file no longer exists"):c.code==="ELOOP"||c.code==="ENXIO"?new te("unsafe-file","Scoped file became unsafe while opening"):c});try{let[c,l,f]=await Promise.all([s.stat(),Ve.lstat(e),Ve.realpath(e)]);if(await wm(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==a||!ho(r,c)||!ho(c,l))throw new te("unsafe-file","Scoped file changed while opening");let u=[],d=CC("sha256"),p=Buffer.allocUnsafe(64*1024),m=0;for(;;){let y=t.file.expected.size+1-m;if(y<1)throw new te("scope-mismatch","Scoped file exceeds its projected size");let w=await s.read(p,0,Math.min(p.length,y),null);if(w.bytesRead===0)break;if(m+=w.bytesRead,m>t.file.expected.size)throw new te("scope-mismatch","Scoped file exceeds its projected size");let E=Buffer.from(p.subarray(0,w.bytesRead));u.push(E),d.update(E)}let[h,v,b]=await Promise.all([s.stat(),Ve.lstat(e),Ve.realpath(e)]);if(await wm(n),m!==t.file.expected.size||d.digest("hex")!==t.file.expected.hash)throw new te("scope-mismatch","Scoped file content no longer matches its projection");if(!h.isFile()||!v.isFile()||v.isSymbolicLink()||b!==a||!z(i,b)||!ho(c,h)||!ho(c,v))throw new te("unsafe-file","Scoped file changed while reading");let N=Buffer.concat(u,m);if(N.includes(0))return{bytes:m,text:null};try{return{bytes:m,text:new RC("utf-8",{fatal:!0}).decode(N)}}catch{return{bytes:m,text:null}}}finally{await s.close()}}function _C(t){let e=new Map(t.current.entries.map(r=>[r.path,r])),i=[],n=[];for(let r of t.scope.changes){if(!r.after)continue;let a=e.get(r.path);if(!a||a.hash!==r.after.hash||a.size!==r.after.size||a.type!=="file"){n.push(r.path);continue}i.push({path:r.path,expected:r.after})}return i.sort((r,a)=>r.path.localeCompare(a.path,"en")),n.sort((r,a)=>r.localeCompare(a,"en")),{files:i,mismatches:n}}function OC(t,e,i){let n=e.split(`
|
|
174
|
+
`);for(let r=0;r<n.length;r+=1){let a=n[r].endsWith("\r")?n[r].slice(0,-1):n[r],o=r+1;/^(?:<{7}|={7}|>{7})(?: |$)/u.test(a)&&i({path:t,line:o,kind:"conflict-marker"}),/[ \t]+$/u.test(a)&&i({path:t,line:o,kind:"trailing-whitespace"}),/^ +\t/u.test(a)&&i({path:t,line:o,kind:"space-before-tab"})}}async function ym(t){if(!t.state.implementation_scope)throw new Error("Native scoped check requires an implementation scope");let e=await er(t.paths,t.state.name,t.state.implementation_scope),i=await vm({paths:t.paths,state:t.state,scope:e}),n=gm(t.clock,"start"),r=_C(e),a=[],o=0,s=y=>{o+=1,a.length<ae.maxIssues&&a.push(y)},c=r.files,l=r.files.length+r.mismatches.length;if(e.scope.unresolvedScopes.some(y=>y.kind==="scope-detail-overflow")){let y=e.scope.changes.at(-1)?.path??e.current.entries.at(-1)?.path??e.baseline.entries.at(-1)?.path;if(!y)throw new Error("Native implementation scope overflow has no bounded diagnostic path");s({path:y,line:1,kind:"scan-limit"}),c=[]}else if(l>ae.maxFiles){let y=[...r.files.map(w=>w.path),...r.mismatches].sort((w,E)=>w.localeCompare(E,"en"));s({path:y[ae.maxFiles],line:1,kind:"scan-limit"}),c=[]}else{let y=0;for(let w of r.files){if(w.expected.size>ae.maxFileBytes){s({path:w.path,line:1,kind:"scan-limit"}),c=[];break}if(y+=w.expected.size,y>ae.maxTotalBytes){s({path:w.path,line:1,kind:"scan-limit"}),c=[];break}}}for(let y of r.mismatches)s({path:y,line:1,kind:"scope-mismatch"});let u=0,d=0,p=0;for(let y of c)try{let w=await IC({projectRoot:t.paths.projectRoot,file:y});p+=w.bytes,w.text===null?(d+=1,s({path:y.path,line:1,kind:"binary-skipped"})):(u+=1,OC(y.path,w.text,s))}catch(w){if(!(w instanceof te))throw w;s({path:y.path,line:1,kind:w.kind})}let m=await vm({paths:t.paths,state:t.state,scope:e}),h=gm(t.clock,"end"),v=AC(i,m,e);a.sort((y,w)=>y.path.localeCompare(w.path,"en")||y.line-w.line||mm[y.kind]-mm[w.kind]);let b=zp({change:t.state.name,sourceRevision:t.state.revision,status:o===0&&v.length===0?"passed":"failed",startedAt:n,endedAt:h,contract:{expectedHash:e.scope.contractHash,beforeHash:i.contractHash,afterHash:m.contractHash},implementation:{scopeHash:e.scope.scopeHash,expectedSnapshotHash:e.scope.currentProjectionHash,beforeSnapshotHash:i.snapshotHash,afterSnapshotHash:m.snapshotHash},counts:{filesSelected:l,filesScanned:u,binaryFilesSkipped:d,bytesScanned:p,issueCount:o,recordedIssueCount:a.length},issues:a,issuesTruncated:o>a.length,stale:v.length>0,staleReasons:v}),N=await Up({paths:t.paths,name:t.state.name,receipt:b});return{receipt:ri(b),ref:N}}import{execFile as jC,spawn as VO}from"node:child_process";import{promisify as HC}from"node:util";var tr=class extends Error{recovery;constructor(e,i){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var rj=64*1024;var aj=3600*1e3;var oj=HC(jC);var sj=["$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("; ");async function Nm(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([er(t,e.name,e.implementation_scope),Xn({changeDir:J(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:Al(i.scope.declaredArtifacts)},acceptanceIds:n.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${r}`,implementationExecutionId:r,scope:i}}var $C=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function bm(t,e){let i=[];for(let n of $C){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}}function FC(t,e){return bm(t,e).ok}async function km(t){let e=await Nm(t.paths,t.state),i=t.checkReceipt.stale||t.checkReceipt.issues.some(o=>["scan-limit","scope-mismatch","unsafe-file","binary-skipped"].includes(o.kind)),n=t.checkReceipt.status==="passed"?"passed":i?"blocked":"failed",r=cm({kind:"static-inspection",role:"required-check",status:n,bindings:e.bindings,acceptanceIds:[],actor:`native-runtime:${t.checkReceipt.checker.policy}`,issuedAt:t.checkReceipt.endedAt,evidence:{subjects:e.scope.scope.changes.map(o=>o.path).sort(),rule:t.checkReceipt.checker.policy,resultSummary:n==="passed"?"The built-in scoped inspection passed without skipped or blocking input.":`The built-in scoped inspection recorded ${t.checkReceipt.counts.issueCount} blocking issue(s).`,checkReceiptRef:t.checkReceiptRef,checkReceiptHash:t.checkReceipt.receiptHash}}),a=await hm({paths:t.paths,name:t.state.name,receipt:r});return{receipt:r,ref:a}}function LC(t){let{receipt:e,checkReceipt:i,context:n}=t;if(e.kind!=="static-inspection"||e.role!=="required-check"||e.status!=="passed"||!FC(e,n.bindings)||i.status!=="passed"||i.stale)return!1;let r=n.scope.scope.changes.filter(o=>o.after!==null),a=r.reduce((o,s)=>o+s.after.size,0);return i.change===n.bindings.change&&i.sourceRevision===n.bindings.sourceRevision&&i.contract.expectedHash===n.bindings.contractHash&&i.contract.beforeHash===n.bindings.contractHash&&i.contract.afterHash===n.bindings.contractHash&&i.implementation.scopeHash===n.bindings.scopeHash&&i.implementation.expectedSnapshotHash===n.bindings.snapshotHash&&i.implementation.beforeSnapshotHash===n.bindings.snapshotHash&&i.implementation.afterSnapshotHash===n.bindings.snapshotHash&&i.counts.filesSelected===r.length&&i.counts.filesScanned+i.counts.binaryFilesSkipped===r.length&&i.counts.bytesScanned===a&&i.counts.issueCount===0&&i.counts.recordedIssueCount===0&&i.issues.length===0&&!i.issuesTruncated}async function Sm(t){let e=await pm(t.paths,t.state.name);if(e.length===0)return null;let i=[];for(let a of e)try{let o=await Tl(t.paths,t.state.name,a);o.kind==="static-inspection"&&o.role==="required-check"&&o.status==="passed"&&i.push({ref:a,receipt:o})}catch{}if(i.length===0)return null;let n;try{if(n=await Nm(t.paths,t.state),!(await qC({paths:t.paths,context:n})).matched)return null}catch{return null}let r=null;for(let{ref:a,receipt:o}of i)try{let s=await Em({paths:t.paths,state:t.state,receipt:o});if(s===null||!LC({receipt:o,checkReceipt:s,context:n}))continue;let c={receipt:o,ref:a,checkReceipt:s,checkReceiptRef:o.evidence.checkReceiptRef};(r===null||c.receipt.issuedAt>r.receipt.issuedAt||c.receipt.issuedAt===r.receipt.issuedAt&&c.ref>r.ref)&&(r=c)}catch{}return r}function MC(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 BC=20;function DC(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,f=c>=0?s:void 0;if(c<=0&&(r+=1),c>=0&&(a+=1),l&&f&&l.hash===f.hash&&l.size===f.size)continue;let u=l?.path??f?.path;u&&(n+=1,i.length<BC&&i.push({path:u,kind:l?f?"modified":"removed":"added"}))}return{changedPaths:i,changedPathCount:n,changedPathsTruncated:i.length!==n}}async function qC(t){let e=MC(t.context.scope.baseline),i=await Rn(t.paths,e,{origin:"explicit",now:t.now}),n=zn({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=DC(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 Em(t){if(t.receipt.kind!=="static-inspection")return null;let e=await so(t.paths,t.state.name,t.receipt.evidence.checkReceiptRef);if(e.receiptHash!==t.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return e}async function Cm(t){return Ue(t.paths,`check ${t.name}`,()=>Jn(t.paths,t.name,`check ${t.name}`,()=>VC(t)))}async function VC(t){await no(t.paths,t.name);let e=await xe(t.paths,t.name);if(e.phase!=="verify")throw new Error(`Native check requires Verify, got ${e.phase}`);if(!e.implementation_scope)throw new Error("Native check requires an implementation scope");let i=await Sm({paths:t.paths,state:e});if(i)return{change:e,receipt:i.checkReceipt,checkRef:i.checkReceiptRef,ref:i.ref};let n=await ym({paths:t.paths,state:e}),r=await km({paths:t.paths,state:e,checkReceipt:n.receipt,checkReceiptRef:n.ref});return{change:e,receipt:n.receipt,checkRef:n.ref,ref:r.ref}}import XC from"path";var zC=["Outcome","Scope","Non-goals","Acceptance examples"],xj=[...zC,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var JC=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 po=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 k0={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var _0=16*1024*1024,O0=256*1024,j0=16*1024;var F0=16*1024;var K0=16*1024;var HH=16*1024*1024,mo=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"},vo=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 zH=10*1024*1024,Ft=class extends Error{};function Rm(t,e){let i=t.flatMap((n,r)=>n===e?[r]:[]);if(i.length>1)throw new Ft(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function Pm(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new Ft(`${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 Ft(`${e} requires a value`);return t.splice(n,2),r}function Am(t){if(t.length>0)throw new Ft(`Unexpected argument: ${t[0]}`)}function xm(t,e){let i=t.shift();if(!i||i.startsWith("--"))throw new Ft(`${e} is required`);return i}async function Tm(t){return t?XC.resolve(t):va(process.cwd())}async function Im(t){let e=await $d({startPath:t,allowMissingConfig:!1});return{config:e.config,paths:e.paths}}function _m(t,e){if(e instanceof Ft)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof mo)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 vo)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof $n)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 Ma)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 Ba)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 po)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof tr)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 Om(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}})+`
|
|
175
|
+
`}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function jm(t,e){let i=xm(t,"change name");Am(t);let{paths:n}=await Im(e),r=await Cm({paths:n,name:i}),a={ref:r.ref,hash:r.receipt.receiptHash,status:r.receipt.status,checker:r.receipt.checker,counts:r.receipt.counts,issues:r.receipt.issues,issuesTruncated:r.receipt.issuesTruncated,stale:r.receipt.stale,staleReasons:r.receipt.staleReasons,startedAt:r.receipt.startedAt,endedAt:r.receipt.endedAt,sourceRevision:r.receipt.sourceRevision},o=r.receipt.status==="passed"&&!r.receipt.stale;return{command:"check",exitCode:o?0:1,data:a,text:`Native check ${o?"passed":"failed"}: ${r.ref}
|
|
176
|
+
`}}function QC(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}})+`
|
|
177
|
+
`}}async function Hm(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{Rm(r,"--json"),s=Pm(r,"--project-root");let f=[...r,...a],u=await Tm(s);c=await e(f,u)}catch(f){c=_m(t,f)}let l=o?QC(c):Om(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
|
|
172
178
|
`)?"":`
|
|
173
|
-
`)),l.exitCode}process.exitCode=await
|
|
179
|
+
`)),l.exitCode}process.exitCode=await Hm("check",jm);
|