@rpamis/comet 0.4.0-beta.12 → 0.4.0-beta.14
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/assets/manifest.json +15 -1
- package/assets/skills/comet/SKILL.md +5 -11
- package/assets/skills/comet/reference/comet-yaml-fields.md +1 -1
- package/assets/skills/comet/reference/context-recovery.md +3 -3
- package/assets/skills/comet/reference/decision-point.md +4 -5
- package/assets/skills/comet/reference/scripts.md +17 -47
- package/assets/skills/comet/reference/subagent-dispatch.md +8 -8
- package/assets/skills/comet/rules/comet-phase-guard.en.md +2 -2
- package/assets/skills/comet/rules/comet-phase-guard.md +2 -2
- package/assets/skills/comet/scripts/comet-archive.mjs +165 -2
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +146 -8071
- package/assets/skills/comet/scripts/comet-guard.mjs +207 -2
- package/assets/skills/comet/scripts/comet-handoff.mjs +165 -2
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +151 -2
- package/assets/skills/comet/scripts/comet-hook-router.mjs +155 -12101
- package/assets/skills/comet/scripts/comet-intent.mjs +10 -2
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +148 -2
- package/assets/skills/comet/scripts/comet-runtime.mjs +286 -19170
- package/assets/skills/comet/scripts/comet-state.mjs +164 -2
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +149 -2
- package/assets/skills/comet-archive/SKILL.md +1 -1
- package/assets/skills/comet-build/SKILL.md +13 -14
- package/assets/skills/comet-classic/SKILL.md +9 -9
- package/assets/skills/comet-design/SKILL.md +4 -4
- package/assets/skills/comet-hotfix/SKILL.md +2 -2
- package/assets/skills/comet-native/SKILL.md +17 -2
- package/assets/skills/comet-native/reference/commands.md +12 -0
- package/assets/skills/comet-native/reference/recovery.md +2 -0
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +178 -0
- package/assets/skills/comet-native/scripts/comet-native-check.mjs +173 -0
- package/assets/skills/comet-native/scripts/comet-native-checkpoint.mjs +179 -0
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +207 -0
- package/assets/skills/comet-native/scripts/comet-native-evidence.mjs +151 -0
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +150 -2
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +171 -0
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +200 -0
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +182 -0
- package/assets/skills/comet-native/scripts/comet-native-receipt.mjs +179 -0
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +185 -0
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +227 -31299
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +178 -0
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +151 -0
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +181 -0
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +175 -0
- package/assets/skills/comet-tweak/SKILL.md +2 -2
- package/assets/skills/comet-verify/SKILL.md +3 -3
- package/assets/skills-zh/comet/SKILL.md +5 -11
- package/assets/skills-zh/comet/reference/comet-yaml-fields.md +1 -1
- package/assets/skills-zh/comet/reference/context-recovery.md +3 -3
- package/assets/skills-zh/comet/reference/decision-point.md +4 -5
- package/assets/skills-zh/comet/reference/scripts.md +9 -39
- package/assets/skills-zh/comet/reference/subagent-dispatch.md +8 -8
- package/assets/skills-zh/comet-archive/SKILL.md +1 -1
- package/assets/skills-zh/comet-build/SKILL.md +13 -14
- package/assets/skills-zh/comet-classic/SKILL.md +7 -7
- package/assets/skills-zh/comet-design/SKILL.md +5 -5
- package/assets/skills-zh/comet-hotfix/SKILL.md +2 -2
- package/assets/skills-zh/comet-native/SKILL.md +17 -2
- package/assets/skills-zh/comet-native/reference/commands.md +12 -0
- package/assets/skills-zh/comet-native/reference/recovery.md +2 -0
- package/assets/skills-zh/comet-tweak/SKILL.md +2 -2
- package/assets/skills-zh/comet-verify/SKILL.md +3 -3
- package/bin/comet.js +5 -1
- package/bin/fast-runtime-router.js +82 -0
- package/dist/app/cli/index.js +57 -18
- package/dist/app/cli/index.js.map +1 -1
- package/dist/app/commands/dashboard.js +2 -2
- package/dist/app/commands/dashboard.js.map +1 -1
- package/dist/app/commands/i18n.d.ts +1 -1
- package/dist/app/commands/i18n.d.ts.map +1 -1
- package/dist/app/commands/i18n.js +100 -0
- package/dist/app/commands/i18n.js.map +1 -1
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +11 -5
- package/dist/app/commands/init.js.map +1 -1
- package/dist/app/commands/project-scope-selection.d.ts +2 -1
- package/dist/app/commands/project-scope-selection.d.ts.map +1 -1
- package/dist/app/commands/project-scope-selection.js +5 -7
- package/dist/app/commands/project-scope-selection.js.map +1 -1
- package/dist/app/commands/uninstall.d.ts +6 -0
- package/dist/app/commands/uninstall.d.ts.map +1 -1
- package/dist/app/commands/uninstall.js +298 -69
- package/dist/app/commands/uninstall.js.map +1 -1
- package/dist/app/commands/update.d.ts +1 -0
- package/dist/app/commands/update.d.ts.map +1 -1
- package/dist/app/commands/update.js +205 -25
- package/dist/app/commands/update.js.map +1 -1
- package/dist/config/repository-layout.json +33 -3
- package/dist/domains/comet-classic/classic-archive-entry.js +1 -1
- package/dist/domains/comet-classic/classic-archive-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-branch-binding.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-branch-binding.js +8 -2
- package/dist/domains/comet-classic/classic-branch-binding.js.map +1 -1
- package/dist/domains/comet-classic/classic-current-change.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-current-change.js +6 -1
- package/dist/domains/comet-classic/classic-current-change.js.map +1 -1
- package/dist/domains/comet-classic/classic-guard-entry.js +1 -1
- package/dist/domains/comet-classic/classic-guard-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-guard.js +1 -1
- package/dist/domains/comet-classic/classic-guard.js.map +1 -1
- package/dist/domains/comet-classic/classic-handoff-entry.js +1 -1
- package/dist/domains/comet-classic/classic-handoff-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard-entry.js +1 -1
- package/dist/domains/comet-classic/classic-hook-guard-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard.js +7 -4
- package/dist/domains/comet-classic/classic-hook-guard.js.map +1 -1
- package/dist/domains/comet-classic/classic-intent-entry.js +1 -1
- package/dist/domains/comet-classic/classic-intent-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.js +26 -15
- package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
- package/dist/domains/comet-classic/classic-layout.d.ts +7 -4
- package/dist/domains/comet-classic/classic-layout.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout.js +10 -9
- package/dist/domains/comet-classic/classic-layout.js.map +1 -1
- package/dist/domains/comet-classic/classic-resume-probe-entry.js +1 -1
- package/dist/domains/comet-classic/classic-resume-probe-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-script-entry.d.ts +2 -2
- package/dist/domains/comet-classic/classic-script-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-script-entry.js +4 -3
- package/dist/domains/comet-classic/classic-script-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.js +6 -6
- package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-state-entry.js +1 -1
- package/dist/domains/comet-classic/classic-state-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-validate-entry.js +1 -1
- package/dist/domains/comet-classic/classic-validate-entry.js.map +1 -1
- package/dist/domains/comet-entry/entry-reads.d.ts +17 -0
- package/dist/domains/comet-entry/entry-reads.d.ts.map +1 -0
- package/dist/domains/comet-entry/entry-reads.js +20 -0
- package/dist/domains/comet-entry/entry-reads.js.map +1 -0
- package/dist/domains/comet-entry/hook-router-entry.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-router-entry.js +3 -1
- package/dist/domains/comet-entry/hook-router-entry.js.map +1 -1
- package/dist/domains/comet-entry/hook-router.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-router.js +8 -3
- package/dist/domains/comet-entry/hook-router.js.map +1 -1
- package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
- package/dist/domains/comet-entry/init-workflow.js +9 -11
- package/dist/domains/comet-entry/init-workflow.js.map +1 -1
- package/dist/domains/comet-entry/resolve-entry.d.ts.map +1 -1
- package/dist/domains/comet-entry/resolve-entry.js +3 -4
- package/dist/domains/comet-entry/resolve-entry.js.map +1 -1
- package/dist/domains/comet-entry/resume-probe.d.ts.map +1 -1
- package/dist/domains/comet-entry/resume-probe.js +16 -5
- package/dist/domains/comet-entry/resume-probe.js.map +1 -1
- package/dist/domains/comet-native/native-archive-command.d.ts +3 -0
- package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-archive-command.js +49 -0
- package/dist/domains/comet-native/native-archive-command.js.map +1 -0
- package/dist/domains/comet-native/native-archive-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-archive-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-archive-entry.js +4 -0
- package/dist/domains/comet-native/native-archive-entry.js.map +1 -0
- package/dist/domains/comet-native/native-check-command.d.ts +3 -0
- package/dist/domains/comet-native/native-check-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-check-command.js +30 -0
- package/dist/domains/comet-native/native-check-command.js.map +1 -0
- package/dist/domains/comet-native/native-check-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-check-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-check-entry.js +4 -0
- package/dist/domains/comet-native/native-check-entry.js.map +1 -0
- package/dist/domains/comet-native/native-checkpoint-command.d.ts +3 -0
- package/dist/domains/comet-native/native-checkpoint-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-checkpoint-command.js +39 -0
- package/dist/domains/comet-native/native-checkpoint-command.js.map +1 -0
- package/dist/domains/comet-native/native-checkpoint-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-checkpoint-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-checkpoint-entry.js +4 -0
- package/dist/domains/comet-native/native-checkpoint-entry.js.map +1 -0
- package/dist/domains/comet-native/native-cli-shared.d.ts +40 -0
- package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -0
- package/dist/domains/comet-native/native-cli-shared.js +272 -0
- package/dist/domains/comet-native/native-cli-shared.js.map +1 -0
- package/dist/domains/comet-native/native-cli.d.ts +2 -5
- package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli.js +37 -785
- package/dist/domains/comet-native/native-cli.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-doctor-command.d.ts +3 -0
- package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-doctor-command.js +29 -0
- package/dist/domains/comet-native/native-doctor-command.js.map +1 -0
- package/dist/domains/comet-native/native-doctor-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-doctor-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-doctor-entry.js +4 -0
- package/dist/domains/comet-native/native-doctor-entry.js.map +1 -0
- package/dist/domains/comet-native/native-evidence-command.d.ts +3 -0
- package/dist/domains/comet-native/native-evidence-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-evidence-command.js +35 -0
- package/dist/domains/comet-native/native-evidence-command.js.map +1 -0
- package/dist/domains/comet-native/native-evidence-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-evidence-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-evidence-entry.js +4 -0
- package/dist/domains/comet-native/native-evidence-entry.js.map +1 -0
- package/dist/domains/comet-native/native-evidence-storage.d.ts +17 -6
- package/dist/domains/comet-native/native-evidence-storage.d.ts.map +1 -1
- package/dist/domains/comet-native/native-evidence-storage.js +89 -23
- 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 +18 -0
- package/dist/domains/comet-native/native-findings.js.map +1 -1
- package/dist/domains/comet-native/native-hook-guard-command.d.ts +3 -0
- package/dist/domains/comet-native/native-hook-guard-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-hook-guard-command.js +32 -0
- package/dist/domains/comet-native/native-hook-guard-command.js.map +1 -0
- package/dist/domains/comet-native/native-hook-guard-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-hook-guard-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-hook-guard-entry.js +4 -0
- package/dist/domains/comet-native/native-hook-guard-entry.js.map +1 -0
- package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
- package/dist/domains/comet-native/native-hook-guard.js +7 -1
- package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
- package/dist/domains/comet-native/native-init-command.d.ts +3 -0
- package/dist/domains/comet-native/native-init-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-init-command.js +29 -0
- package/dist/domains/comet-native/native-init-command.js.map +1 -0
- package/dist/domains/comet-native/native-init-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-init-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-init-entry.js +4 -0
- package/dist/domains/comet-native/native-init-entry.js.map +1 -0
- package/dist/domains/comet-native/native-new-command.d.ts +3 -0
- package/dist/domains/comet-native/native-new-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-new-command.js +35 -0
- package/dist/domains/comet-native/native-new-command.js.map +1 -0
- package/dist/domains/comet-native/native-new-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-new-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-new-entry.js +4 -0
- package/dist/domains/comet-native/native-new-entry.js.map +1 -0
- package/dist/domains/comet-native/native-next-command.d.ts +3 -0
- package/dist/domains/comet-native/native-next-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-next-command.js +82 -0
- package/dist/domains/comet-native/native-next-command.js.map +1 -0
- package/dist/domains/comet-native/native-next-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-next-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-next-entry.js +4 -0
- package/dist/domains/comet-native/native-next-entry.js.map +1 -0
- package/dist/domains/comet-native/native-receipt-command.d.ts +3 -0
- package/dist/domains/comet-native/native-receipt-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-receipt-command.js +107 -0
- package/dist/domains/comet-native/native-receipt-command.js.map +1 -0
- package/dist/domains/comet-native/native-receipt-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-receipt-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-receipt-entry.js +4 -0
- package/dist/domains/comet-native/native-receipt-entry.js.map +1 -0
- package/dist/domains/comet-native/native-receipt-refresh.d.ts +86 -0
- package/dist/domains/comet-native/native-receipt-refresh.d.ts.map +1 -0
- package/dist/domains/comet-native/native-receipt-refresh.js +232 -0
- package/dist/domains/comet-native/native-receipt-refresh.js.map +1 -0
- package/dist/domains/comet-native/native-root-command.d.ts +3 -0
- package/dist/domains/comet-native/native-root-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-root-command.js +29 -0
- package/dist/domains/comet-native/native-root-command.js.map +1 -0
- package/dist/domains/comet-native/native-root-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-root-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-root-entry.js +4 -0
- package/dist/domains/comet-native/native-root-entry.js.map +1 -0
- package/dist/domains/comet-native/native-script-entry.d.ts +12 -0
- package/dist/domains/comet-native/native-script-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-script-entry.js +44 -0
- package/dist/domains/comet-native/native-script-entry.js.map +1 -0
- package/dist/domains/comet-native/native-select-command.d.ts +3 -0
- package/dist/domains/comet-native/native-select-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-select-command.js +15 -0
- package/dist/domains/comet-native/native-select-command.js.map +1 -0
- package/dist/domains/comet-native/native-select-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-select-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-select-entry.js +4 -0
- package/dist/domains/comet-native/native-select-entry.js.map +1 -0
- package/dist/domains/comet-native/native-show-command.d.ts +3 -0
- package/dist/domains/comet-native/native-show-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-show-command.js +41 -0
- package/dist/domains/comet-native/native-show-command.js.map +1 -0
- package/dist/domains/comet-native/native-show-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-show-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-show-entry.js +4 -0
- package/dist/domains/comet-native/native-show-entry.js.map +1 -0
- package/dist/domains/comet-native/native-snapshot.d.ts +9 -0
- package/dist/domains/comet-native/native-snapshot.d.ts.map +1 -1
- package/dist/domains/comet-native/native-snapshot.js +141 -5
- package/dist/domains/comet-native/native-snapshot.js.map +1 -1
- package/dist/domains/comet-native/native-spec-command.d.ts +3 -0
- package/dist/domains/comet-native/native-spec-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-spec-command.js +34 -0
- package/dist/domains/comet-native/native-spec-command.js.map +1 -0
- package/dist/domains/comet-native/native-spec-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-spec-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-spec-entry.js +4 -0
- package/dist/domains/comet-native/native-spec-entry.js.map +1 -0
- package/dist/domains/comet-native/native-status-command.d.ts +3 -0
- package/dist/domains/comet-native/native-status-command.d.ts.map +1 -0
- package/dist/domains/comet-native/native-status-command.js +36 -0
- package/dist/domains/comet-native/native-status-command.js.map +1 -0
- package/dist/domains/comet-native/native-status-entry.d.ts +2 -0
- package/dist/domains/comet-native/native-status-entry.d.ts.map +1 -0
- package/dist/domains/comet-native/native-status-entry.js +4 -0
- package/dist/domains/comet-native/native-status-entry.js.map +1 -0
- package/dist/domains/comet-native/native-transitions.d.ts +4 -0
- package/dist/domains/comet-native/native-transitions.d.ts.map +1 -1
- package/dist/domains/comet-native/native-transitions.js +28 -4
- package/dist/domains/comet-native/native-transitions.js.map +1 -1
- package/dist/domains/comet-native/native-types.d.ts +8 -0
- package/dist/domains/comet-native/native-types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts +14 -0
- package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-verification-receipt-runtime.js +29 -1
- package/dist/domains/comet-native/native-verification-receipt-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-verification-runtime.d.ts +28 -1
- package/dist/domains/comet-native/native-verification-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-verification-runtime.js +92 -14
- package/dist/domains/comet-native/native-verification-runtime.js.map +1 -1
- package/dist/domains/dashboard/collector.d.ts.map +1 -1
- package/dist/domains/dashboard/collector.js +53 -41
- package/dist/domains/dashboard/collector.js.map +1 -1
- package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
- package/dist/domains/dashboard/native-collector.js +13 -3
- package/dist/domains/dashboard/native-collector.js.map +1 -1
- package/dist/domains/dashboard/project-directory.d.ts +20 -0
- package/dist/domains/dashboard/project-directory.d.ts.map +1 -0
- package/dist/domains/dashboard/project-directory.js +87 -0
- package/dist/domains/dashboard/project-directory.js.map +1 -0
- package/dist/domains/dashboard/project-root.d.ts +8 -0
- package/dist/domains/dashboard/project-root.d.ts.map +1 -0
- package/dist/domains/dashboard/project-root.js +68 -0
- package/dist/domains/dashboard/project-root.js.map +1 -0
- package/dist/domains/dashboard/server.d.ts +1 -0
- package/dist/domains/dashboard/server.d.ts.map +1 -1
- package/dist/domains/dashboard/server.js +50 -10
- package/dist/domains/dashboard/server.js.map +1 -1
- package/dist/domains/dashboard/web/assets/{arc-BXDAG6Qx.js → arc-mNt_SS1l.js} +1 -1
- package/dist/domains/dashboard/web/assets/architectureDiagram-3BPJPVTR-Bc5akVD6.js +36 -0
- package/dist/domains/dashboard/web/assets/{blockDiagram-GPEHLZMM-STNPWdDl.js → blockDiagram-GPEHLZMM-C43zhVBe.js} +2 -2
- package/dist/domains/dashboard/web/assets/{c4Diagram-AAUBKEIU-Bh-rUIcJ.js → c4Diagram-AAUBKEIU-dToETarK.js} +2 -2
- package/dist/domains/dashboard/web/assets/channel-b2wWDG4F.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-2J33WTMH-BRhFNAFH.js → chunk-2J33WTMH-C0oO137R.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-4BX2VUAB-CwA3zkFS.js → chunk-4BX2VUAB-CGms1fgI.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-55IACEB6-C1tqAl_E.js → chunk-55IACEB6-Bugl8v6f.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-727SXJPM-DDefBoUS.js → chunk-727SXJPM-8ATNMlBG.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-AQP2D5EJ-Dq-0Yi9D.js → chunk-AQP2D5EJ-BNYjSSqU.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-FMBD7UC4-DC-MVNgk.js → chunk-FMBD7UC4-_nJAqSbe.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-ND2GUHAM-BLWZ8zWd.js → chunk-ND2GUHAM-lyxYm5NX.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-QZHKN3VN-DaK5rvZu.js → chunk-QZHKN3VN-PUMVeWpd.js} +1 -1
- package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-B9SWZywo.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-B9SWZywo.js +1 -0
- package/dist/domains/dashboard/web/assets/cose-bilkent-S5V4N54A-DzMqjexn.js +1 -0
- package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-CBaY4KFj.js → cynefin-VYW2F7L2-B67ET0eq.js} +1 -1
- package/dist/domains/dashboard/web/assets/dagre-BM42HDAG-CQPMvRLK.js +4 -0
- package/dist/domains/dashboard/web/assets/diagram-2AECGRRQ-BRpLrFHM.js +43 -0
- package/dist/domains/dashboard/web/assets/diagram-5GNKFQAL-CPGWuGrE.js +10 -0
- package/dist/domains/dashboard/web/assets/{diagram-KO2AKTUF-BZcengGf.js → diagram-KO2AKTUF-D2wpX2iO.js} +2 -2
- package/dist/domains/dashboard/web/assets/diagram-LMA3HP47-D54mAbDu.js +24 -0
- package/dist/domains/dashboard/web/assets/diagram-OG6HWLK6-ZGQDpSs_.js +24 -0
- package/dist/domains/dashboard/web/assets/{erDiagram-TEJ5UH35-BBrwULhs.js → erDiagram-TEJ5UH35-C3qDo7sd.js} +2 -2
- package/dist/domains/dashboard/web/assets/{flowDiagram-I6XJVG4X-DiNn0Yzp.js → flowDiagram-I6XJVG4X-B7hStPd9.js} +2 -2
- package/dist/domains/dashboard/web/assets/ganttDiagram-6RSMTGT7-IqcLFbTK.js +292 -0
- package/dist/domains/dashboard/web/assets/gitGraphDiagram-PVQCEYII-YrMZpzUu.js +106 -0
- package/dist/domains/dashboard/web/assets/index-DhtBssCt.js +257 -0
- package/dist/domains/dashboard/web/assets/{index-QO0z6F4w.js → index-icxk8_BP.js} +1 -1
- package/dist/domains/dashboard/web/assets/index-pr3axVDI.css +1 -0
- package/dist/domains/dashboard/web/assets/infoDiagram-5YYISTIA-CcIgGK_7.js +2 -0
- package/dist/domains/dashboard/web/assets/{ishikawaDiagram-YF4QCWOH-DCPPspol.js → ishikawaDiagram-YF4QCWOH-1x3rNjGP.js} +2 -2
- package/dist/domains/dashboard/web/assets/{journeyDiagram-JHISSGLW-C_v8b1Os.js → journeyDiagram-JHISSGLW-B2XiqMNP.js} +2 -2
- package/dist/domains/dashboard/web/assets/{kanban-definition-UN3LZRKU-CgpE9lG7.js → kanban-definition-UN3LZRKU-x46cGuo3.js} +2 -2
- package/dist/domains/dashboard/web/assets/{linear-jSddcREx.js → linear-DFLqGZWl.js} +1 -1
- package/dist/domains/dashboard/web/assets/{mermaid.core-5Ibr28Ig.js → mermaid.core-g3J6BACc.js} +69 -69
- package/dist/domains/dashboard/web/assets/{mindmap-definition-RKZ34NQL-XPCohX0x.js → mindmap-definition-RKZ34NQL-CTdeKmcX.js} +2 -2
- package/dist/domains/dashboard/web/assets/{pieDiagram-4H26LBE5-DvhxgQWl.js → pieDiagram-4H26LBE5-C_obwjIf.js} +2 -2
- package/dist/domains/dashboard/web/assets/{quadrantDiagram-W4KKPZXB-CCUxdF-S.js → quadrantDiagram-W4KKPZXB-B6Gnfz9M.js} +4 -4
- package/dist/domains/dashboard/web/assets/{requirementDiagram-4Y6WPE33-FS3TCmdX.js → requirementDiagram-4Y6WPE33-nX4PObnB.js} +2 -2
- package/dist/domains/dashboard/web/assets/{sankeyDiagram-5OEKKPKP-r129rscN.js → sankeyDiagram-5OEKKPKP-QjDwwHgl.js} +2 -2
- package/dist/domains/dashboard/web/assets/{sequenceDiagram-3UESZ5HK--DCY0bvU.js → sequenceDiagram-3UESZ5HK-BEEe0j6B.js} +2 -2
- package/dist/domains/dashboard/web/assets/stateDiagram-AJRCARHV-CXfAaBgM.js +1 -0
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-CD3nS4cC.js +1 -0
- package/dist/domains/dashboard/web/assets/{timeline-definition-PNZ67QCA-NlqCuFuo.js → timeline-definition-PNZ67QCA-BOzX2EnD.js} +2 -2
- package/dist/domains/dashboard/web/assets/{vennDiagram-CIIHVFJN-B4W_d1Nq.js → vennDiagram-CIIHVFJN-C40vhXRq.js} +2 -2
- package/dist/domains/dashboard/web/assets/{wardleyDiagram-YWT4CUSO-Bex-_jWd.js → wardleyDiagram-YWT4CUSO-B1rm89JH.js} +2 -2
- package/dist/domains/dashboard/web/assets/{xychartDiagram-2RQKCTM6-CmxeVM2Z.js → xychartDiagram-2RQKCTM6-BlMr59qK.js} +2 -2
- package/dist/domains/dashboard/web/index.html +2 -2
- package/dist/domains/integrations/openspec.d.ts +1 -0
- package/dist/domains/integrations/openspec.d.ts.map +1 -1
- package/dist/domains/integrations/openspec.js +11 -2
- package/dist/domains/integrations/openspec.js.map +1 -1
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +36 -6
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/domains/skill/uninstall.d.ts +10 -2
- package/dist/domains/skill/uninstall.d.ts.map +1 -1
- package/dist/domains/skill/uninstall.js +256 -23
- package/dist/domains/skill/uninstall.js.map +1 -1
- package/dist/domains/workflow-contract/contained-atomic-write.d.ts +3 -0
- package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
- package/dist/domains/workflow-contract/contained-atomic-write.js +15 -2
- package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
- package/dist/domains/workflow-contract/index.d.ts +1 -1
- package/dist/domains/workflow-contract/index.d.ts.map +1 -1
- package/dist/domains/workflow-contract/index.js +1 -1
- package/dist/domains/workflow-contract/index.js.map +1 -1
- package/dist/domains/workflow-contract/project-config-reader.d.ts +2 -0
- package/dist/domains/workflow-contract/project-config-reader.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config-reader.js.map +1 -1
- package/dist/domains/workflow-contract/project-config-writer.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config-writer.js +3 -2
- package/dist/domains/workflow-contract/project-config-writer.js.map +1 -1
- package/dist/domains/workflow-contract/project-config.d.ts +2 -0
- package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config.js +54 -5
- package/dist/domains/workflow-contract/project-config.js.map +1 -1
- package/dist/platform/install/detect.d.ts +1 -0
- package/dist/platform/install/detect.d.ts.map +1 -1
- package/dist/platform/install/detect.js +2 -0
- package/dist/platform/install/detect.js.map +1 -1
- package/dist/platform/install/platforms.d.ts +2 -0
- package/dist/platform/install/platforms.d.ts.map +1 -1
- package/dist/platform/install/platforms.js +1 -0
- package/dist/platform/install/platforms.js.map +1 -1
- package/dist/platform/process/hook-read-cache.d.ts +45 -0
- package/dist/platform/process/hook-read-cache.d.ts.map +1 -0
- package/dist/platform/process/hook-read-cache.js +102 -0
- package/dist/platform/process/hook-read-cache.js.map +1 -0
- package/dist/platform/version/version.d.ts.map +1 -1
- package/dist/platform/version/version.js +9 -2
- package/dist/platform/version/version.js.map +1 -1
- package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +2 -0
- package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +2 -0
- package/eval/local/tasks/comet-native-workflow/instruction.md +3 -3
- package/eval/local/tasks/comet-native-workflow/task.toml +4 -2
- package/eval/local/tasks/comet-native-workflow/validation/test_native_workflow.py +212 -75
- package/eval/local/tests/scaffold/test_native_wave_evaluations.py +114 -39
- package/eval/local/tests/scaffold/test_tasks.py +5 -1
- package/package.json +7 -3
- package/dist/domains/dashboard/web/assets/_commonjsHelpers-CqkleIqs.js +0 -1
- package/dist/domains/dashboard/web/assets/architectureDiagram-3BPJPVTR-R2JyCv0i.js +0 -36
- package/dist/domains/dashboard/web/assets/channel-XR_5gd6D.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-CG_TnucZ.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-CG_TnucZ.js +0 -1
- package/dist/domains/dashboard/web/assets/cose-bilkent-S5V4N54A-DCPgAyMU.js +0 -1
- package/dist/domains/dashboard/web/assets/dagre-BM42HDAG-CLKQ6BQM.js +0 -4
- package/dist/domains/dashboard/web/assets/diagram-2AECGRRQ-DCup336F.js +0 -43
- package/dist/domains/dashboard/web/assets/diagram-5GNKFQAL-DgpDOFTE.js +0 -10
- package/dist/domains/dashboard/web/assets/diagram-LMA3HP47-DSECilBo.js +0 -24
- package/dist/domains/dashboard/web/assets/diagram-OG6HWLK6-3FuzANXW.js +0 -24
- package/dist/domains/dashboard/web/assets/ganttDiagram-6RSMTGT7-DcvbTHnu.js +0 -292
- package/dist/domains/dashboard/web/assets/gitGraphDiagram-PVQCEYII-CgCY3MJo.js +0 -106
- package/dist/domains/dashboard/web/assets/index-BR3wUr2k.css +0 -1
- package/dist/domains/dashboard/web/assets/index-CovQUq5W.js +0 -24
- package/dist/domains/dashboard/web/assets/infoDiagram-5YYISTIA-hzBGAEue.js +0 -2
- package/dist/domains/dashboard/web/assets/stateDiagram-AJRCARHV-yHkUByrT.js +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-XHzDdqcm.js +0 -1
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
|
+
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
+
var Lg=Object.create;var Ou=Object.defineProperty;var Mg=Object.getOwnPropertyDescriptor;var Dg=Object.getOwnPropertyNames;var Fg=Object.getPrototypeOf,Bg=Object.prototype.hasOwnProperty;var Mr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var qg=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Dg(t))!Bg.call(e,r)&&r!==i&&Ou(e,r,{get:()=>t[r],enumerable:!(n=Mg(t,r))||n.enumerable});return e};var ju=(e,t,i)=>(i=e!=null?Lg(Fg(e)):{},qg(t||!e||!e.__esModule?Ou(i,"default",{value:e,enumerable:!0}):i,e));var L=R(le=>{"use strict";var Yo=Symbol.for("yaml.alias"),Fu=Symbol.for("yaml.document"),Dr=Symbol.for("yaml.map"),Bu=Symbol.for("yaml.pair"),Xo=Symbol.for("yaml.scalar"),Fr=Symbol.for("yaml.seq"),dt=Symbol.for("yaml.node.type"),Jg=e=>!!e&&typeof e=="object"&&e[dt]===Yo,Ug=e=>!!e&&typeof e=="object"&&e[dt]===Fu,Kg=e=>!!e&&typeof e=="object"&&e[dt]===Dr,Gg=e=>!!e&&typeof e=="object"&&e[dt]===Bu,qu=e=>!!e&&typeof e=="object"&&e[dt]===Xo,Yg=e=>!!e&&typeof e=="object"&&e[dt]===Fr;function Vu(e){if(e&&typeof e=="object")switch(e[dt]){case Dr:case Fr:return!0}return!1}function Xg(e){if(e&&typeof e=="object")switch(e[dt]){case Yo:case Dr:case Xo:case Fr:return!0}return!1}var Qg=e=>(qu(e)||Vu(e))&&!!e.anchor;le.ALIAS=Yo;le.DOC=Fu;le.MAP=Dr;le.NODE_TYPE=dt;le.PAIR=Bu;le.SCALAR=Xo;le.SEQ=Fr;le.hasAnchor=Qg;le.isAlias=Jg;le.isCollection=Vu;le.isDocument=Ug;le.isMap=Kg;le.isNode=Xg;le.isPair=Gg;le.isScalar=qu;le.isSeq=Yg});var vn=R(Qo=>{"use strict";var ae=L(),Ne=Symbol("break visit"),zu=Symbol("skip children"),nt=Symbol("remove node");function Br(e,t){let i=Wu(t);ae.isDocument(e)?Pi(null,e.contents,i,Object.freeze([e]))===nt&&(e.contents=null):Pi(null,e,i,Object.freeze([]))}Br.BREAK=Ne;Br.SKIP=zu;Br.REMOVE=nt;function Pi(e,t,i,n){let r=Ju(e,t,i,n);if(ae.isNode(r)||ae.isPair(r))return Uu(e,n,r),Pi(e,r,i,n);if(typeof r!="symbol"){if(ae.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=Pi(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===Ne)return Ne;o===nt&&(t.items.splice(a,1),a-=1)}}}else if(ae.isPair(t)){n=Object.freeze(n.concat(t));let a=Pi("key",t.key,i,n);if(a===Ne)return Ne;a===nt&&(t.key=null);let o=Pi("value",t.value,i,n);if(o===Ne)return Ne;o===nt&&(t.value=null)}}return r}async function qr(e,t){let i=Wu(t);ae.isDocument(e)?await Ai(null,e.contents,i,Object.freeze([e]))===nt&&(e.contents=null):await Ai(null,e,i,Object.freeze([]))}qr.BREAK=Ne;qr.SKIP=zu;qr.REMOVE=nt;async function Ai(e,t,i,n){let r=await Ju(e,t,i,n);if(ae.isNode(r)||ae.isPair(r))return Uu(e,n,r),Ai(e,r,i,n);if(typeof r!="symbol"){if(ae.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=await Ai(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===Ne)return Ne;o===nt&&(t.items.splice(a,1),a-=1)}}}else if(ae.isPair(t)){n=Object.freeze(n.concat(t));let a=await Ai("key",t.key,i,n);if(a===Ne)return Ne;a===nt&&(t.key=null);let o=await Ai("value",t.value,i,n);if(o===Ne)return Ne;o===nt&&(t.value=null)}}return r}function Wu(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Ju(e,t,i,n){if(typeof i=="function")return i(e,t,n);if(ae.isMap(t))return i.Map?.(e,t,n);if(ae.isSeq(t))return i.Seq?.(e,t,n);if(ae.isPair(t))return i.Pair?.(e,t,n);if(ae.isScalar(t))return i.Scalar?.(e,t,n);if(ae.isAlias(t))return i.Alias?.(e,t,n)}function Uu(e,t,i){let n=t[t.length-1];if(ae.isCollection(n))n.items[e]=i;else if(ae.isPair(n))e==="key"?n.key=i:n.value=i;else if(ae.isDocument(n))n.contents=i;else{let r=ae.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}Qo.visit=Br;Qo.visitAsync=qr});var Zo=R(Gu=>{"use strict";var Ku=L(),Zg=vn(),ew={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},tw=e=>e.replace(/[!,[\]{}]/g,t=>ew[t]),gn=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let n=t.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(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,n,r]=t.match(/^(.*!)([^!]*)$/s);r||i(`The ${t} 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==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,n]of Object.entries(this.tags))if(t.startsWith(n))return i+tw(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),r;if(t&&n.length>0&&Ku.isNode(t.contents)){let a={};Zg.visit(t.contents,(o,s)=>{Ku.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:"||(!t||r.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
|
|
5
|
+
`)}};gn.defaultYaml={explicit:!1,version:"1.2"};gn.defaultTags={"!!":"tag:yaml.org,2002:"};Gu.Directives=gn});var Vr=R(wn=>{"use strict";var Yu=L(),iw=vn();function nw(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function Xu(e){let t=new Set;return iw.visit(e,{Value(i,n){n.anchor&&t.add(n.anchor)}}),t}function Qu(e,t){for(let i=1;;++i){let n=`${e}${i}`;if(!t.has(n))return n}}function rw(e,t){let i=[],n=new Map,r=null;return{onAnchor:a=>{i.push(a),r??(r=Xu(e));let o=Qu(t,r);return r.add(o),o},setAnchors:()=>{for(let a of i){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(Yu.isScalar(o.node)||Yu.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}}wn.anchorIsValid=nw;wn.anchorNames=Xu;wn.createNodeAnchors=rw;wn.findNewAnchor=Qu});var es=R(Zu=>{"use strict";function yn(e,t,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=yn(e,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=yn(e,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=yn(e,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=yn(e,n,r,a);o===void 0?delete n[r]:o!==a&&(n[r]=o)}return e.call(t,i,n)}Zu.applyReviver=yn});var xt=R(tf=>{"use strict";var aw=L();function ef(e,t,i){if(Array.isArray(e))return e.map((n,r)=>ef(n,String(r),i));if(e&&typeof e.toJSON=="function"){if(!i||!aw.hasAnchor(e))return e.toJSON(t,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=a=>{n.res=a,delete i.onCreate};let r=e.toJSON(t,i);return i.onCreate&&i.onCreate(r),r}return typeof e=="bigint"&&!i?.keep?Number(e):e}tf.toJS=ef});var zr=R(rf=>{"use strict";var ow=es(),nf=L(),sw=xt(),ts=class{constructor(t){Object.defineProperty(this,nf.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:n,onAnchor:r,reviver:a}={}){if(!nf.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},s=sw.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof a=="function"?ow.applyReviver(a,{"":s},"",s):s}};rf.NodeBase=ts});var Nn=R(af=>{"use strict";var cw=Vr(),lw=vn(),xi=L(),uw=zr(),fw=xt(),is=class extends uw.NodeBase{constructor(t){super(xi.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;i?.aliasResolveCache?n=i.aliasResolveCache:(n=[],lw.visit(t,{Node:(a,o)=>{(xi.isAlias(o)||xi.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(t,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||(fw.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=Wr(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(t,i,n){let r=`*${this.source}`;if(t){if(cw.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${r} `}return r}};function Wr(e,t,i){if(xi.isAlias(t)){let n=t.resolve(e),r=i&&n&&i.get(n);return r?r.count*r.aliasCount:0}else if(xi.isCollection(t)){let n=0;for(let r of t.items){let a=Wr(e,r,i);a>n&&(n=a)}return n}else if(xi.isPair(t)){let n=Wr(e,t.key,i),r=Wr(e,t.value,i);return Math.max(n,r)}return 1}af.Alias=is});var te=R(ns=>{"use strict";var dw=L(),hw=zr(),pw=xt(),mw=e=>!e||typeof e!="function"&&typeof e!="object",Tt=class extends hw.NodeBase{constructor(t){super(dw.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:pw.toJS(this.value,t,i)}toString(){return String(this.value)}};Tt.BLOCK_FOLDED="BLOCK_FOLDED";Tt.BLOCK_LITERAL="BLOCK_LITERAL";Tt.PLAIN="PLAIN";Tt.QUOTE_DOUBLE="QUOTE_DOUBLE";Tt.QUOTE_SINGLE="QUOTE_SINGLE";ns.Scalar=Tt;ns.isScalarValue=mw});var bn=R(sf=>{"use strict";var vw=Nn(),ni=L(),of=te(),gw="tag:yaml.org,2002:";function ww(e,t,i){if(t){let n=i.filter(a=>a.tag===t),r=n.find(a=>!a.format)??n[0];if(!r)throw new Error(`Tag ${t} not found`);return r}return i.find(n=>n.identify?.(e)&&!n.format)}function yw(e,t,i){if(ni.isDocument(e)&&(e=e.contents),ni.isNode(e))return e;if(ni.isPair(e)){let u=i.schema[ni.MAP].createNode?.(i.schema,null,i);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:n,onAnchor:r,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(n&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=r(e)),new vw.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=gw+t.slice(2));let l=ww(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new of.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[ni.MAP]:Symbol.iterator in Object(e)?o[ni.SEQ]:o[ni.MAP]}a&&(a(l),delete i.onTagObj);let f=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new of.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}sf.createNode=yw});var Ur=R(Jr=>{"use strict";var Nw=bn(),rt=L(),bw=zr();function rs(e,t,i){let n=i;for(let r=t.length-1;r>=0;--r){let a=t[r];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=n,n=o}else n=new Map([[a,n]])}return Nw.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var cf=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,as=class extends bw.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(n=>rt.isNode(n)||rt.isPair(n)?n.clone(t):n),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(cf(t))this.add(i);else{let[n,...r]=t,a=this.get(n,!0);if(rt.isCollection(a))a.addIn(r,i);else if(a===void 0&&this.schema)this.set(n,rs(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(t){let[i,...n]=t;if(n.length===0)return this.delete(i);let r=this.get(i,!0);if(rt.isCollection(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}getIn(t,i){let[n,...r]=t,a=this.get(n,!0);return r.length===0?!i&&rt.isScalar(a)?a.value:a:rt.isCollection(a)?a.getIn(r,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!rt.isPair(i))return!1;let n=i.value;return n==null||t&&rt.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[i,...n]=t;if(n.length===0)return this.has(i);let r=this.get(i,!0);return rt.isCollection(r)?r.hasIn(n):!1}setIn(t,i){let[n,...r]=t;if(r.length===0)this.set(n,i);else{let a=this.get(n,!0);if(rt.isCollection(a))a.setIn(r,i);else if(a===void 0&&this.schema)this.set(n,rs(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};Jr.Collection=as;Jr.collectionFromPath=rs;Jr.isEmptyPath=cf});var Sn=R(Kr=>{"use strict";var Sw=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function os(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var kw=(e,t,i)=>e.endsWith(`
|
|
6
|
+
`)?os(i,t):i.includes(`
|
|
7
|
+
`)?`
|
|
8
|
+
`+os(i,t):(e.endsWith(" ")?"":" ")+i;Kr.indentComment=os;Kr.lineComment=kw;Kr.stringifyComment=Sw});var uf=R(kn=>{"use strict";var Ew="flow",ss="block",Gr="quoted";function Cw(e,t,i="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!r||r<0)return e;r<a&&(a=0);let c=Math.max(1+a,1+r-t.length);if(e.length<=c)return e;let l=[],f={},u=r-t.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,w=-1;i===ss&&(h=lf(e,h,t.length),h!==-1&&(u=h+c));for(let N;N=e[h+=1];){if(i===Gr&&N==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(N===`
|
|
9
|
+
`)i===ss&&(h=lf(e,h,t.length)),u=h+t.length+c,d=void 0;else{if(N===" "&&p&&p!==" "&&p!==`
|
|
10
|
+
`&&p!==" "){let y=e[h+1];y&&y!==" "&&y!==`
|
|
11
|
+
`&&y!==" "&&(d=h)}if(h>=u)if(d)l.push(d),u=d+c,d=void 0;else if(i===Gr){for(;p===" "||p===" ";)p=N,N=e[h+=1],m=!0;let y=h>w+1?h-2:v-1;if(f[y])return e;l.push(y),f[y]=!0,u=y+c,d=void 0}else m=!0}p=N}if(m&&s&&s(),l.length===0)return e;o&&o();let S=e.slice(0,l[0]);for(let N=0;N<l.length;++N){let y=l[N],E=l[N+1]||e.length;y===0?S=`
|
|
12
|
+
${t}${e.slice(0,E)}`:(i===Gr&&f[y]&&(S+=`${e[y]}\\`),S+=`
|
|
13
|
+
${t}${e.slice(y+1,E)}`)}return S}function lf(e,t,i){let n=t,r=t+1,a=e[r];for(;a===" "||a===" ";)if(t<r+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
+
`);n=t,r=t+1,a=e[r]}return n}kn.FOLD_BLOCK=ss;kn.FOLD_FLOW=Ew;kn.FOLD_QUOTED=Gr;kn.foldFlowLines=Cw});var Cn=R(ff=>{"use strict";var ze=te(),It=uf(),Xr=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Qr=e=>/^(%|---|\.\.\.)/m.test(e);function Rw(e,t,i){if(!t||t<0)return!1;let n=t-i,r=e.length;if(r<=n)return!1;for(let a=0,o=0;a<r;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>n)return!0;if(o=a+1,r-o<=n)return!1}return!0}function En(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:n}=t,r=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Qr(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let 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
|
+
|
|
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:It.foldFlowLines(o,a,It.FOLD_QUOTED,Xr(t,!1))}function cs(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return En(e,t);let i=t.indent||(Qr(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return t.implicitKey?n:It.foldFlowLines(n,i,It.FOLD_FLOW,Xr(t,!1))}function Ti(e,t){let{singleQuote:i}=t.options,n;if(i===!1)n=En;else{let r=e.includes('"'),a=e.includes("'");r&&!a?n=cs:a&&!r?n=En:n=i?cs:En}return n(e,t)}var ls;try{ls=new RegExp(`(^|(?<!
|
|
21
|
+
))
|
|
22
|
+
+(?!
|
|
23
|
+
|$)`,"g")}catch{ls=/\n+(?!\n|$)/g}function Yr({comment:e,type:t,value:i},n,r,a){let{blockQuote:o,commentString:s,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(i))return Ti(i,n);let l=n.indent||(n.forceBlockIndent||Qr(i)?" ":""),f=o==="literal"?!0:o==="folded"||t===ze.Scalar.BLOCK_FOLDED?!1:t===ze.Scalar.BLOCK_LITERAL?!0:!Rw(i,c,l.length);if(!i)return f?`|
|
|
24
|
+
`:`>
|
|
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
|
+
`);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(ls,`$&${l}`));let h=!1,v,w=-1;for(v=0;v<i.length;++v){let E=i[v];if(E===" ")h=!0;else if(E===`
|
|
29
|
+
`)w=v;else break}let S=i.substring(0,w<v?w+1:v);S&&(i=i.substring(S.length),S=S.replace(/\n+/g,`$&${l}`));let y=(h?l?"2":"1":"")+u;if(e&&(y+=" "+s(e.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,k=Xr(n,!0);o!=="folded"&&t!==ze.Scalar.BLOCK_FOLDED&&(k.onOverflow=()=>{g=!0});let b=It.foldFlowLines(`${S}${E}${p}`,l,It.FOLD_BLOCK,k);if(!g)return`>${y}
|
|
31
|
+
${l}${b}`}return i=i.replace(/\n+/g,`$&${l}`),`|${y}
|
|
32
|
+
${l}${S}${i}${p}`}function Pw(e,t,i,n){let{type:r,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(`
|
|
33
|
+
`)||f&&/[[\]{},]/.test(a))return Ti(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
|
|
34
|
+
`)?Ti(a,t):Yr(e,t,i,n);if(!s&&!f&&r!==ze.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return Yr(e,t,i,n);if(Qr(a)){if(c==="")return t.forceBlockIndent=!0,Yr(e,t,i,n);if(s&&c===l)return Ti(a,t)}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}=t.doc.schema;if(m.some(d)||p?.some(d))return Ti(a,t)}return s?u:It.foldFlowLines(u,c,It.FOLD_FLOW,Xr(t,!1))}function Aw(e,t,i,n){let{implicitKey:r,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==ze.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=ze.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case ze.Scalar.BLOCK_FOLDED:case ze.Scalar.BLOCK_LITERAL:return r||a?Ti(o.value,t):Yr(o,t,i,n);case ze.Scalar.QUOTE_DOUBLE:return En(o.value,t);case ze.Scalar.QUOTE_SINGLE:return cs(o.value,t);case ze.Scalar.PLAIN:return Pw(o,t,i,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:u}=t.options,d=r&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}ff.stringifyString=Aw});var Rn=R(us=>{"use strict";var xw=Vr(),_t=L(),Tw=Sn(),Iw=Cn();function _w(e,t){let i=Object.assign({blockQuote:!0,commentString:Tw.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),n;switch(i.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:n,options:i}}function Ow(e,t){if(t.tag){let r=e.filter(a=>a.tag===t.tag);if(r.length>0)return r.find(a=>a.format===t.format)??r[0]}let i,n;if(_t.isScalar(t)){n=t.value;let r=e.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===t.format)??r.find(a=>!a.format)}else n=t,i=e.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 jw(e,t,{anchors:i,doc:n}){if(!n.directives)return"";let r=[],a=(_t.isScalar(e)||_t.isCollection(e))&&e.anchor;a&&xw.anchorIsValid(a)&&(i.add(a),r.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}function $w(e,t,i,n){if(_t.isPair(e))return e.toString(t,i,n);if(_t.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let r,a=_t.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>r=c});r??(r=Ow(t.doc.schema.tags,a));let o=jw(a,r,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof r.stringify=="function"?r.stringify(a,t,i,n):_t.isScalar(a)?Iw.stringifyString(a,t,i,n):a.toString(t,i,n);return o?_t.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}us.createStringifyContext=_w;us.stringify=$w});var mf=R(pf=>{"use strict";var ht=L(),df=te(),hf=Rn(),Pn=Sn();function Hw({key:e,value:t},i,n,r){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=i,d=ht.isNode(e)&&e.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(ht.isCollection(e)||!ht.isNode(e)&&typeof e=="object"){let k="With simple keys, collection cannot be used as a key value";throw new Error(k)}}let p=!u&&(!e||d&&t==null&&!i.inFlow||ht.isCollection(e)||(ht.isScalar(e)?e.type===df.Scalar.BLOCK_FOLDED||e.type===df.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(u||!a),indent:s+c});let m=!1,h=!1,v=hf.stringify(e,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||t==null)return m&&n&&n(),v===""?"?":p?`? ${v}`:v}else if(a&&!u||t==null&&p)return v=`? ${v}`,d&&!m?v+=Pn.lineComment(v,i.indent,l(d)):h&&r&&r(),v;m&&(d=null),p?(d&&(v+=Pn.lineComment(v,i.indent,l(d))),v=`? ${v}
|
|
38
|
+
${s}:`):(v=`${v}:`,d&&(v+=Pn.lineComment(v,i.indent,l(d))));let w,S,N;ht.isNode(t)?(w=!!t.spaceBefore,S=t.commentBefore,N=t.comment):(w=!1,S=null,N=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!d&&ht.isScalar(t)&&(i.indentAtStart=v.length+1),h=!1,!f&&c.length>=2&&!i.inFlow&&!p&&ht.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let y=!1,E=hf.stringify(t,i,()=>y=!0,()=>h=!0),g=" ";if(d||w||S){if(g=w?`
|
|
39
|
+
`:"",S){let k=l(S);g+=`
|
|
40
|
+
${Pn.indentComment(k,i.indent)}`}E===""&&!i.inFlow?g===`
|
|
41
|
+
`&&N&&(g=`
|
|
42
|
+
|
|
43
|
+
`):g+=`
|
|
44
|
+
${i.indent}`}else if(!p&&ht.isCollection(t)){let k=E[0],b=E.indexOf(`
|
|
45
|
+
`),C=b!==-1,B=i.inFlow??t.flow??t.items.length===0;if(C||!B){let Y=!1;if(C&&(k==="&"||k==="!")){let F=E.indexOf(" ");k==="&"&&F!==-1&&F<b&&E[F+1]==="!"&&(F=E.indexOf(" ",F+1)),(F===-1||b<F)&&(Y=!0)}Y||(g=`
|
|
46
|
+
${i.indent}`)}}else(E===""||E[0]===`
|
|
47
|
+
`)&&(g="");return v+=g+E,i.inFlow?y&&n&&n():N&&!y?v+=Pn.lineComment(v,i.indent,l(N)):h&&r&&r(),v}pf.stringifyPair=Hw});var ds=R(fs=>{"use strict";var vf=Mr("process");function Lw(e,...t){e==="debug"&&console.log(...t)}function Mw(e,t){(e==="debug"||e==="warn")&&(typeof vf.emitWarning=="function"?vf.emitWarning(t):console.warn(t))}fs.debug=Lw;fs.warn=Mw});var na=R(ia=>{"use strict";var ta=L(),gf=te(),Zr="<<",ea={identify:e=>e===Zr||typeof e=="symbol"&&e.description===Zr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new gf.Scalar(Symbol(Zr)),{addToJSMap:wf}),stringify:()=>Zr},Dw=(e,t)=>(ea.identify(t)||ta.isScalar(t)&&(!t.type||t.type===gf.Scalar.PLAIN)&&ea.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===ea.tag&&i.default);function wf(e,t,i){let n=yf(e,i);if(ta.isSeq(n))for(let r of n.items)hs(e,t,r);else if(Array.isArray(n))for(let r of n)hs(e,t,r);else hs(e,t,n)}function hs(e,t,i){let n=yf(e,i);if(!ta.isMap(n))throw new Error("Merge sources must be maps or map aliases");let r=n.toJSON(null,e,Map);for(let[a,o]of r)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function yf(e,t){return e&&ta.isAlias(t)?t.resolve(e.doc,e):t}ia.addMergeToJSMap=wf;ia.isMergeKey=Dw;ia.merge=ea});var ms=R(Sf=>{"use strict";var Fw=ds(),Nf=na(),Bw=Rn(),bf=L(),ps=xt();function qw(e,t,{key:i,value:n}){if(bf.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,n);else if(Nf.isMergeKey(e,i))Nf.addMergeToJSMap(e,t,n);else{let r=ps.toJS(i,"",e);if(t instanceof Map)t.set(r,ps.toJS(n,r,e));else if(t instanceof Set)t.add(r);else{let a=Vw(i,r,e),o=ps.toJS(n,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Vw(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(bf.isNode(e)&&i?.doc){let n=Bw.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=e.toString(n);if(!i.mapKeyWarned){let a=JSON.stringify(r);a.length>40&&(a=a.substring(0,36)+'..."'),Fw.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(t)}Sf.addPairToJSMap=qw});var Ot=R(vs=>{"use strict";var kf=bn(),zw=mf(),Ww=ms(),ra=L();function Jw(e,t,i){let n=kf.createNode(e,void 0,i),r=kf.createNode(t,void 0,i);return new aa(n,r)}var aa=class e{constructor(t,i=null){Object.defineProperty(this,ra.NODE_TYPE,{value:ra.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:n}=this;return ra.isNode(i)&&(i=i.clone(t)),ra.isNode(n)&&(n=n.clone(t)),new e(i,n)}toJSON(t,i){let n=i?.mapAsMap?new Map:{};return Ww.addPairToJSMap(i,n,this)}toString(t,i,n){return t?.doc?zw.stringifyPair(this,t,i,n):JSON.stringify(this)}};vs.Pair=aa;vs.createPair=Jw});var gs=R(Cf=>{"use strict";var ri=L(),Ef=Rn(),oa=Sn();function Uw(e,t,i){return(t.inFlow??e.flow?Gw:Kw)(e,t,i)}function Kw({comment:e,items:t},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<t.length;++m){let h=t[m],v=null;if(ri.isNode(h))!u&&h.spaceBefore&&d.push(""),sa(i,d,h.commentBefore,u),h.comment&&(v=h.comment);else if(ri.isPair(h)){let S=ri.isNode(h.key)?h.key:null;S&&(!u&&S.spaceBefore&&d.push(""),sa(i,d,S.commentBefore,u))}u=!1;let w=Ef.stringify(h,f,()=>v=null,()=>u=!0);v&&(w+=oa.lineComment(w,a,l(v))),u&&v&&(u=!1),d.push(n+w)}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
|
+
${c}${h}`:`
|
|
49
|
+
`}}return e?(p+=`
|
|
50
|
+
`+oa.indentComment(l(e),c),s&&s()):u&&o&&o(),p}function Gw({items:e},t,{flowChars:i,itemIndent:n}){let{indent:r,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;n+=a;let c=Object.assign({},t,{indent:n,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(ri.isNode(h))h.spaceBefore&&u.push(""),sa(t,u,h.commentBefore,!1),h.comment&&(v=h.comment);else if(ri.isPair(h)){let S=ri.isNode(h.key)?h.key:null;S&&(S.spaceBefore&&u.push(""),sa(t,u,S.commentBefore,!1),S.comment&&(l=!0));let N=ri.isNode(h.value)?h.value:null;N?(N.comment&&(v=N.comment),N.commentBefore&&(l=!0)):h.value==null&&S?.comment&&(v=S.comment)}v&&(l=!0);let w=Ef.stringify(h,c,()=>v=null);l||(l=u.length>f||w.includes(`
|
|
51
|
+
`)),m<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=u.reduce((S,N)=>S+N.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),v&&(w+=oa.lineComment(w,n,s(v))),u.push(w),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=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=d;for(let h of u)m+=h?`
|
|
52
|
+
${a}${r}${h}`:`
|
|
53
|
+
`;return`${m}
|
|
54
|
+
${r}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function sa({indent:e,options:{commentString:t}},i,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let a=oa.indentComment(t(n),e);i.push(a.trimStart())}}Cf.stringifyCollection=Uw});var $t=R(ys=>{"use strict";var Yw=gs(),Xw=ms(),Qw=Ur(),jt=L(),ca=Ot(),Zw=te();function An(e,t){let i=jt.isScalar(t)?t.value:t;for(let n of e)if(jt.isPair(n)&&(n.key===t||n.key===i||jt.isScalar(n.key)&&n.key.value===i))return n}var ws=class extends Qw.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(jt.MAP,t),this.items=[]}static from(t,i,n){let{keepUndefined:r,replacer:a}=n,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||r)&&o.items.push(ca.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 t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let n;jt.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new ca.Pair(t,t?.value):n=new ca.Pair(t.key,t.value);let r=An(this.items,n.key),a=this.schema?.sortMapEntries;if(r){if(!i)throw new Error(`Key ${n.key} already set`);jt.isScalar(r.value)&&Zw.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(t){let i=An(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let r=An(this.items,t)?.value;return(!i&&jt.isScalar(r)?r.value:r)??void 0}has(t){return!!An(this.items,t)}set(t,i){this.add(new ca.Pair(t,i),!0)}toJSON(t,i,n){let r=n?new n:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(r);for(let a of this.items)Xw.addPairToJSMap(i,r,a);return r}toString(t,i,n){if(!t)return JSON.stringify(this);for(let r of this.items)if(!jt.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Yw.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:i})}};ys.YAMLMap=ws;ys.findPair=An});var Ii=R(Pf=>{"use strict";var ey=L(),Rf=$t(),ty={collection:"map",default:!0,nodeClass:Rf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return ey.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Rf.YAMLMap.from(e,t,i)};Pf.map=ty});var Ht=R(Af=>{"use strict";var iy=bn(),ny=gs(),ry=Ur(),ua=L(),ay=te(),oy=xt(),Ns=class extends ry.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(ua.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=la(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let n=la(t);if(typeof n!="number")return;let r=this.items[n];return!i&&ua.isScalar(r)?r.value:r}has(t){let i=la(t);return typeof i=="number"&&i<this.items.length}set(t,i){let n=la(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let r=this.items[n];ua.isScalar(r)&&ay.isScalarValue(i)?r.value=i:this.items[n]=i}toJSON(t,i){let n=[];i?.onCreate&&i.onCreate(n);let r=0;for(let a of this.items)n.push(oy.toJS(a,String(r++),i));return n}toString(t,i,n){return t?ny.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:n,onComment:i}):JSON.stringify(this)}static from(t,i,n){let{replacer:r}=n,a=new this(t);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(iy.createNode(s,void 0,n))}}return a}};function la(e){let t=ua.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Af.YAMLSeq=Ns});var _i=R(Tf=>{"use strict";var sy=L(),xf=Ht(),cy={collection:"seq",default:!0,nodeClass:xf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return sy.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>xf.YAMLSeq.from(e,t,i)};Tf.seq=cy});var xn=R(If=>{"use strict";var ly=Cn(),uy={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,n){return t=Object.assign({actualString:!0},t),ly.stringifyString(e,t,i,n)}};If.string=uy});var fa=R(jf=>{"use strict";var _f=te(),Of={identify:e=>e==null,createNode:()=>new _f.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new _f.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Of.test.test(e)?e:t.options.nullStr};jf.nullTag=Of});var bs=R(Hf=>{"use strict";var fy=te(),$f={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new fy.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&$f.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?i.options.trueStr:i.options.falseStr}};Hf.boolTag=$f});var Oi=R(Lf=>{"use strict";function dy({format:e,minFractionDigits:t,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(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Lf.stringifyNumber=dy});var ks=R(da=>{"use strict";var hy=te(),Ss=Oi(),py={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ss.stringifyNumber},my={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Ss.stringifyNumber(e)}},vy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new hy.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Ss.stringifyNumber};da.float=vy;da.floatExp=my;da.floatNaN=py});var Cs=R(pa=>{"use strict";var Mf=Oi(),ha=e=>typeof e=="bigint"||Number.isInteger(e),Es=(e,t,i,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),i);function Df(e,t,i){let{value:n}=e;return ha(n)&&n>=0?i+n.toString(t):Mf.stringifyNumber(e)}var gy={identify:e=>ha(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Es(e,2,8,i),stringify:e=>Df(e,8,"0o")},wy={identify:ha,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Es(e,0,10,i),stringify:Mf.stringifyNumber},yy={identify:e=>ha(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Es(e,2,16,i),stringify:e=>Df(e,16,"0x")};pa.int=wy;pa.intHex=yy;pa.intOct=gy});var Bf=R(Ff=>{"use strict";var Ny=Ii(),by=fa(),Sy=_i(),ky=xn(),Ey=bs(),Rs=ks(),Ps=Cs(),Cy=[Ny.map,Sy.seq,ky.string,by.nullTag,Ey.boolTag,Ps.intOct,Ps.int,Ps.intHex,Rs.floatNaN,Rs.floatExp,Rs.float];Ff.schema=Cy});var zf=R(Vf=>{"use strict";var Ry=te(),Py=Ii(),Ay=_i();function qf(e){return typeof e=="bigint"||Number.isInteger(e)}var ma=({value:e})=>JSON.stringify(e),xy=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ma},{identify:e=>e==null,createNode:()=>new Ry.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ma},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ma},{identify:qf,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>qf(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:ma}],Ty={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Iy=[Py.map,Ay.seq].concat(xy,Ty);Vf.schema=Iy});var xs=R(Wf=>{"use strict";var Tn=Mr("buffer"),As=te(),_y=Cn(),Oy={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Tn.Buffer=="function")return Tn.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.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 t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},n,r,a){if(!i)return"";let o=i,s;if(typeof Tn.Buffer=="function")s=o instanceof Tn.Buffer?o.toString("base64"):Tn.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=As.Scalar.BLOCK_LITERAL),t!==As.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(t===As.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return _y.stringifyString({comment:e,type:t,value:s},n,r,a)}};Wf.binary=Oy});var wa=R(ga=>{"use strict";var va=L(),Ts=Ot(),jy=te(),$y=Ht();function Jf(e,t){if(va.isSeq(e))for(let i=0;i<e.items.length;++i){let n=e.items[i];if(!va.isPair(n)){if(va.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let r=n.items[0]||new Ts.Pair(new jy.Scalar(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
|
|
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}e.items[i]=va.isPair(n)?n:new Ts.Pair(n)}}else t("Expected a sequence for this tag");return e}function Uf(e,t,i){let{replacer:n}=i,r=new $y.YAMLSeq(e);r.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof n=="function"&&(o=n.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;r.items.push(Ts.createPair(s,c,i))}return r}var Hy={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Jf,createNode:Uf};ga.createPairs=Uf;ga.pairs=Hy;ga.resolvePairs=Jf});var Os=R(_s=>{"use strict";var Kf=L(),Is=xt(),In=$t(),Ly=Ht(),Gf=wa(),ai=class e extends Ly.YAMLSeq{constructor(){super(),this.add=In.YAMLMap.prototype.add.bind(this),this.delete=In.YAMLMap.prototype.delete.bind(this),this.get=In.YAMLMap.prototype.get.bind(this),this.has=In.YAMLMap.prototype.has.bind(this),this.set=In.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let n=new Map;i?.onCreate&&i.onCreate(n);for(let r of this.items){let a,o;if(Kf.isPair(r)?(a=Is.toJS(r.key,"",i),o=Is.toJS(r.value,a,i)):a=Is.toJS(r,"",i),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(t,i,n){let r=Gf.createPairs(t,i,n),a=new this;return a.items=r.items,a}};ai.tag="tag:yaml.org,2002:omap";var My={collection:"seq",identify:e=>e instanceof Map,nodeClass:ai,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Gf.resolvePairs(e,t),n=[];for(let{key:r}of i.items)Kf.isScalar(r)&&(n.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new ai,i)},createNode:(e,t,i)=>ai.from(e,t,i)};_s.YAMLOMap=ai;_s.omap=My});var ed=R(js=>{"use strict";var Yf=te();function Xf({value:e,source:t},i){return t&&(e?Qf:Zf).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Qf={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Yf.Scalar(!0),stringify:Xf},Zf={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Yf.Scalar(!1),stringify:Xf};js.falseTag=Zf;js.trueTag=Qf});var td=R(ya=>{"use strict";var Dy=te(),$s=Oi(),Fy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:$s.stringifyNumber},By={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():$s.stringifyNumber(e)}},qy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Dy.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let n=e.substring(i+1).replace(/_/g,"");n[n.length-1]==="0"&&(t.minFractionDigits=n.length)}return t},stringify:$s.stringifyNumber};ya.float=qy;ya.floatExp=By;ya.floatNaN=Fy});var nd=R(On=>{"use strict";var id=Oi(),_n=e=>typeof e=="bigint"||Number.isInteger(e);function Na(e,t,i,{intAsBigInt:n}){let r=e[0];if((r==="-"||r==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return r==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return r==="-"?-1*a:a}function Hs(e,t,i){let{value:n}=e;if(_n(n)){let r=n.toString(t);return n<0?"-"+i+r.substr(1):i+r}return id.stringifyNumber(e)}var Vy={identify:_n,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Na(e,2,2,i),stringify:e=>Hs(e,2,"0b")},zy={identify:_n,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Na(e,1,8,i),stringify:e=>Hs(e,8,"0")},Wy={identify:_n,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Na(e,0,10,i),stringify:id.stringifyNumber},Jy={identify:_n,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Na(e,2,16,i),stringify:e=>Hs(e,16,"0x")};On.int=Wy;On.intBin=Vy;On.intHex=Jy;On.intOct=zy});var Ms=R(Ls=>{"use strict";var ka=L(),ba=Ot(),Sa=$t(),oi=class e extends Sa.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;ka.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new ba.Pair(t.key,null):i=new ba.Pair(t,null),Sa.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let n=Sa.findPair(this.items,t);return!i&&ka.isPair(n)?ka.isScalar(n.key)?n.key.value:n.key:n}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let n=Sa.findPair(this.items,t);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new ba.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,n);throw new Error("Set items must all have null values")}static from(t,i,n){let{replacer:r}=n,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof r=="function"&&(o=r.call(i,o,o)),a.items.push(ba.createPair(o,null,n));return a}};oi.tag="tag:yaml.org,2002:set";var Uy={collection:"map",identify:e=>e instanceof Set,nodeClass:oi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>oi.from(e,t,i),resolve(e,t){if(ka.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new oi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Ls.YAMLSet=oi;Ls.set=Uy});var Fs=R(Ea=>{"use strict";var Ky=Oi();function Ds(e,t){let i=e[0],n=i==="-"||i==="+"?e.substring(1):e,r=o=>t?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 rd(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Ky.stringifyNumber(e);let n="";t<0&&(n="-",t*=i(-1));let r=i(60),a=[t%r];return t<60?a.unshift(0):(t=(t-a[0])/r,a.unshift(t%r),t>=60&&(t=(t-a[0])/r,a.unshift(t))),n+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Gy={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>Ds(e,i),stringify:rd},Yy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Ds(e,!1),stringify:rd},ad={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(ad.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,n,r,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,n-1,r,a||0,o||0,s||0,c),f=t[8];if(f&&f!=="Z"){let u=Ds(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Ea.floatTime=Yy;Ea.intTime=Gy;Ea.timestamp=ad});var cd=R(sd=>{"use strict";var Xy=Ii(),Qy=fa(),Zy=_i(),eN=xn(),tN=xs(),od=ed(),Bs=td(),Ca=nd(),iN=na(),nN=Os(),rN=wa(),aN=Ms(),qs=Fs(),oN=[Xy.map,Zy.seq,eN.string,Qy.nullTag,od.trueTag,od.falseTag,Ca.intBin,Ca.intOct,Ca.int,Ca.intHex,Bs.floatNaN,Bs.floatExp,Bs.float,tN.binary,iN.merge,nN.omap,rN.pairs,aN.set,qs.intTime,qs.floatTime,qs.timestamp];sd.schema=oN});var wd=R(Ws=>{"use strict";var dd=Ii(),sN=fa(),hd=_i(),cN=xn(),lN=bs(),Vs=ks(),zs=Cs(),uN=Bf(),fN=zf(),pd=xs(),jn=na(),md=Os(),vd=wa(),ld=cd(),gd=Ms(),Ra=Fs(),ud=new Map([["core",uN.schema],["failsafe",[dd.map,hd.seq,cN.string]],["json",fN.schema],["yaml11",ld.schema],["yaml-1.1",ld.schema]]),fd={binary:pd.binary,bool:lN.boolTag,float:Vs.float,floatExp:Vs.floatExp,floatNaN:Vs.floatNaN,floatTime:Ra.floatTime,int:zs.int,intHex:zs.intHex,intOct:zs.intOct,intTime:Ra.intTime,map:dd.map,merge:jn.merge,null:sN.nullTag,omap:md.omap,pairs:vd.pairs,seq:hd.seq,set:gd.set,timestamp:Ra.timestamp},dN={"tag:yaml.org,2002:binary":pd.binary,"tag:yaml.org,2002:merge":jn.merge,"tag:yaml.org,2002:omap":md.omap,"tag:yaml.org,2002:pairs":vd.pairs,"tag:yaml.org,2002:set":gd.set,"tag:yaml.org,2002:timestamp":Ra.timestamp};function hN(e,t,i){let n=ud.get(t);if(n&&!e)return i&&!n.includes(jn.merge)?n.concat(jn.merge):n.slice();let r=n;if(!r)if(Array.isArray(e))r=[];else{let a=Array.from(ud.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)r=r.concat(a);else typeof e=="function"&&(r=e(r.slice()));return i&&(r=r.concat(jn.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?fd[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(fd).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},[])}Ws.coreKnownTags=dN;Ws.getTags=hN});var Ks=R(yd=>{"use strict";var Js=L(),pN=Ii(),mN=_i(),vN=xn(),Pa=wd(),gN=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Us=class e{constructor({compat:t,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Pa.getTags(t,"compat"):t?Pa.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?Pa.coreKnownTags:{},this.tags=Pa.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,Js.MAP,{value:pN.map}),Object.defineProperty(this,Js.SCALAR,{value:vN.string}),Object.defineProperty(this,Js.SEQ,{value:mN.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?gN:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};yd.Schema=Us});var bd=R(Nd=>{"use strict";var wN=L(),Gs=Rn(),$n=Sn();function yN(e,t){let i=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),n=!0):e.directives.docStart&&(n=!0)}n&&i.push("---");let r=Gs.createStringifyContext(e,t),{commentString:a}=r.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift($n.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(wN.isNode(e.contents)){if(e.contents.spaceBefore&&n&&i.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);i.push($n.indentComment(f,""))}r.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Gs.stringify(e.contents,r,()=>s=null,c);s&&(l+=$n.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Gs.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
+
`)?(i.push("..."),i.push($n.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push($n.indentComment(a(c),"")))}return i.join(`
|
|
59
|
+
`)+`
|
|
60
|
+
`}Nd.stringifyDocument=yN});var Hn=R(Sd=>{"use strict";var NN=Nn(),ji=Ur(),He=L(),bN=Ot(),SN=xt(),kN=Ks(),EN=bd(),Ys=Vr(),CN=es(),RN=bn(),Xs=Zo(),Qs=class e{constructor(t,i,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,He.NODE_TYPE,{value:He.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 Xs.Directives({version:o}),this.setSchema(o,n),this.contents=t===void 0?null:this.createNode(t,r,n)}clone(){let t=Object.create(e.prototype,{[He.NODE_TYPE]:{value:He.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=He.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){$i(this.contents)&&this.contents.add(t)}addIn(t,i){$i(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let n=Ys.anchorNames(this);t.anchor=!i||n.has(i)?Ys.findNewAnchor(i||"a",n):i}return new NN.Alias(t.anchor)}createNode(t,i,n){let r;if(typeof i=="function")t=i.call({"":t},"",t),r=i;else if(Array.isArray(i)){let v=S=>typeof S=="number"||S instanceof String||S instanceof Number,w=i.filter(v).map(String);w.length>0&&(i=i.concat(w)),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=RN.createNode(t,f,m);return s&&He.isCollection(h)&&(h.flow=!0),d(),h}createPair(t,i,n={}){let r=this.createNode(t,null,n),a=this.createNode(i,null,n);return new bN.Pair(r,a)}delete(t){return $i(this.contents)?this.contents.delete(t):!1}deleteIn(t){return ji.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):$i(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return He.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return ji.isEmptyPath(t)?!i&&He.isScalar(this.contents)?this.contents.value:this.contents:He.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return He.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return ji.isEmptyPath(t)?this.contents!==void 0:He.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=ji.collectionFromPath(this.schema,[t],i):$i(this.contents)&&this.contents.set(t,i)}setIn(t,i){ji.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=ji.collectionFromPath(this.schema,Array.from(t),i):$i(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let n;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Xs.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Xs.Directives({version:t}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let r=JSON.stringify(t);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 kN.Schema(Object.assign(n,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:n,maxAliasCount:r,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=SN.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"?CN.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return EN.stringifyDocument(this,t)}};function $i(e){if(He.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Sd.Document=Qs});var Dn=R(Mn=>{"use strict";var Ln=class extends Error{constructor(t,i,n,r){super(),this.name=t,this.code=n,this.message=r,this.pos=i}},Zs=class extends Ln{constructor(t,i,n){super("YAMLParseError",t,i,n)}},ec=class extends Ln{constructor(t,i,n){super("YAMLWarning",t,i,n)}},PN=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:n,col:r}=i.linePos[0];i.message+=` at line ${n}, column ${r}`;let a=r-1,o=e.substring(t.lineStarts[n-1],t.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=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
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
|
+
|
|
63
|
+
${o}
|
|
64
|
+
${l}
|
|
65
|
+
`}};Mn.YAMLError=Ln;Mn.YAMLParseError=Zs;Mn.YAMLWarning=ec;Mn.prettifyError=PN});var Fn=R(kd=>{"use strict";function AN(e,{flow:t,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,w=null,S=null,N=null,y=null,E=null;for(let b of e)switch(m&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&b.type!=="comment"&&b.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!t&&(i!=="doc-start"||n?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),f=!0;break;case"comment":{f||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let C=b.source.substring(1)||" ";u?u+=d+C:u=C,d="",l=!1;break}case"newline":l?u?u+=b.source:(!y||i!=="seq-item-ind")&&(c=!0):d+=b.source,l=!0,p=!0,(v||w)&&(S=b),f=!0;break;case"anchor":v&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=b,E??(E=b.offset),l=!1,f=!1,m=!0;break;case"tag":{w&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),w=b,E??(E=b.offset),l=!1,f=!1,m=!0;break}case i:(v||w)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),y&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),y=b,l=i==="seq-item-ind"||i==="explicit-key-ind",f=!1;break;case"comma":if(t){N&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=b,l=!1,f=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,f=!1}let g=e[e.length-1],k=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:N,found:y,spaceBefore:c,comment:u,hasNewline:p,anchor:v,tag:w,newlineAfterProp:S,end:k,start:E??k}}kd.resolveProps=AN});var Aa=R(Ed=>{"use strict";function tc(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(tc(t.key)||tc(t.value))return!0}return!1;default:return!0}}Ed.containsNewline=tc});var ic=R(Cd=>{"use strict";var xN=Aa();function TN(e,t,i){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&xN.containsNewline(t)&&i(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Cd.flowIndentCheck=TN});var nc=R(Pd=>{"use strict";var Rd=L();function IN(e,t,i){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let r=typeof n=="function"?n:(a,o)=>a===o||Rd.isScalar(a)&&Rd.isScalar(o)&&a.value===o.value;return t.some(a=>r(a.key,i))}Pd.mapIncludes=IN});var Od=R(_d=>{"use strict";var Ad=Ot(),_N=$t(),xd=Fn(),ON=Aa(),Td=ic(),jN=nc(),Id="All mapping items must start at the same column";function $N({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??_N.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=xd.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",Id)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||ON.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",Id);i.atKey=!0;let w=h.end,S=d?e(i,d,h,r):t(i,w,u,null,h,r);i.schema.compat&&Td.flowIndentCheck(n.indent,d,r),i.atKey=!1,jN.mapIncludes(i,s.items,S)&&r(w,"DUPLICATE_KEY","Map keys must be unique");let N=xd.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:S.range[2],onError:r,parentIndent:n.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=N.end,N.found){v&&(m?.type==="block-map"&&!N.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<N.found.offset-1024&&r(S.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let y=m?e(i,m,N,r):t(i,c,p,null,N,r);i.schema.compat&&Td.flowIndentCheck(n.indent,m,r),c=y.range[2];let E=new Ad.Pair(S,y);i.options.keepSourceTokens&&(E.srcToken=f),s.items.push(E)}else{v&&r(S.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),N.comment&&(S.comment?S.comment+=`
|
|
68
|
+
`+N.comment:S.comment=N.comment);let y=new Ad.Pair(S);i.options.keepSourceTokens&&(y.srcToken=f),s.items.push(y)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}_d.resolveBlockMap=$N});var $d=R(jd=>{"use strict";var HN=Ht(),LN=Fn(),MN=ic();function DN({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??HN.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=LN.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?e(i,u,d,r):t(i,d.end,f,null,d,r);i.schema.compat&&MN.flowIndentCheck(n.indent,u,r),c=p.range[2],s.items.push(p)}return s.range=[n.offset,c,l??c],s}jd.resolveBlockSeq=DN});var Hi=R(Hd=>{"use strict";function FN(e,t,i,n){let r="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&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`)}t+=c.length}}return{comment:r,offset:t}}Hd.resolveEnd=FN});var Fd=R(Dd=>{"use strict";var BN=L(),qN=Ot(),Ld=$t(),VN=Ht(),zN=Hi(),Md=Fn(),WN=Aa(),JN=nc(),rc="Block collections are not allowed within flow collections",ac=e=>e&&(e.type==="block-map"||e.type==="block-seq");function UN({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Ld.YAMLMap:VN.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 w=n.items[v],{start:S,key:N,sep:y,value:E}=w,g=Md.resolveProps(S,{flow:s,indicator:"explicit-key-ind",next:N??y?.[0],offset:u,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!g.found){if(!g.anchor&&!g.tag&&!y&&!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&&WN.containsNewline(N)&&r(N,"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 k="";e:for(let b of S)switch(b.type){case"comma":case"space":break;case"comment":k=b.source.substring(1);break e;default:break e}if(k){let b=l.items[l.items.length-1];BN.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
|
|
70
|
+
`+k:b.comment=k,g.comment=g.comment.substring(k.length+1)}}if(!o&&!y&&!g.found){let k=E?e(i,E,g,r):t(i,g.end,y,null,g,r);l.items.push(k),u=k.range[2],ac(E)&&r(k.range,"BLOCK_IN_FLOW",rc)}else{i.atKey=!0;let k=g.end,b=N?e(i,N,g,r):t(i,k,S,null,g,r);ac(N)&&r(b.range,"BLOCK_IN_FLOW",rc),i.atKey=!1;let C=Md.resolveProps(y??[],{flow:s,indicator:"map-value-ind",next:E,offset:b.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(C.found){if(!o&&!g.found&&i.options.strict){if(y)for(let F of y){if(F===C.found)break;if(F.type==="newline"){r(F,"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?e(i,E,C,r):C.found?t(i,C.end,y,null,C,r):null;B?ac(E)&&r(B.range,"BLOCK_IN_FLOW",rc):C.comment&&(b.comment?b.comment+=`
|
|
71
|
+
`+C.comment:b.comment=C.comment);let Y=new qN.Pair(b,B);if(i.options.keepSourceTokens&&(Y.srcToken=w),o){let F=l;JN.mapIncludes(i,F.items,b)&&r(k,"DUPLICATE_KEY","Map keys must be unique"),F.items.push(Y)}else{let F=new Ld.YAMLMap(i.schema);F.flow=!0,F.items.push(Y);let U=(B??b).range;F.range=[b.range[0],U[1],U[2]],l.items.push(F)}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),w=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",w),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let v=zN.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}Dd.resolveFlowCollection=UN});var qd=R(Bd=>{"use strict";var KN=L(),GN=te(),YN=$t(),XN=Ht(),QN=Od(),ZN=$d(),eb=Fd();function oc(e,t,i,n,r,a){let o=i.type==="block-map"?QN.resolveBlockMap(e,t,i,n,a):i.type==="block-seq"?ZN.resolveBlockSeq(e,t,i,n,a):eb.resolveFlowCollection(e,t,i,n,a),s=o.constructor;return r==="!"||r===s.tagName?(o.tag=s.tagName,o):(r&&(o.tag=r),o)}function tb(e,t,i,n,r){let a=n.tag,o=a?t.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===YN.YAMLMap.tagName&&s==="map"||o===XN.YAMLSeq.tagName&&s==="seq")return oc(e,t,i,r,o);let c=t.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=t.schema.knownTags[o];if(d?.collection===s)t.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),oc(e,t,i,r,o)}let l=oc(e,t,i,r,o,c),f=c.resolve?.(l,d=>r(a,"TAG_RESOLVE_FAILED",d),t.options)??l,u=KN.isNode(f)?f:new GN.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Bd.composeCollection=tb});var cc=R(Vd=>{"use strict";var sc=te();function ib(e,t,i){let n=t.offset,r=nb(t,e.options.strict,i);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let a=r.mode===">"?sc.Scalar.BLOCK_FOLDED:sc.Scalar.BLOCK_LITERAL,o=t.source?rb(t.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 t.source&&(v+=t.source.length),{value:h,type:a,comment:r.comment,range:[n,v,v]}}let c=t.indent+r.indent,l=t.offset+r.length,f=0;for(let h=0;h<s;++h){let[v,w]=o[h];if(w===""||w==="\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&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+w.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,w]=o[h];l+=v.length+w.length+1;let S=w[w.length-1]==="\r";if(S&&(w=w.slice(0,-1)),w&&v.length<c){let y=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;i(l-w.length-(S?2:1),"BAD_INDENT",y),v=""}a===sc.Scalar.BLOCK_LITERAL?(u+=d+v.slice(c)+w,d=`
|
|
75
|
+
`):v.length>c||w[0]===" "?(d===" "?d=`
|
|
76
|
+
`:!p&&d===`
|
|
77
|
+
`&&(d=`
|
|
78
|
+
|
|
79
|
+
`),u+=d+v.slice(c)+w,d=`
|
|
80
|
+
`,p=!0):w===""?d===`
|
|
81
|
+
`?u+=`
|
|
82
|
+
`:d=`
|
|
83
|
+
`:(u+=d+w,d=" ",p=!1)}switch(r.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)u+=`
|
|
84
|
+
`+o[h][0].slice(c);u[u.length-1]!==`
|
|
85
|
+
`&&(u+=`
|
|
86
|
+
`);break;default:u+=`
|
|
87
|
+
`}let m=n+r.length+t.source.length;return{value:u,type:a,comment:r.comment,range:[n,m,m]}}function nb({offset:e,props:t},i,n){if(t[0].type!=="block-scalar-header")return n(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=t[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=e+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<t.length;++d){let p=t[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 rb(e){let t=e.split(/\n( *)/),i=t[0],n=i.match(/^( *)/),a=[n?.[1]?[n[1],i.slice(n[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Vd.resolveBlockScalar=ib});var uc=R(Wd=>{"use strict";var lc=te(),ab=Hi();function ob(e,t,i){let{offset:n,type:r,source:a,end:o}=e,s,c,l=(d,p,m)=>i(n+d,p,m);switch(r){case"scalar":s=lc.Scalar.PLAIN,c=sb(a,l);break;case"single-quoted-scalar":s=lc.Scalar.QUOTE_SINGLE,c=cb(a,l);break;case"double-quoted-scalar":s=lc.Scalar.QUOTE_DOUBLE,c=lb(a,l);break;default:return i(e,"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=ab.resolveEnd(o,f,t,i);return{value:c,type:s,comment:u.comment,range:[n,f,u.offset]}}function sb(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),zd(e)}function cb(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),zd(e.slice(1,-1)).replace(/''/g,"'")}function zd(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
|
+
`,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
|
+
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let r=n[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;n=i.exec(e);)n[1]===""?a===`
|
|
90
|
+
`?r+=a:a=`
|
|
91
|
+
`:(r+=a+n[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,n=s.exec(e),r+a+(n?.[1]??"")}function lb(e,t){let i="";for(let n=1;n<e.length-1;++n){let r=e[n];if(!(r==="\r"&&e[n+1]===`
|
|
92
|
+
`))if(r===`
|
|
93
|
+
`){let{fold:a,offset:o}=ub(e,n);i+=a,n=o}else if(r==="\\"){let a=e[++n],o=fb[a];if(o)i+=o;else if(a===`
|
|
94
|
+
`)for(a=e[n+1];a===" "||a===" ";)a=e[++n+1];else if(a==="\r"&&e[n+1]===`
|
|
95
|
+
`)for(a=e[++n+1];a===" "||a===" ";)a=e[++n+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=db(e,n+1,s,t),n+=s}else{let s=e.substr(n-1,2);t(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(r===" "||r===" "){let a=n,o=e[n+1];for(;o===" "||o===" ";)o=e[++n+1];o!==`
|
|
96
|
+
`&&!(o==="\r"&&e[n+2]===`
|
|
97
|
+
`)&&(i+=n>a?e.slice(a,n+1):r)}else i+=r}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function ub(e,t){let i="",n=e[t+1];for(;(n===" "||n===" "||n===`
|
|
98
|
+
`||n==="\r")&&!(n==="\r"&&e[t+2]!==`
|
|
99
|
+
`);)n===`
|
|
100
|
+
`&&(i+=`
|
|
101
|
+
`),t+=1,n=e[t+1];return i||(i=" "),{fold:i,offset:t}}var fb={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function db(e,t,i,n){let r=e.substr(t,i),o=r.length===i&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return n(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Wd.resolveFlowScalar=ob});var Kd=R(Ud=>{"use strict";var si=L(),Jd=te(),hb=cc(),pb=uc();function mb(e,t,i,n){let{value:r,type:a,comment:o,range:s}=t.type==="block-scalar"?hb.resolveBlockScalar(e,t,n):pb.resolveFlowScalar(t,e.options.strict,n),c=i?e.directives.tagName(i.source,u=>n(i,"TAG_RESOLVE_FAILED",u)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[si.SCALAR]:c?l=vb(e.schema,r,c,i,n):t.type==="scalar"?l=gb(e,r,t,n):l=e.schema[si.SCALAR];let f;try{let u=l.resolve(r,d=>n(i??t,"TAG_RESOLVE_FAILED",d),e.options);f=si.isScalar(u)?u:new Jd.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);n(i??t,"TAG_RESOLVE_FAILED",d),f=new Jd.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 vb(e,t,i,n,r){if(i==="!")return e[si.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[si.SCALAR])}function gb({atKey:e,directives:t,schema:i},n,r,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(n))||i[si.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(n))??i[si.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}Ud.composeScalar=mb});var Yd=R(Gd=>{"use strict";function wb(e,t,i){if(t){i??(i=t.length);for(let n=i-1;n>=0;--n){let r=t[n];switch(r.type){case"space":case"comment":case"newline":e-=r.source.length;continue}for(r=t[++n];r?.type==="space";)e+=r.source.length,r=t[++n];break}}return e}Gd.emptyScalarPosition=wb});var Zd=R(dc=>{"use strict";var yb=Nn(),Nb=L(),bb=qd(),Xd=Kd(),Sb=Hi(),kb=Yd(),Eb={composeNode:Qd,composeEmptyNode:fc};function Qd(e,t,i,n){let r=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,f=!0;switch(t.type){case"alias":l=Cb(e,t,n),(s||c)&&n(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Xd.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=bb.composeCollection(Eb,e,t,i,n),s&&(l.anchor=s.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);n(t,"RESOURCE_EXHAUSTION",d)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=fc(e,t.offset,void 0,null,i,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),r&&e.options.stringKeys&&(!Nb.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&f&&(l.srcToken=t),l}function fc(e,t,i,n,{spaceBefore:r,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:kb.emptyScalarPosition(t,i,n),indent:-1,source:""},u=Xd.composeScalar(e,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 Cb({options:e},{offset:t,source:i,end:n},r){let a=new yb.Alias(i.substring(1));a.source===""&&r(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&r(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=Sb.resolveEnd(n,o,e.strict,r);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}dc.composeEmptyNode=fc;dc.composeNode=Qd});var ih=R(th=>{"use strict";var Rb=Hn(),eh=Zd(),Pb=Hi(),Ab=Fn();function xb(e,t,{offset:i,start:n,value:r,end:a},o){let s=Object.assign({_directives:t},e),c=new Rb.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Ab.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?eh.composeNode(l,r,f,o):eh.composeEmptyNode(l,f.end,n,null,f,o);let u=c.contents.range[2],d=Pb.resolveEnd(a,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[i,u,d.offset],c}th.composeDoc=xb});var pc=R(ah=>{"use strict";var Tb=Mr("process"),Ib=Zo(),_b=Hn(),Bn=Dn(),nh=L(),Ob=ih(),jb=Hi();function qn(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function rh(e){let t="",i=!1,n=!1;for(let r=0;r<e.length;++r){let a=e[r];switch(a[0]){case"#":t+=(t===""?"":n?`
|
|
103
|
+
|
|
104
|
+
`:`
|
|
105
|
+
`)+(a.substring(1)||" "),i=!0,n=!1;break;case"%":e[r+1]?.[0]!=="#"&&(r+=1),i=!1;break;default:i||(n=!0),i=!1}}return{comment:t,afterEmptyLine:n}}var hc=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,n,r,a)=>{let o=qn(i);a?this.warnings.push(new Bn.YAMLWarning(o,n,r)):this.errors.push(new Bn.YAMLParseError(o,n,r))},this.directives=new Ib.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:n,afterEmptyLine:r}=rh(this.prelude);if(n){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${n}`:n;else if(r||t.directives.docStart||!a)t.commentBefore=n;else if(nh.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];nh.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${n}
|
|
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)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:rh(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,n=-1){for(let r of t)yield*this.next(r);yield*this.end(i,n)}*next(t){switch(Tb.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,n,r)=>{let a=qn(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",n,r)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=Ob.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,n=new Bn.YAMLParseError(qn(t),"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 Bn.YAMLParseError(qn(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let i=jb.resolveEnd(t.end,t.offset+t.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 Bn.YAMLParseError(qn(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let n=Object.assign({_directives:this.directives},this.options),r=new _b.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}}};ah.Composer=hc});var ch=R(xa=>{"use strict";var $b=cc(),Hb=uc(),Lb=Dn(),oh=Cn();function Mb(e,t=!0,i){if(e){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 Lb.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Hb.resolveFlowScalar(e,t,n);case"block-scalar":return $b.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function Db(e,t){let{implicitKey:i=!1,indent:n,inFlow:r=!1,offset:a=-1,type:o="PLAIN"}=t,s=oh.stringifyString({type:o,value:e},{implicitKey:i,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
110
|
+
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
|
+
`),f=s.substring(0,l),u=s.substring(l+1)+`
|
|
112
|
+
`,d=[{type:"block-scalar-header",offset:a,indent:n,source:f}];return sh(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 Fb(e,t,i={}){let{afterKey:n=!1,implicitKey:r=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(n&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=oh.stringifyString({type:o,value:t},{implicitKey:r||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Bb(e,c);break;case'"':mc(e,c,"double-quoted-scalar");break;case"'":mc(e,c,"single-quoted-scalar");break;default:mc(e,c,"scalar")}}function Bb(e,t){let i=t.indexOf(`
|
|
114
|
+
`),n=t.substring(0,i),r=t.substring(i+1)+`
|
|
115
|
+
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=n,e.source=r}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:n}];sh(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:r})}}function sh(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function mc(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let n=e.props.slice(1),r=t.length;e.props[0].type==="block-scalar-header"&&(r-=e.props[0].source.length);for(let a of n)a.offset+=r;delete e.props,Object.assign(e,{type:i,source:t,end:n});break}case"block-map":case"block-seq":{let r={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:i,source:t,end:[r]});break}default:{let n="indent"in e?e.indent:-1,r="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:n,source:t,end:r})}}}xa.createScalarToken=Db;xa.resolveAsScalar=Mb;xa.setScalarValue=Fb});var uh=R(lh=>{"use strict";var qb=e=>"type"in e?Ia(e):Ta(e);function Ia(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Ia(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Ta(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Ta(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Ta(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function Ta({start:e,key:t,sep:i,value:n}){let r="";for(let a of e)r+=a.source;if(t&&(r+=Ia(t)),i)for(let a of i)r+=a.source;return n&&(r+=Ia(n)),r}lh.stringify=qb});var ph=R(hh=>{"use strict";var vc=Symbol("break visit"),Vb=Symbol("skip children"),fh=Symbol("remove item");function ci(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),dh(Object.freeze([]),e,t)}ci.BREAK=vc;ci.SKIP=Vb;ci.REMOVE=fh;ci.itemAtPath=(e,t)=>{let i=e;for(let[n,r]of t){let a=i?.[n];if(a&&"items"in a)i=a.items[r];else return}return i};ci.parentCollection=(e,t)=>{let i=ci.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],r=i?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function dh(e,t,i){let n=i(t,e);if(typeof n=="symbol")return n;for(let r of["key","value"]){let a=t[r];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=dh(Object.freeze(e.concat([[r,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===vc)return vc;s===fh&&(a.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}hh.visit=ci});var _a=R(be=>{"use strict";var gc=ch(),zb=uh(),Wb=ph(),wc="\uFEFF",yc="",Nc="",bc="",Jb=e=>!!e&&"items"in e,Ub=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Kb(e){switch(e){case wc:return"<BOM>";case yc:return"<DOC>";case Nc:return"<FLOW_END>";case bc:return"<SCALAR>";default:return JSON.stringify(e)}}function Gb(e){switch(e){case wc:return"byte-order-mark";case yc:return"doc-mode";case Nc:return"flow-error-end";case bc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
|
+
`:case`\r
|
|
119
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}be.createScalarToken=gc.createScalarToken;be.resolveAsScalar=gc.resolveAsScalar;be.setScalarValue=gc.setScalarValue;be.stringify=zb.stringify;be.visit=Wb.visit;be.BOM=wc;be.DOCUMENT=yc;be.FLOW_END=Nc;be.SCALAR=bc;be.isCollection=Jb;be.isScalar=Ub;be.prettyToken=Kb;be.tokenType=Gb});var Ec=R(vh=>{"use strict";var Vn=_a();function We(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var mh=new Set("0123456789ABCDEFabcdef"),Yb=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Oa=new Set(",[]{}"),Xb=new Set(` ,[]{}
|
|
121
|
+
\r `),Sc=e=>!e||Xb.has(e),kc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let n=this.next??"stream";for(;n&&(i||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
|
|
122
|
+
`?!0:i==="\r"?this.buffer[t+1]===`
|
|
123
|
+
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let n=0;for(;i===" ";)i=this.buffer[++n+t];if(i==="\r"){let r=this.buffer[n+t+1];if(r===`
|
|
124
|
+
`||!r&&!this.atEnd)return t+n+1}return i===`
|
|
125
|
+
`||n>=this.indentNext||!i&&!this.atEnd?t+n:-1}if(i==="-"||i==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&We(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
126
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Vn.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,n=t.indexOf("#");for(;n!==-1;){let a=t[n-1];if(a===" "||a===" "){i=n-1;break}else n=t.indexOf("#",n+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let r=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield Vn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let i=this.peek(3);if((i==="---"||i==="...")&&We(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&&!We(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&We(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 t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Sc),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,n=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=n=i):i=0,i+=yield*this.pushSpaces(!0);while(t+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("..."))&&We(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield Vn.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(Sc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||We(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let n=this.buffer.substring(0,i),r=n.indexOf(`
|
|
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 t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>We(i)||i==="#")}*parseBlockScalar(){let t=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
|
+
`:t=a,i=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
|
+
`)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(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
131
|
+
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let r=t+1;for(n=this.buffer[r];n===" ";)n=this.buffer[++r];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
|
|
132
|
+
`;)n=this.buffer[++r];t=r-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
+
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield Vn.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=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(We(a)||t&&Oa.has(a))break;i=n}else if(We(r)){let a=this.buffer[n+1];if(r==="\r"&&(a===`
|
|
134
|
+
`?(n+=1,r=`
|
|
135
|
+
`,a=this.buffer[n+1]):i=n),a==="#"||t&&Oa.has(a))break;if(r===`
|
|
136
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(t&&Oa.has(r))break;i=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Vn.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let n=this.buffer.slice(this.pos,t);return n?(yield n,this.pos+=n.length,n.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Sc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,n=this.charAt(1);if(We(n)||i&&Oa.has(n)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!We(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(Yb.has(i))i=this.buffer[++t];else if(i==="%"&&mh.has(this.buffer[t+1])&&mh.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
|
+
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,n;do n=this.buffer[++i];while(n===" "||t&&n===" ");let r=i-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=i),r}*pushUntil(t){let i=this.pos,n=this.buffer[i];for(;!t(n);)n=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};vh.Lexer=kc});var Rc=R(gh=>{"use strict";var Cc=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,n=this.lineStarts.length;for(;i<n;){let a=i+n>>1;this.lineStarts[a]<t?i=a+1:n=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let r=this.lineStarts[i-1];return{line:i,col:t-r+1}}}};gh.LineCounter=Cc});var Ac=R(Sh=>{"use strict";var Qb=Mr("process"),wh=_a(),Zb=Ec();function Lt(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function yh(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function bh(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function ja(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Li(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function $a(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function Nh(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Lt(t.start,"explicit-key-ind")&&!Lt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,bh(t.value)?t.value.end?$a(t.value.end,t.sep):t.value.end=t.sep:$a(t.start,t.sep),delete t.sep)}var Pc=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Zb.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(t,i))yield*this.next(n);i||(yield*this.end())}*next(t){if(this.source=t,Qb.env.LOG_TOKENS&&console.log("|",wh.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=wh.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let n=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let 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"&&Nh(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&&yh(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 t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{yh(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let i=ja(this.peek(2)),n=Li(i),r;t.end?(r=t.end,r.push(this.sourceToken),delete t.end):r=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:n,key:t,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
|
|
139
|
+
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
140
|
+
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let 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):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){$a(r,i.start),r.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.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>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):r||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Lt(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(bh(i.key)&&!Lt(i.sep,"newline")){let o=Li(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(Lt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Li(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||r?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Lt(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?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!Lt(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&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let 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):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){$a(r,i.start),r.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||Lt(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.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(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!i||i.value?t.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":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);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===t.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=ja(n),a=Li(r);Nh(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
|
|
141
|
+
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
142
|
+
`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=ja(t),n=Li(i);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=ja(t),n=Li(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Sh.Parser=Pc});var Ph=R(Wn=>{"use strict";var kh=pc(),eS=Hn(),zn=Dn(),tS=ds(),iS=L(),nS=Rc(),Eh=Ac();function Ch(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new nS.LineCounter||null,prettyErrors:t}}function rS(e,t={}){let{lineCounter:i,prettyErrors:n}=Ch(t),r=new Eh.Parser(i?.addNewLine),a=new kh.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(zn.prettifyError(e,i)),s.warnings.forEach(zn.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Rh(e,t={}){let{lineCounter:i,prettyErrors:n}=Ch(t),r=new Eh.Parser(i?.addNewLine),a=new kh.Composer(t),o=null;for(let s of a.compose(r.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new zn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(zn.prettifyError(e,i)),o.warnings.forEach(zn.prettifyError(e,i))),o}function aS(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=Rh(e,i);if(!r)return null;if(r.warnings.forEach(a=>tS.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 oS(e,t,i){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:i===void 0&&t&&(i=t),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(e===void 0){let{keepUndefined:r}=i??t??{};if(!r)return}return iS.isDocument(e)&&!n?e.toString(i):new eS.Document(e,n,i).toString(i)}Wn.parse=aS;Wn.parseAllDocuments=rS;Wn.parseDocument=Rh;Wn.stringify=oS});var Tc=R(V=>{"use strict";var sS=pc(),cS=Hn(),lS=Ks(),xc=Dn(),uS=Nn(),Mt=L(),fS=Ot(),dS=te(),hS=$t(),pS=Ht(),mS=_a(),vS=Ec(),gS=Rc(),wS=Ac(),Ha=Ph(),Ah=vn();V.Composer=sS.Composer;V.Document=cS.Document;V.Schema=lS.Schema;V.YAMLError=xc.YAMLError;V.YAMLParseError=xc.YAMLParseError;V.YAMLWarning=xc.YAMLWarning;V.Alias=uS.Alias;V.isAlias=Mt.isAlias;V.isCollection=Mt.isCollection;V.isDocument=Mt.isDocument;V.isMap=Mt.isMap;V.isNode=Mt.isNode;V.isPair=Mt.isPair;V.isScalar=Mt.isScalar;V.isSeq=Mt.isSeq;V.Pair=fS.Pair;V.Scalar=dS.Scalar;V.YAMLMap=hS.YAMLMap;V.YAMLSeq=pS.YAMLSeq;V.CST=mS;V.Lexer=vS.Lexer;V.LineCounter=gS.LineCounter;V.Parser=wS.Parser;V.parse=Ha.parse;V.parseAllDocuments=Ha.parseAllDocuments;V.parseDocument=Ha.parseDocument;V.stringify=Ha.stringify;V.visit=Ah.visit;V.visitAsync=Ah.visitAsync});import{randomUUID as vx}from"crypto";import{promises as gx}from"fs";import pn from"path";import{isDeepStrictEqual as wx}from"util";import{createHash as Vg}from"crypto";function $u(e,t,i,n){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!n.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function Hu(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Hu(e[t]);return Object.freeze(e)}function At(e){return Hu(structuredClone(e))}function Ko(e,t,i,n){return e.resolveStep({pkg:At(t),state:At(i),context:At(n)})}function Lu(e,t,i,n,r,a){return e.resolveNext({pkg:At(t),state:At(i),step:At(n),outcome:At(r),context:At(a)})}function zg(e,t,i){return Vg("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function Go(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function Mu(e,t,i,n,r){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=Ko(n,e,t,r);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Go(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:zg(s.runId,s.iteration,o.id),stepId:o.id};return Wg(e,s,c,i)}function Wg(e,t,i,n){let r=$u(i,t,e.guardrails,n);return r.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:r.reason}}function Du(e,t,i,n,r){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?Ko(n,e,t,r):void 0,o=a?Go(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?Lu(n,e,t,o,i,r):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Go(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as Cl}from"fs";import pm from"path";var go=ju(Tc(),1);import{promises as am}from"fs";import gt from"path";import{createHash as SS}from"node:crypto";import{promises as Je}from"node:fs";import Le from"node:path";import{TextDecoder as kS}from"node:util";import Ic from"path";var yS=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),NS=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function bS(e){return e.toLowerCase().startsWith(".env")}function at(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>bS(n))?"environment-file":i.some(n=>NS.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>yS.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function xh(e,t){let i=at(t);if(i)return i;let n=Ic.resolve(e.projectRoot,...t.split("/")),r=Ic.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===Ic.resolve(e.configFile)?"native-runtime":null}function Dt(e){return e!==0&&e!==0n&&e!=="0"}function de(e,t){return Dt(e.dev)&&Dt(t.dev)&&Dt(e.ino)&&Dt(t.ino)}function $(e,t){let i=Dt(e.dev)&&Dt(t.dev);if(i&&e.dev!==t.dev)return!1;let n=Dt(e.ino)&&Dt(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var Jn=1024*1024;function _c(e,t){let i=Le.relative(e,t);return i===""||!Le.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Le.sep}`)}function ES(e){let t=Le.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||Le.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),n=at(e);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${e}`);return e}function CS(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function RS(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function La(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return de(i,n)?$(i,n):$(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Th(e){let t=await Je.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Je.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function PS(e,t){let i=Le.resolve(e),n=Le.resolve(t);if(!_c(i,n))throw new Error("Native artifact path is outside its root");let r=[await Th(i)],a=i;for(let o of Le.relative(i,n).split(Le.sep).filter(Boolean)){a=Le.join(a,o);let s=await Th(a);if(!_c(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Ih(e){for(let t of e){let i=await Je.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!RS(t,i)||await Je.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function me(e){let t=ES(e.ref),i=CS(e.maxBytes??Jn),n=Le.resolve(e.root,...t.split("/")),r=await PS(e.root,Le.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await Je.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Je.realpath(n);if(!_c(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);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 Ih(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!La(a,c)||!La(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let N=i+1-d,y=await s.read(p,0,Math.min(p.length,N),null);if(y.bytesRead===0)break;if(d+=y.bytesRead,d>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);u.push(Buffer.from(p.subarray(0,y.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),Je.lstat(n),Je.realpath(n)]);if(await Ih(r),!h.isFile()||h.isSymbolicLink()||v!==o||!La(c,m)||!La(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let w=Buffer.concat(u,d),S;try{S=new kS("utf-8",{fatal:!0}).decode(w)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:d,hash:SS("sha256").update(w).digest("hex"),text:S}}finally{await s.close()}}import{randomUUID as AS}from"crypto";import{promises as he}from"fs";import Ue from"path";function jc(e,t){let i=Ue.relative(e,t);return i===""||!Ue.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ue.sep}`)}function xS(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Oc(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return de(i,n)?$(i,n):$(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function _h(e){let t=await he.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await he.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Un(e){for(let t of e){let i=await he.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!xS(t,i)||await he.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function TS(e,t){let i=Ue.resolve(e),n=Ue.resolve(t);if(!jc(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await _h(i)],a=Ue.relative(i,n).split(Ue.sep).filter(Boolean),o=i;for(let s of a){await Un(r),o=Ue.join(o,s);try{await he.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await _h(o);if(!jc(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Un(r),r}async function IS(e){let t;try{t=await he.open(e,"r"),await t.sync()}catch(i){let n=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw i}finally{await t?.close()}}async function Oh(e,t,i={}){let n=Ue.dirname(e),r=i.containedRoot?await TS(i.containedRoot,n):null;r||await he.mkdir(n,{recursive:!0});let a=Ue.join(n,`.${Ue.basename(e)}.${AS()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await he.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([he.lstat(a),he.realpath(a)]);if(await Un(r),!c.isFile()||c.isSymbolicLink()||!Oc(s,c)||!jc(r[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!Oc(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 Un(r);let c=await he.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Oc(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await he.link(a,e),await he.unlink(a)):await he.rename(a,e),await IS(n)}catch(c){if(await o?.close(),!r)await he.rm(a,{force:!0});else try{await Un(r),await he.rm(a,{force:!0})}catch{}throw c}}async function pt(e,t,i={}){await Oh(e,t,i)}async function jh(e,t,i={}){await Oh(e,t,i)}async function Se(e,t,i={}){await pt(e,JSON.stringify(t,null,2)+`
|
|
143
|
+
`,i)}var Hc=ju(Tc(),1);import Ma from"path";var Ba=64*1024,Da=1024,Fa=64,Lc=5,_S=[".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/**"],ke={include:["**/*"],exclude:[..._S],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function OS(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Ma.posix.isAbsolute(i)||Ma.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${t} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${t} must not contain empty or dot path segments`);return n}function li(e){let t=OS(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Hh(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Mc(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||Ma.posix.isAbsolute(n)||Ma.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${t} cannot contain wildcards`);return r.join("/")}function Kn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Lh(e,t,i){let n=e??t;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function qa(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Da)throw new Error(`${t} exceeds ${Da} characters`);let i=0;for(let n=0;n<e.length;n+=1)e[n]==="?"?i+=1:e[n]==="*"&&(i+=1,e[n+1]==="*"&&(n+=1));if(i>Fa)throw new Error(`${t} contains more than ${Fa} wildcard tokens`);return e}function $h(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(n=>qa(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function $c(e,t,i){let n=e??t;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function jS(e){if(e===void 0)return{...ke,include:[...ke.include],exclude:[...ke.exclude]};let t=Kn(e,"native.snapshot");return{include:$h(t.include,"native.snapshot.include",ke.include),exclude:$h(t.exclude,"native.snapshot.exclude",ke.exclude),max_files:$c(t.max_files,ke.max_files,"native.snapshot.max_files"),max_total_bytes:$c(t.max_total_bytes,ke.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:$c(t.max_duration_ms,ke.max_duration_ms,"native.snapshot.max_duration_ms")}}function $S(e){if(e===void 0)return;let t=Kn(e,"native.pending_root_move"),i=t.id,n=t.from_artifact_root,r=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof 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(t.cleanup!==void 0){let s=Kn(t.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:li(n),toArtifactRoot:li(r),stage:a,...o?{cleanup:o}:{}}}function HS(e,t={}){let i=Kn(e,"native"),n=i.artifact_root??(t.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??Lc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=$S(i.pending_root_move);return{artifact_root:li(n),language:Lh(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:jS(i.snapshot),...s?{pending_root_move:s}:{}}}function LS(e){let t=Kn(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=t.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=t.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Hh(t.artifact_layout),language:Lh(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function MS(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function DS(e,t,i,n,r){let a=e.schema!==void 0;if(!(a||e.default_workflow!==void 0||e.workflows!==void 0||!r.allowPartialProject&&e.native!==void 0)||r.allowPartialProject&&!a)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=e.workflows??[e.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!t)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:c,ambient_resume:n,...t?{native:t}:{},...i?{classic:i}:{}}}function Va(e,t={}){let i=(0,Hc.parseDocument)(e,{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=MS(r.ambient_resume),o=r.native===void 0?void 0:HS(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=r.classic===void 0?void 0:LS(r.classic),c=DS(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function Dc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:li(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:Lc,snapshot:{...ke,include:[...ke.include],exclude:[...ke.exclude]}}}}import{createHash as BS}from"crypto";import{promises as Ja}from"fs";import Ft from"path";import{constants as za,promises as ui}from"fs";var Ke=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function Fc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Mh(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Gn(e){return{dev:e.dev,ino:e.ino,birthtime:Fc(e)}}function Wa(e,t){let i=Gn(e),n=Gn(t);return de(i,n)?$(i,n):$(i,n)&&Fc(e)===Fc(t)&&Mh(e)===Mh(t)&&e.size===t.size}async function fi(e,t,i={}){if(!Number.isSafeInteger(t)||t<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 ui.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new Ke("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Ke("too-large",`${n} exceeds ${t} bytes`);let o=await ui.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Gn(a)});let s=process.platform==="win32"?za.O_RDONLY:za.O_RDONLY|za.O_NOFOLLOW|za.O_NONBLOCK,c;try{c=await ui.open(e,s)}catch(l){throw l.code==="ELOOP"?new Ke("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:r}),ui.lstat(e,{bigint:r}),ui.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!Wa(a,l)||!Wa(a,f))throw new Ke("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,t+1));for(;;){let S=t+1-p,{bytesRead:N}=await c.read(m,0,Math.min(m.length,S),null);if(N===0)break;if(p+=N,p>t)throw new Ke("too-large",`${n} exceeds ${t} bytes`);d.push(Buffer.from(m.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([c.stat({bigint:r}),ui.lstat(e,{bigint:r}),ui.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||w!==o||!Wa(a,h)||!Wa(a,v))throw new Ke("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:w,identity:Gn(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:w}}finally{await c.close()}}function FS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Bc(e,t){let i=Ft.relative(e,t);return i===""||!Ft.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ft.sep}`)}async function Dh(e,t){let i=Ft.resolve(e),n=await Ja.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Ja.realpath(i)}async function Fh(e,t,i,n){let r=e;for(let a=0;a<i.length;a++){r=Ft.join(r,i[a]);let o;try{o=await Ja.lstat(r)}catch(f){if(FS(f))return{exists:!1,kind:"missing"};throw f}let s=Ft.relative(e,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 Ja.realpath(r);if(!Bc(t,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 Yn(e,t,i){let n=Mc(t,i.label),r=Ft.resolve(e),a=await Dh(r,i.label),o=n.split("/"),s=Ft.resolve(r,...o);if(!Bc(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Fh(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Mi(e,t,i,n){let r=await Yn(e,t,{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 Dh(r.projectRoot,n.label);return fi(r.target,i,{...n,verify:async(o,s)=>{if(!Bc(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Fh(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var Xn=".comet/config.yaml";function qS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function qc(e,t={}){return(await Ua(e,t)).document}async function VS(e){try{return(await Mi(e,Xn,Ba,{label:Xn})).bytes}catch(t){if(qS(t))return null;throw t}}function zS(e){return e?{exists:!0,sha256:BS("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Ua(e,t={}){let i=await VS(e);return{document:i?Va(i.toString("utf8"),t):null,identity:zS(i)}}var FI=16*1024;import{promises as Di}from"fs";import K from"path";import GS from"os";var Ka=".comet/config.yaml";async function zc(e){try{return await Di.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function YS(e){try{let t=await Di.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Qn(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}async function Zn(e){let t=[],i=e;for(;!await zc(i);){let r=K.dirname(i);if(r===i)break;t.push(K.basename(i)),i=r}let n=await Di.realpath(i);return K.resolve(n,...t.reverse())}async function zh(e){try{return(await Di.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ga(e){let t=K.resolve(e);try{(await Di.stat(t)).isDirectory()||(t=K.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=K.resolve(GS.homedir());for(;;){if(!(t===n&&i!==n)){let o=K.join(t,...Ka.split("/")),s=t===i||await YS(o);if(await zc(o)&&s)return t}if(await zc(K.join(t,".git")))return t;let a=K.dirname(t);if(a===t)return i;t=a}}function Ya(e){return li(e)}async function XS(e,t){let i=Ya(t),n=K.resolve(e,...i.split("/")),r=await Di.realpath(e),a=await Zn(n);if(!Qn(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function Wc(e,t){let i=Ya(t),n=await XS(e,i),r=K.join(n,"comet");if(await zh(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Zn(n),Zn(r)]);if(!Qn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:K.resolve(e),configFile:K.join(e,...Ka.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:K.join(r,"specs"),changesDir:K.join(r,"changes"),archiveDir:K.join(r,"archive"),runtimeDir:K.join(r,"runtime"),locksDir:K.join(r,"runtime","locks"),transactionsDir:K.join(r,"runtime","transactions")}}function G(e,t){return Qn(K.resolve(e),K.resolve(t))}async function H(e,t){let i=K.resolve(e),n=K.resolve(t);if(!Qn(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await zh(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([Zn(i),Zn(n)]);if(!Qn(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var Jc=ke;var Xa=qa;function ZS(e="docs",t="en"){return Dc(e,t)}async function Bt(e){let t=(await qc(e))?.config??null;return t?.native?t:null}async function Fi(e){let t=await Bt(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Wh(e){let t=await Ga(e.startPath),i=await Bt(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${Ka} 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=e.explicitArtifactRoot?Ya(e.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??ZS(n??"docs"),a=await Wc(t,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as Ok}from"fs";import jk from"path";import{AsyncLocalStorage as ek}from"async_hooks";import{randomUUID as Kh}from"crypto";import{promises as Me}from"fs";import Gh from"os";import ve from"path";var Jh=16*1024,Yh=".coordinator",tk=5e3,Uh=new ek,Qa=new Map;function ik(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function nk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function Xh(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Uc(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return de(i,n)?$(i,n):$(i,n)&&e.size===t.size}function Kc(e,t){return Uc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function mt(e){let t,i;try{let n=await fi(e,Jh,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Ke?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Jh} bytes: ${e}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:n}):new Error(`Native lock changed while reading: ${e}`,{cause:n}):n}return{file:e,owner:nk(JSON.parse(t.toString("utf8")),e),identity:Xh(i)}}async function rk(e){return(await mt(e))?.owner??null}function Qh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Gh.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=uk(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function ak(e,t){try{await Me.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Me.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Gc(e,t){let i=await mt(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Kc(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Me.mkdir(t,{recursive:!0});let n=ve.join(t,`${ve.basename(e.file)}.${e.owner.id}.${Kh()}.removed`);try{await Me.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await mt(n);if(!r||r.owner.id!==e.owner.id||!Uc(r.identity,e.identity))throw await ak(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Me.rm(n,{force:!0}),"removed"}function Zh(e){return{id:Kh(),pid:process.pid,hostname:Gh.hostname(),createdAt:new Date().toISOString(),operation:e}}async function ep(e,t){let i;try{i=await Me.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await rk(e);throw new Error(`Native lock is already held: ${e}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(t,null,2)+`
|
|
144
|
+
`,"utf8"),await i.sync(),Xh(await i.stat({bigint:!0}))}finally{await i.close()}}async function ok(e,t){let i=await H(e.nativeRoot,e.locksDir);await Me.mkdir(i,{recursive:!0});let n=await H(e.nativeRoot,ve.join(i,Yh));await Me.mkdir(n,{recursive:!0});let r=Zh(t),a=ve.join(n,`.${r.id}.tmp`),o=ve.join(n,`${r.id}.claim`);try{let s=await ep(a,r);await Me.rename(a,o);let c=await mt(o);if(!c||!Uc(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.nativeRoot,locksDir:i,owner:r,identity:c.identity}}finally{await Me.rm(a,{force:!0})}}async function sk(e){let t=ve.dirname(e.file),i=!1,n=ve.basename(e.file);for(let r of await Me.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=ve.join(t,r.name);if(ve.resolve(a)!==ve.resolve(e.file))try{let o=await mt(a),s=Qh(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Gc(o,t);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function tp(e){let t=await mt(e.file);if(t){if(t.owner.id!==e.owner.id||!Kc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Gc(t,ve.dirname(e.file))}}async function ck(e,t){let i=Date.now()+tk;for(;;){let n=await ok(e,t);if(!await sk(n))return n;if(await tp(n),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(r=>setTimeout(r,2+Math.floor(Math.random()*7)))}}async function lk(e){let t=Qa.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return Qa.set(e,r),await t,()=>{i(),Qa.get(e)===r&&Qa.delete(e)}}async function ip(e,t,i){let n=ve.resolve(e.locksDir),r=Uh.getStore();if(r?.has(n))return i();let a=await lk(n);try{let o=await ck(e,t),s=new Map(r??[]);return s.set(n,o),await Uh.run(s,async()=>{try{return await i()}finally{await tp(o)}})}finally{a()}}async function Bi(e,t,i){return ip(e,`acquire ${t}`,async()=>{let n=await H(e.nativeRoot,e.locksDir);await Me.mkdir(n,{recursive:!0});let r=await H(e.nativeRoot,ve.join(n,ik(t))),a=Zh(i),o=await ep(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function qi(e){await mt(e.file)&&await ip(e,`release ${ve.basename(e.file)}`,async()=>{let t=await mt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Kc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=ve.join(e.locksDir,Yh);await Gc(t,i)})}function uk(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function np(e){return Qh(await mt(e))}import{promises as Zc}from"fs";import ge from"path";import{TextDecoder as pk}from"util";import{createHash as fk}from"node:crypto";import{constants as Za,promises as z}from"node:fs";import Q from"node:path";import{TextDecoder as dk}from"node:util";function _e(e,t){let i=Q.relative(e,t);return i===""||!Q.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Q.sep}`)}function rp(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Yc(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ap(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Vi(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function zi(e,t){let i=await z.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await z.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Wi(e,t,i){let n=Q.resolve(e),r=Q.resolve(t);if(!_e(n,r))throw new Error(`${i} is outside its managed root`);let a=[await zi(n,i)],o=n;for(let s of Q.relative(n,r).split(Q.sep).filter(Boolean)){await ce(a,i),o=Q.join(o,s);let c=await zi(o,i);if(!_e(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ce(a,i),a}async function ce(e,t){for(let i of e){let n=await z.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Yc(i,n)||await z.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function hk(e,t,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-r,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>t)throw new Error(`${i} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function ie(e){let t=rp(e.maxBytes),i=Q.resolve(e.file),n=await Wi(e.root,Q.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(f=>zi(Q.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ce(n,e.label);let a=await z.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=ap(a),s=await z.realpath(i);if(!_e(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(f=>_e(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Za.O_RDONLY:Za.O_RDONLY|Za.O_NOFOLLOW|Za.O_NONBLOCK,l=await z.open(i,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([z.lstat(i),z.realpath(i)]);if(await ce(n,e.label),await ce(r,e.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!Vi(o,f)||!Vi(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await hk(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),z.lstat(i),z.realpath(i)]);if(await ce(n,e.label),await ce(r,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!Vi(o,m)||!Vi(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:fk("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function op(e){let t=await ie(e),i;try{i=new dk("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e.label} is not valid UTF-8`,{cause:n})}return{...t,text:i}}async function qt(e){let t=await Wi(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await z.readdir(e.directory,{withFileTypes:!0});else{let n=rp(e.maxEntries);i=[];let r=await z.opendir(e.directory);try{for await(let a of r)if(i.push(a),i.length>n)throw new Error(`${e.label} exceeds ${n} entries`)}finally{await r.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await ce(t,e.label),{entries:i,verify:()=>ce(t,e.label)}}async function er(e){let t=await Wi(e.root,e.directory,e.label);return{verify:()=>ce(t,e.label)}}async function sp(e){let t=Q.resolve(e.file),i=await Wi(e.root,Q.dirname(t),e.label),n=await z.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=ap(n),a=await z.realpath(t);if(!_e(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ie({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([z.lstat(t),z.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Vi(r,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await ce(i,e.label);let[l,f]=await Promise.all([z.lstat(t),z.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Vi(r,l)||f!==a)throw new Error(`${e.label} changed before removal`);await z.rm(t),await ce(i,e.label)}async function di(e){let t=Q.resolve(e.root),i=Q.resolve(e.directory);if(!_e(t,i))throw new Error(`${e.label} is outside its managed root`);let n=[await zi(t,e.label)],r=t;for(let a of Q.relative(t,i).split(Q.sep).filter(Boolean)){await ce(n,e.label),r=Q.join(r,a);try{await z.mkdir(r)}catch(s){if(s.code!=="EEXIST")throw s}let o=await zi(r,e.label);if(!_e(n[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${r}`);n.push(o)}await ce(n,e.label)}async function cp(e){let t=Q.resolve(e.root),i=Q.resolve(e.source),n=Q.resolve(e.target);if(i===n||!_e(t,i)||!_e(t,n)||_e(i,n)||_e(n,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await di({root:t,directory:Q.dirname(n),label:`${e.label} target parent`});let r=await Wi(t,Q.dirname(i),e.label),a=await Wi(t,Q.dirname(n),e.label),o=await zi(i,e.label);if(!_e(r[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await z.lstat(n),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([ce(r,e.label),ce(a,e.label)]);let s=await z.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Yc(o,s)||await z.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await z.rename(i,n),await Promise.all([ce(r,e.label),ce(a,e.label)]);let c=await z.lstat(n);if(!c.isDirectory()||c.isSymbolicLink()||!Yc(o,c)||!_e(r[0].realPath,await z.realpath(n)))throw new Error(`${e.label} source identity changed while moving`);try{throw await z.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function hi(e){let t=await ie({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await jh(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await z.lstat(e.target)}catch(r){if(r.code==="ENOENT")return;throw r}throw new Error(`${e.label} target changed before commit`)}if((await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var mk=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),vk=new Set(["id","type","source","target","staged","backup"]),gk=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),wk=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),yk=new Set(["sequence","timestamp","type","operationId"]),dp=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),hp=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),Nk=256*1024,bk=1024*1024,pp=16*1024,to=1024,el=64*1024*1024,Sk=2e4,mp=new pk("utf-8",{fatal:!0});function ir(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function nr(e,t,i){let n=Object.keys(e).filter(r=>!t.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Ui(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Xc(e,t){if(typeof e!="string"||e.length===0||ge.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function eo(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function lp(e,t){if(Xc(e,t),e.includes("\\")||e!==ge.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function kk(e,t){let i=ir(e,`transaction operations[${t}]`);if(nr(i,vk,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Xc(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&Xc(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 rr(e){let t=ir(e,"Native Archive transaction journal");if(nr(t,gk,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!dp.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Ui(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(eo(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=ir(s,`Archive transaction operations[${c}]`);if(nr(l,wk,`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`);lp(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&lp(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&eo(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(eo(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`);eo(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/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${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:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function vp(e){let t=ir(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return rr(t);if(nr(t,mk,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!dp.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!ge.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!ge.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Ui(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(kk),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:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function gp(e,t){let i=ir(e,`Native transaction event at line ${t}`);if(nr(i,yk,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Ui(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!hp.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let n=i.type==="operation-started"||i.type==="operation-completed";if(n&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!n&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function Ek(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let n=0;n<e.length;n+=1){let r=t[n],a=e[n];if(r==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==r)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[n,r,a,o]of i){if(e.length<=n)continue;let s=e.slice(n,Math.min(n+r,e.length));if(!Array.from({length:o-a+1},(l,f)=>String(a+f).padStart(r,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Ui(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Ui(e)}function Ji(e,t){return e.length<t.length&&t.startsWith(e)}function Ck(e){let t='","operationId":"';if(Ji(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),n=i.indexOf('"');if(n===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let r=i.slice(0,n);return/^[a-z0-9][a-z0-9-]*$/u.test(r)?Ji(i.slice(n),'"}'):!1}function Rk(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>pp)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Ji(e,i))return!0;if(!e.startsWith(i))return!1;let n=e.slice(i.length),r=n.slice(0,Math.min(24,n.length));if(!Ek(r))return!1;if(n.length<24)return!0;if(!Ui(r))return!1;let a='","type":"',o=n.slice(24);if(Ji(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of hp){if(Ji(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(Ck(l))return!0}else if(Ji(l,'"}'))return!0}return!1}function Pk(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>pp)throw new Error(`Native transaction event at line ${t} is too large`);return gp(JSON.parse(e),t)}function Ak(e){let t=e.split(`
|
|
145
|
+
`),i=t.at(-1)==="";if(i&&t.pop(),t.length>to)throw new Error(`Native transaction event log exceeds ${to} events`);let n=[];for(let r=0;r<t.length;r+=1){let a=r+1,o=t[r],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&r===t.length-1;try{n.push(Pk(s,a))}catch(l){if(c){let f=!1;try{JSON.parse(s),f=!0}catch{}if(!f&&Rk(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return n}function wp(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
146
|
+
`)}
|
|
147
|
+
`}function xk(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return ge.join(e.transactionsDir,t)}function yp(e,t){let i=xk(e,t);return{directory:i,journal:ge.join(i,"transaction.json"),events:ge.join(i,"events.jsonl"),staged:ge.join(i,"staged"),backups:ge.join(i,"backups")}}async function Ge(e,t){let i=yp(e,t);return await Promise.all(Object.values(i).map(n=>H(e.nativeRoot,n))),i}function Tk(e,t){if(t.length===0||ge.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i=ge.resolve(e.nativeRoot,...t.split(/[\\/]/u));if(!G(e.nativeRoot,i))throw new Error(`Unsafe Native transaction ref: ${t}`);return i}async function tr(e,t){return H(e.nativeRoot,Tk(e,t))}async function io(e){try{return await Zc.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function tl(e,t,i={}){let n=await Ge(e,t);try{await Zc.lstat(n.events)}catch(r){if(r.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw r}try{let r=await ie({root:e.nativeRoot,file:n.events,maxBytes:bk,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=mp.decode(r.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=Ak(a),s=wp(o);return{exists:!0,hash:r.hash,size:r.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(r){throw r.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:r}):r}}async function up(e,t,i){let n=await tl(e,t);if(n.exists!==i.exists||n.hash!==i.hash||n.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Vt(e,t,i,n){let r=await Ge(e,t),a=await tl(e,t),o=a.events.find(c=>c.type===i&&c.operationId===n);if(o)return a.needsRepair&&await pt(r.events,a.canonicalSource,{containedRoot:e.nativeRoot,beforeCommit:()=>up(e,t,a)}),o;if(a.events.length>=to)throw new Error(`Native transaction event log ${t} exceeds ${to} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...n?{operationId:n}:{}};return gp(s,s.sequence),await Zc.mkdir(r.directory,{recursive:!0}),await pt(r.events,wp([...a.events,s]),{containedRoot:e.nativeRoot,beforeCommit:()=>up(e,t,a)}),s}async function no(e,t,i={}){let n=await Ge(e,t),r=await ie({root:e.nativeRoot,file:n.journal,maxBytes:Nk,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(mp.decode(r.bytes)),o=vp(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Ki(e,t,i={}){return(await tl(e,t,i)).events}async function Np(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=vp({...t,status:i});return await Se((await Ge(e,t.id)).journal,n),n}async function Qc(e,t,i){try{return await ie({root:e.nativeRoot,file:t,maxBytes:el,label:i})}catch(n){if(n.code==="ENOENT")return null;throw n}}async function bp(e,t,i,n){let r=await Qc(e,t,`${n} source`);if(!r)throw new Error(`${n} source does not exist`);let a=await Qc(e,i,`${n} target`);await di({root:e.nativeRoot,directory:ge.dirname(i),label:`${n} target parent`}),await hi({sourceRoot:e.nativeRoot,source:t,targetRoot:e.nativeRoot,target:i,maxBytes:el,label:n,expectedHash:r.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function Ik(e,t,i){let n=await Qc(e,t,i);n&&await sp({root:e.nativeRoot,file:t,maxBytes:el,expectedHash:n.hash,expectedSize:n.size,label:i})}async function fp(e,t){if(!t.backup)return;let i=await tr(e,t.target),n=await tr(e,t.backup);!await io(i)||await io(n)||await bp(e,i,n,`Legacy Native transaction backup ${t.id}`)}async function _k(e,t){let i=await tr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await fp(e,t),await bp(e,await tr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await fp(e,t),await Ik(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await tr(e,t.source),[r,a]=await Promise.all([io(n),io(i)]);if(!r&&a){await(await qt({root:e.nativeRoot,directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:Sk})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!r)throw new Error(`Move source does not exist: ${t.source}`);await cp({root:e.nativeRoot,source:n,target:i,label:`Legacy Native transaction move ${t.id}`})}async function Sp(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=t.status==="prepared"?await Np(e,t,"applying"):t,r=await Ki(e,t.id),a=new Set(r.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of n.operations)a.has(s.id)||(await Vt(e,n.id,"operation-started",s.id),await _k(e,s),await Vt(e,n.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return n=await no(e,n.id),n}async function ro(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Vt(e,t.id,i),i==="commit"?Np(e,t,"committed"):t}function vt(e,t){let i=ge.resolve(t);if(!G(e.nativeRoot,i))throw new Error(`Path is outside the Native root: ${t}`);return ge.relative(e.nativeRoot,i).split(ge.sep).join("/")}async function $k(e,t){let i;try{i=await Ok.readdir(e.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 no(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function Hk(e,t){let i=Date.now()+5e3,n=jk.join(e.locksDir,"root-move.lock");for(;;)try{return await Bi(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await np(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 zt(e,t,i,n){let r=await Hk(e,t);try{if(await Fi(e.projectRoot),await $k(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await qi(r)}}function kp(e){return Number.isSafeInteger(e)&&e>=1}async function Ep(e){if(!kp(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!kp(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((n,r)=>JSON.stringify(n)===JSON.stringify(r));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as co}from"crypto";import{spawn as Hp}from"node:child_process";import{promises as Z}from"fs";import q from"path";import{createHash as Cp}from"crypto";import{createReadStream as Lk}from"fs";async function il(e){let t=Cp("sha256");for await(let i of Lk(e))t.update(i);return t.digest("hex")}function J(e){return Cp("sha256").update(e).digest("hex")}var ao={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Lp=1e3,Mk=8*1024*1024,Dk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Fk=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),Bk=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),qk=new Set(["schema","include","exclude","hash"]),Vk=new Set(["provider","gitSelection","physicalSelection","projection"]),zk=new Set(["provider","selection"]),Wk=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Jk=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),Uk=new Set(["schema","status","before","after"]),Kk=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Gk=new Set(["path","hash","size","type","gitObjectId"]),Yk=new Set(["path","size","type","reason"]),Xk=new Set(["ref","hash","count"]),Qk=new Set(["change-created","legacy-migration","explicit"]),Zk=new Set(["file","directory","other"]),eE=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"]),lo=/^[a-f0-9]{64}$/u,Mp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,tE=new Set(["EACCES","EPERM"]),Xi=64*1024,cl=64*1024,iE=6e4,nE=1e3,rE=2,Dp={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},aE={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function oE(e){let t=e.deadlineMs??iE;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Ye(e){return Math.max(0,e.deadlineAt-Date.now())}function _(e){return Ye(e)>=1}function nl(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function ar(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function sE(e){let t={...aE,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function cE(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let n=process.env.SystemRoot??process.env.WINDIR,r=n&&q.win32.isAbsolute(n)?q.win32.resolve(n):"C:\\Windows",a=q.win32.join(r,"System32","taskkill.exe");if(!q.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,f=null,u=(d,p=!1)=>{c||(c=!0,f&&clearTimeout(f),p&&l?.kill("SIGKILL"),s(d))};try{l=Hp(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),nE),f.unref()}catch{u(!1)}});for(let s=0;s<rE;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(n){if(n.code!=="ESRCH")throw n}e.kill("SIGKILL")}function ul(e,t,i,n){let r=Ye(e);if(r<1)throw nl();let a=e.gitProcess,o=Hp(a.command,[...a.argsPrefix??[],"-C",t,...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=cE(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?nl(m.error):nl()}return{code:p,spawnError:s}});return{child:o,completion:d}}function lE(e){let t={...Dp,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function oo(e,t,i,n=cl){let{child:r,completion:a}=ul(e,t,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>=Xi)return;let m=Xi-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 rl(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function al(e,t,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}=ul(e,t,i,n.stdin!==void 0),c=[],l=co("sha256"),f=[],u=0,d=0,p=0,m=0,h=Buffer.alloc(0),v=!1,w=!1,S=!1,N=y=>{let E=0;for(;E<y.byteLength;){let g=y.indexOf(0,E),k=g<0?y.byteLength:g,b=y.subarray(E,k);if(!v&&b.byteLength>0&&(h.byteLength+b.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,w=!0):h=Buffer.concat([h,b])),g<0)break;m+=1,h.byteLength===0&&!v&&(S=!0);let C=h.byteLength+1;!v&&m<=n.maxRecords&&p+C<=n.maxBytes?(c.push(h),p+=C):w=!0,h=Buffer.alloc(0),v=!1,E=g+1}};o.stdout.on("data",y=>{l.update(y),d+=y.byteLength,d>n.maxBytes&&(w=!0);let E=n.outputChunkBytes;if(E===void 0){N(y);return}for(let g=0;g<y.byteLength;g+=E)N(y.subarray(g,Math.min(y.byteLength,g+E)))}),o.stderr.on("data",y=>{if(u>=Xi)return;let E=Xi-u,g=Buffer.from(y).subarray(0,E);f.push(g),u+=g.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:y,spawnError:E})=>{let g=n.acceptedExitCodes??[0];if(y!==null&&g.includes(y)&&E===null&&!S&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:w,recordCount:m,stdoutBytes:d});return}a(new Error(`git ${i.join(" ")} failed${E?`: ${E.message}`:S||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 Rp(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function uE(e,t,i){let{child:n,completion:r}=ul(e,t,i,!1),a=[],o=0,s=!1;n.stdout.on("data",f=>{f.byteLength>0&&(s=!0)}),n.stderr.on("data",f=>{if(o>=Xi)return;let u=Xi-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 so(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||q.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||q.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function fE(e,t){return e.map(i=>{let n=so(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function dE(e){let t=q.resolve(e);for(;;){try{return await Z.lstat(q.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=q.dirname(t);if(i===t)return!1;t=i}}async function Fp(e,t,i,n={}){let r={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},a=await al(e,t,["ls-files","--stage","-z"],r);await n.afterStageBefore?.();let o=await al(e,t,["ls-files","--cached","--others","--exclude-standard","-z"],r);await n.afterCombined?.();let s=await al(e,t,["ls-files","--stage","-z"],r);return{stagedBefore:a,combined:o,stagedAfter:s}}function Bp(e){return{stageBefore:rl(e.stagedBefore),combined:rl(e.combined),stageAfter:rl(e.stagedAfter)}}async function hE(e,t,i=Dp,n={}){if(!await dE(t))return null;let r;try{r=await oo(e,t,["rev-parse","--is-inside-work-tree"])}catch(w){throw ar(w)?w:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:w})}if(r.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let a;try{a=await Fp(e,t,i,n)}catch(w){throw ar(w)?w:new Error("Native Git snapshot provider failed after repository detection",{cause:w})}let{stagedBefore:o,combined:s,stagedAfter:c}=a,l=new Set,f=new Map,u=new Set,d=w=>{for(let S of w){let N=Rp(S),y=N.indexOf(" ");if(y<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let E=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(N.slice(0,y))?.groups;if(!E)throw new Error("Native Git snapshot provider returned a malformed staged header");let g=so(N.slice(y+1));if(g===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");l.add(g),E.stage==="0"&&f.set(g,E.objectId),E.mode==="160000"&&E.stage==="0"&&u.add(g)}};d(o.records),d(c.records);let p=s.records.map(Rp),m=fE(p,"combined"),h=new Set(m.filter(w=>!l.has(w))),v=new Set(m.filter((w,S)=>!l.has(w)&&p[S].endsWith("/")));for(let w of u)v.delete(w);return{tracked:l,trackedObjectIds:f,untracked:h,gitlinks:u,nestedRepositories:v,omissions:[],overflow:null,evidence:null,initialFence:Bp(a)}}function Jt(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Pp(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function pE(e,t){return!Jt(e.stageBefore,e.stageAfter)||!Jt(e.stageAfter,t.stageBefore)||!Jt(e.combined,t.combined)||!Jt(t.stageBefore,t.stageAfter)}async function mE(e,t,i,n,r){let a;try{a=await Fp(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(f){throw ar(f)?f:new Error("Native Git snapshot provider failed during its final selection fence",{cause:f})}let o=n.initialFence,s=Bp(a),c=Pp(o)||Pp(s),l=pE(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:J(`comet.native.git-selection-overflow.v2
|
|
148
|
+
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var vE=(1n<<256n)-1n;function gE(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Ap(e){let t=q.resolve(e.paths.projectRoot),i=q.resolve(e.paths.nativeRoot),n=q.resolve(e.paths.configFile),r=q.join(t,".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=()=>Ye(e.execution)>=1?!0:(d=!0,m=!0,!1),v=N=>{let y=Buffer.from(`${N.type}\0${N.path}`,"utf8"),E=co("sha256").update("comet.native.physical-selection-record.v1\0").update(y).digest();for(let g=0;g<s.length;g+=1)s[g]^=E[g];if(c=c+BigInt(`0x${E.toString("hex")}`)&vE,f+=1,u+=y.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||u>e.limits.maxBytes){d=!0,m=!0;return}a.push(N)},w=async N=>{if(m||!h())return;let y;try{y=await Z.opendir(N)}catch(C){if(!h())return;if(!re(C)&&!ne(C)||N===t&&re(C))throw C;p||=ne(C),d||=re(C),m=!0;return}if(!h()){try{await y.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 y.read()}catch(X){if(!h())break;if(!re(X)&&!ne(X)||N===t&&re(X))throw X;p||=ne(X),d||=re(X),m=!0;break}if(!h()||C===null)break;if(l+=1,l>e.limits.maxNodes){d=!0,m=!0;break}let B=q.join(N,C.name),Y=bE(t,B);if(B===n||B===r||Ut(i,B)||e.denylist.some(X=>Ut(X,B))||at(Y)!==null)continue;if(!h())break;let F;try{F=await Z.lstat(B)}catch(X){if(!h())break;if(!re(X)&&!ne(X))throw X;if(p=!0,v({path:Y,type:"other"}),o.push({path:Y,size:null,type:"file",reason:re(X)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(Y),m||!h())break;continue}if(!h())break;let U=gE(F);if(U==="directory"){if(CE(e.policy,Y))continue;if(!h())break;let X;try{X=await Z.realpath(B)}catch(tt){if(!h())break;if(!re(tt)&&!ne(tt))throw tt;if(p=!0,v({path:Y,type:U}),o.push({path:Y,size:null,type:"directory",reason:re(tt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(Y),m||!h())break;continue}if(!h())break;if(!G(e.physicalProjectRoot,X)||Ut(e.physicalNativeRoot,X))continue;if(v({path:Y,type:U}),await e.hooks?.afterNode?.(Y),!h()||(await w(B),m))break;continue}if(v({path:Y,type:U}),await e.hooks?.afterNode?.(Y),!h()||m)break}}catch(C){E=!0,g=C}let k;try{await y.close()}catch(C){k=C}let b=h();if(E)throw g;if(b&&k!==void 0&&k.code!=="ERR_DIR_CLOSED")throw k};await w(t),h(),d?(a.length=0,f=0,u=0):(a.sort((N,y)=>N.path.localeCompare(y.path,"en")),o.sort((N,y)=>N.path.localeCompare(y.path,"en")));let S=d?J(`comet.native.physical-selection-incomplete.v1
|
|
149
|
+
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):J(`comet.native.physical-selection.v1
|
|
150
|
+
${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:S,visitedNodeCount:l,recordCount:f,storedRecordCount:a.length,encodedBytes:u,overflow:d,unstable:p}}}function qp(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function wE(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!qp(e,t),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:e,after:t}:null}}function yE(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function xp(e,t){let n=(await oo(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Mp.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return J(`gitlink:${n}`)}async function Tp(e,t){let i=await xp(e,t),n=await uE(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await xp(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function NE(e,t){if(at(t)!==null)return!1;let i=q.resolve(e.projectRoot,...t.split("/"));return!Ut(q.resolve(e.nativeRoot),i)}function bE(e,t){return q.relative(e,t).split(q.sep).join("/")}function SE(e,t){return t.map(i=>q.resolve(e,...i.split(/[\\/]/u)))}function Ut(e,t){let i=q.resolve(e),n=q.resolve(t);return n===i||G(i,n)}function re(e){return tE.has(e.code??"")}function ne(e){return e.code==="ENOENT"}function Vp(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
151
|
+
`)}function kE(e,t){return J(`comet.native.snapshot-policy.v1
|
|
152
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function ol(e,t,i){let n=new Set(t),r=[...t];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=e[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 EE(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Ip(e){let t=Xa(e,"Native snapshot pattern"),i=[];for(let n=0;n<t.length;n+=1){let r=t[n];r==="*"&&t[n+1]==="*"?(n+=1,t[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?EE(r):void 0;if(a&&!a())return!1;let o=ol(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=ol(i,c,a),o===null||o.size===0)return!1}return ol(i,o,a)?.has(i.length)??!1}}function zp(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>Xa(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>Xa(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let n=kE(t,i);if("hash"in e&&e.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:n},includeMatchers:t.map(Ip),excludeMatchers:i.map(Ip),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 CE(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function _p(e,t,i){if(!e)return!0;let n=()=>_(i),r=!1;for(let a of e.includeMatchers){if(!n())return!1;if(a(t,n)){r=!0;break}}if(!r)return!1;for(let a of e.excludeMatchers)if(!n()||a(t,n))return!1;return!0}function sl(e,t,i){let n=JSON.stringify(i);return J(`${e}
|
|
153
|
+
${Buffer.byteLength(t)}:${t}
|
|
154
|
+
${Buffer.byteLength(n)}:${n}`)}function ll(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Op(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!ll(i))return e.splice(t,1),i}return null}function Wt(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return de(i,n)?$(i,n):$(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function RE(e,t,i,n){if(!_(n))return{status:"budget-exhausted"};let r;try{r=await Z.open(e,"r")}catch(c){if(!_(n))return{status:"budget-exhausted"};throw c}if(!_(n))return await r.close(),{status:"budget-exhausted"};let a=co("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!_(n))return{status:"budget-exhausted"};let c=await r.stat();if(!_(n))return{status:"budget-exhausted"};if(!c.isFile()||!Wt(i,c))return{status:"changed"};for(;;){if(!_(n))return{status:"budget-exhausted"};let l=t+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()||!Wt(c,u)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:u}:{status:"budget-exhausted"}}if(s+f.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,f.bytesRead)),s+=f.bytesRead}}finally{await r.close()}}function De(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fe(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function Yi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ot(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Wp(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=q.posix.normalize(e);if(i!==e||q.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function PE(e,t){let i=De(e,`Native snapshot entry ${t}`);Fe(i,Gk,`Native snapshot entry ${t}`);let n=Wp(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!lo.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let r={path:n,hash:i.hash,size:ot(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Mp.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function AE(e,t){let i=De(e,`Native snapshot omission ${t}`);if(Fe(i,Yk,`Native snapshot omission ${t}`),!Zk.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!eE.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Wp(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:ot(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function xE(e){let t=De(e,"Native snapshot omission overflow");if(Fe(t,Xk,"Native snapshot omission overflow"),typeof t.hash!="string"||!lo.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:Yi(t.count,"Native snapshot omission overflow count")}}function Gi(e,t){let i=De(e,t);if(Fe(i,Jk,t),typeof i.hash!="string"||!lo.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let n=ot(i.recordCount,`${t} recordCount`),r=ot(i.storedRecordCount,`${t} storedRecordCount`),a=ot(i.stdoutBytes,`${t} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function jp(e){let t=De(e,"Native Git selection evidence");if(Fe(t,Wk,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=Gi(t.stageBefore,"Native Git selection stageBefore"),n=Gi(t.combined,"Native Git selection combined"),r=Gi(t.stageAfter,"Native Git selection stageAfter"),a=Gi(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Gi(t.finalCombined,"Native Git selection finalCombined"),s=Gi(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(u=>u.overflow),l=!Jt(i,r)||!Jt(r,a)||!Jt(n,o)||!Jt(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(t.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 $p(e,t){let i=De(e,t);if(Fe(i,Kk,t),typeof i.hash!="string"||!lo.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let n=ot(i.visitedNodeCount,`${t} visitedNodeCount`),r=ot(i.recordCount,`${t} recordCount`),a=ot(i.storedRecordCount,`${t} storedRecordCount`),o=ot(i.encodedBytes,`${t} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function TE(e){let t=De(e,"Native physical selection evidence");if(Fe(t,Uk,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=$p(t.before,"Native physical selection before"),n=$p(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!qp(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(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:n}}function or(e){let t=De(e,"Native content snapshot manifest");if(Fe(t,Fk,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Qk.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let g=De(t.capture,"Native content snapshot capture");if(Fe(g,Vk,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let k=g.gitSelection===void 0?void 0:jp(g.gitSelection),b=g.physicalSelection===void 0?void 0:TE(g.physicalSelection),C=null;if(g.projection!==void 0){let B=De(g.projection,"Native content snapshot projection");if(Fe(B,zk,"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:jp(B.selection)}}}if(g.provider==="git"){if(b||C)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...k?{gitSelection:k}:{}}}else{if(k)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&C)throw new Error("Native physical-tree capture cannot combine selection and projection");i=C?{provider:"physical-tree",projection:C}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=De(t.limits,"Native content snapshot limits");Fe(n,Bk,"Native content snapshot limits");let r={maxFiles:Yi(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Yi(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Yi(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Yi(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:Yi(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let g=De(t.policy,"Native snapshot policy");if(Fe(g,qk,"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=zp({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(PE),s=t.omitted.map(AE),c=ot(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:xE(t.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,k)=>g+k.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>Lp||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(t.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"),w=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...v,...w])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||w.length>1)throw new Error("Native physical selection omissions must not be duplicated");let S=i?.physicalSelection,N=S?.status==="overflow"||S?.status==="overflow-and-changed",y=S?.status==="changed"||S?.status==="overflow-and-changed";if(N!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(y!==(w.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Vp(E)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function IE(e,t){if(!Dk.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=q.join(e.changesDir,t);if(!G(e.changesDir,i))throw new Error("Native change path escaped");return q.join(i,"runtime","baseline-manifest.json")}async function Jp(e,t={}){let i={maxFiles:t.limits?.maxFiles??ao.maxFiles,maxFileBytes:t.limits?.maxFileBytes??ao.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??ao.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??ao.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=zp(t.policy),r=oE({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=lE(t.gitSelectionLimits),o=sE(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=q.resolve(e.projectRoot),c=await Z.realpath(s),l=q.resolve(e.nativeRoot),f=await Z.realpath(l),u=q.resolve(e.configFile),d=q.join(s,".comet","current-change.json"),p=SE(s,t.denylist??[]),m=[],h=[],v=new Map,w=new Map,S=0,N=0,y=J("comet.native.snapshot-omission-overflow.v1"),E=0,g=!1,k=null,b=P=>{N+=1,y=sl(y,"omission",P)},C=P=>{if(S+=1,h.length<Lp){h.push(P);return}if(ll(P)){let A=Op(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");b(A),h.push(P);return}b(P)},B=P=>{S+=P.count,N+=P.count,y=sl(y,"git-selection",{source:"git-selection",...P})},Y=P=>{N+=1,y=sl(y,"manifest-entry",{reason:"manifest-size",entry:P})},F=async(P,A)=>{m.push(P),E+=P.size,v.set(P.path,A),g||(g=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(P.path))},U=(P,A)=>{let T=m.findIndex(ee=>ee.path===P);if(T<0)return;let[j]=m.splice(T,1);E-=j.size,v.delete(P),C(A)},X=async(P,A,T,j)=>{if(!T.isFile()||T.isSymbolicLink()||!_(r))return;let ee;try{ee=await Z.realpath(P)}catch(I){if(!_(r))return;if(!re(I)&&!ne(I))throw I;C({path:A,size:T.size,type:"file",reason:ne(I)?"changed-during-read":"unreadable"});return}if(!_(r)||!G(c,ee)||Ut(f,ee))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 M,O,x;try{if(M=await RE(ee,T.size,T,r),M.status==="budget-exhausted"||!_(r))return;if(M.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!_(r)||(x=await Z.realpath(P),!_(r)))return;O=await Z.lstat(P)}catch(I){if(!_(r))return;if(!re(I)&&!ne(I))throw I;C({path:A,size:T.size,type:"file",reason:ne(I)?"changed-during-read":"unreadable"});return}if(_(r)){if(M.bytes!==T.size||x!==ee||!Wt(T,M.finalStat)||!Wt(M.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:M.hash,size:O.size,type:"file",...j===void 0?{}:{gitObjectId:j}},{kind:"file",target:P,realTarget:ee,stat:O})}},tt=async(P,A,T)=>{if(!_(r))return;let j,ee,M;try{if(j=await Z.readlink(P,{encoding:"buffer"}),!_(r)||(M=await Z.lstat(P),!_(r)))return;ee=await Z.readlink(P,{encoding:"buffer"})}catch(I){if(!_(r))return;if(!re(I)&&!ne(I))throw I;C({path:A,size:null,type:"other",reason:ne(I)?"changed-during-read":"unreadable"});return}if(!_(r))return;if(!M.isSymbolicLink()||!Wt(T,M)||M.mtimeMs!==T.mtimeMs||M.ctimeMs!==T.ctimeMs||!j.equals(ee)){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(E+O>i.maxTotalBytes){C({path:A,size:O,type:"other",reason:"total-size"});return}let x=co("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:M})},it=async()=>{for(let[P,A]of[...v]){if(!_(r))return;if(A.kind==="file"){let O,x;try{if(O=await Z.realpath(A.target),!_(r))return;x=await Z.lstat(A.target)}catch(I){if(!_(r))return;if(!re(I)&&!ne(I))throw I;U(P,{path:P,size:null,type:"file",reason:re(I)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(O!==A.realTarget||!x.isFile()||x.isSymbolicLink()||!Wt(A.stat,x)||x.size!==A.stat.size||x.mtimeMs!==A.stat.mtimeMs||x.ctimeMs!==A.stat.ctimeMs)&&U(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 Z.lstat(A.target),!_(r))return;x=await Z.readlink(A.target,{encoding:"buffer"})}catch(I){if(!_(r))return;if(!re(I)&&!ne(I))throw I;U(P,{path:P,size:null,type:"other",reason:re(I)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(!O.isSymbolicLink()||!Wt(A.stat,O)||O.mtimeMs!==A.stat.mtimeMs||O.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(x))&&U(P,{path:P,size:null,type:"other",reason:"changed-during-read"});continue}let T,j;try{if(T=await Z.realpath(A.target),!_(r))return;j=await Z.lstat(A.target)}catch{if(!_(r))return;U(P,{path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;if(!(T===A.realTarget&&j.isDirectory()&&!j.isSymbolicLink()&&Wt(A.stat,j)&&G(c,T)&&!Ut(f,T))){U(P,{path:P,size:null,type:"directory",reason:"gitlink-changed"});continue}let M;try{if(!_(r))return;M=await Tp(r,T)}catch(O){if(ar(O))throw O;U(P,{path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;M.dirty?U(P,{path:P,size:null,type:"directory",reason:"gitlink-dirty"}):M.hash!==A.hash&&U(P,{path:P,size:null,type:"directory",reason:"gitlink-changed"})}for(let[P,A]of w){if(!_(r))return;try{let T=await Z.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(ne(T))continue;if(!re(T))throw T;C({path:P,size:null,type:"file",reason:"unreadable"})}}},xe=await hE(r,s,a,t.gitSelectionHooks);if(xe===null){let P=await Ap({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:f,denylist:p,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let j of P.records){if(j.type!=="file"&&j.type!=="symlink"||v.has(j.path))continue;if(Ye(r)<1)break;if(!_p(n,j.path,r))continue;if(Ye(r)<1)break;let ee=q.resolve(s,...j.path.split("/")),M;try{M=await Z.lstat(ee)}catch(O){if(!_(r))break;if(!re(O)&&!ne(O))throw O;C({path:j.path,size:null,type:"file",reason:ne(O)?"changed-during-read":"unreadable"});continue}if(Ye(r)<1)break;if(j.type==="symlink"&&M.isSymbolicLink()){if(await tt(ee,j.path,M),Ye(r)<1)break;continue}if(j.type!=="file"||!M.isFile()||M.isSymbolicLink()){C({path:j.path,size:M.isFile()?M.size:null,type:M.isDirectory()?"directory":M.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await X(ee,j.path,M),Ye(r)<1)break}Ye(r)>=1&&await it();let A=await Ap({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:f,denylist:p,policy:n,limits:o}),T=wE(P.evidence,A.evidence);k=T.evidence;for(let j of[...P.omissions,...A.omissions,...T.omissions])h.some(ee=>ee.path===j.path&&ee.reason===j.reason)||C(j)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let P=t.incrementalBaseline,A=new Map,T=!1;if(P){let x=or(P);for(let I of x.entries)I.gitObjectId!==void 0&&A.set(I.path,I);T=A.size>0}let j=new Set,ee=!0;try{let x=await oo(r,s,["ls-files","--modified","-z"],cl);for(let I of x.toString("utf8").split("\0")){let se=so(I);se!==null&&j.add(se)}}catch{T=!1,ee=!1,A.clear()}let M=new Set,O=new Set;for(let x of yE(xe)){if(v.has(x)||!NE(e,x))continue;if(Ye(r)<1)break;if(!_p(n,x,r))continue;if(Ye(r)<1)break;let I=q.resolve(s,...x.split("/"));if(I===u||I===d||p.some(Ie=>Ut(Ie,I)))continue;if(xe.gitlinks.has(x)){if(m.length>=i.maxFiles){C({path:x,size:0,type:"file",reason:"file-count"});continue}let Ie,Lr;try{[Ie,Lr]=await Promise.all([Z.realpath(I),Z.lstat(I)])}catch{C({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Lr.isSymbolicLink()||!Lr.isDirectory()||!G(c,Ie)||Ut(f,Ie)){C({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Ri=await Tp(r,Ie);if(Ri.dirty){C({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await F({path:x,hash:Ri.hash,size:0,type:"file"},{kind:"gitlink",target:I,realTarget:Ie,stat:Lr,hash:Ri.hash})}catch(Ri){if(ar(Ri))throw Ri;C({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let se;try{se=await Z.lstat(I)}catch(Ie){if(ne(Ie)&&xe.tracked.has(x)){w.set(x,I);continue}if(!re(Ie)&&!ne(Ie))throw Ie;C({path:x,size:null,type:"file",reason:ne(Ie)?"changed-during-read":"unreadable"});continue}if(se.isSymbolicLink()){await tt(I,x,se);continue}if(!se.isFile()){xe.nestedRepositories.has(x)||C({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let Ve=xe.trackedObjectIds.get(x),Te=Ve?A.get(x):void 0;if(T&&Te?.gitObjectId!==void 0&&Te.gitObjectId===Ve&&!j.has(x)){if(m.length>=i.maxFiles){C({path:x,size:Te.size,type:"file",reason:"file-count"});continue}if(Te.size>i.maxFileBytes){C({path:x,size:Te.size,type:"file",reason:"file-size"});continue}if(E+Te.size>i.maxTotalBytes){C({path:x,size:Te.size,type:"file",reason:"total-size"});continue}m.push({...Te}),E+=Te.size,M.add(x);continue}let _u=ee&&!j.has(x)?Ve:void 0;await X(I,x,se,_u),_u!==void 0&&O.add(x)}if(await it(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await mE(r,s,a,xe,t.gitSelectionHooks?.outputChunkBytes),M.size>0||T&&O.size>0){let x=await oo(r,s,["ls-files","--modified","-z"],cl),I=new Set;for(let se of x.toString("utf8").split("\0")){let Ve=so(se);Ve!==null&&I.add(Ve)}for(let se of M){if(!I.has(se))continue;let Ve=m.find(Te=>Te.path===se);U(se,{path:se,size:Ve?.size??null,type:"file",reason:"changed-during-read"})}for(let se of O){if(!I.has(se))continue;let Ve=m.find(Te=>Te.path===se);Ve&&delete Ve.gitObjectId}}for(let x of xe.omissions)C(x);xe.overflow&&B(xe.overflow)}m.sort((P,A)=>P.path.localeCompare(A.path,"en")),h.sort((P,A)=>P.path.localeCompare(A.path,"en"));let Hg=xe===null?{provider:"physical-tree",...k?{physicalSelection:k}:{}}:{provider:"git",...xe.evidence?{gitSelection:xe.evidence}:{}},Iu=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:Hg,createdAt:(t.now??new Date).toISOString(),complete:S===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:S,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${y}`,hash:y,count:N}}:{}}),Uo=Iu();for(;Vp(Uo)>i.maxManifestBytes;){if(h.filter(A=>!ll(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let j=Op(h);if(j===null)break;b(j)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))S+=1,Y(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Uo=Iu()}return Uo}async function fl(e,t,i={}){let r=(await Bt(e.projectRoot))?.native.snapshot??Jc;return Jp(e,{...i,policy:t.policy,incrementalBaseline:t,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 Up(e,t){let i=IE(e,t);await H(e.nativeRoot,i);try{let n=await op({root:e.nativeRoot,file:i,maxBytes:Mk,label:"Native baseline snapshot manifest"});return or(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as KE}from"crypto";import vl from"path";var st=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 fo,promises as we}from"node:fs";import je from"node:path";import{TextDecoder as qE}from"node:util";import ME from"path";var Kp=(e,t)=>{let i=e[t];return i==null?null:String(i)};function cr(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function sr(e,t){let i=cr(e,t);if(ME.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function DE(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}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 Gp(e){if(!e.run_id)return null;let t=cr(e,"run_id"),i=cr(e,"skill"),n=cr(e,"skill_version"),r=cr(e,"skill_hash"),a=sr(e,"pending_ref"),o=sr(e,"trajectory_ref"),s=sr(e,"context_ref"),c=sr(e,"artifacts_ref"),l=sr(e,"checkpoint_ref"),f=Number(e.iteration);if(!Number.isInteger(f)||f<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:n,skillHash:r,orchestration:e.orchestration,currentStep:Kp(e,"current_step"),iteration:f,pending:Kp(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:DE(e)}}var qO=256*1024;var FE=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function BE(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=Gp(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function uo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(n=>!FE.has(n));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return BE(t)}var Oe={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 ur(e,t){let i=je.relative(e,t);return i===""||!je.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${je.sep}`)}function Xp(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function lr(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function VE(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Qi(e,t,i){let n=st[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=je.resolve(e),a=je.resolve(r,...n.split("/"));if(!ur(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Yp(e){let t=await we.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await we.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function dl(e,t){let i=je.resolve(e),n=je.resolve(t);if(!ur(i,n))throw new Error("Native Run path is outside its change");let r=[await Yp(i)],a=i;for(let o of je.relative(i,n).split(je.sep).filter(Boolean)){a=je.join(a,o);let s;try{s=await Yp(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!ur(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function ho(e){for(let t of e){let i=await we.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!VE(t,i)||await we.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function zE(e,t,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-r,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>t)throw new Error(`${i} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function fr(e,t,i,n,r){let a=await dl(e,je.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await we.lstat(t)}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=Xp(o),c=await we.realpath(t);if(!ur(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?fo.O_RDONLY:fo.O_RDONLY|fo.O_NOFOLLOW|fo.O_NONBLOCK,f;try{f=await we.open(t,l)}catch(u){throw new Error(`${n} changed while opening`,{cause:u})}try{let[u,d,p]=await Promise.all([f.stat(),we.lstat(t),we.realpath(t)]);if(await ho(a),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==c||!lr(s,u)||!lr(s,d))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await zE(f,i,n);await r?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([f.stat(),we.lstat(t),we.realpath(t)]);if(await ho(a),!v.isFile()||v.isSymbolicLink()||w!==c||!lr(s,h)||!lr(s,v))throw new Error(`${n} changed while reading`);let S;try{S=new qE("utf-8",{fatal:!0}).decode(m)}catch(N){throw new Error(`${n} is not valid UTF-8`,{cause:N})}return{text:S,target:{exists:!0,identity:s,realPath:c}}}finally{await f.close()}}async function WE(e,t,i){let n=await dl(e,je.dirname(t));if(!n)return{exists:!1};let r;try{r=await we.lstat(t)}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 we.realpath(t);if(!ur(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await ho(n),{exists:!0,identity:Xp(r),realPath:a}}async function JE(e,t,i,n){let r=await dl(e,je.dirname(t));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await we.lstat(t)}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()||!lr(i.identity,a)||await we.realpath(t)!==i.realPath)throw new Error(`${n} changed before commit`);await ho(r)}async function hl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await WE(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await pt(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await JE(e.changeDir,e.file,i,e.label)}});let n=await fr(e.changeDir,e.file,e.maxBytes,e.label);if(!n||n.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function UE(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Qp(e){return`${JSON.stringify(e,null,2)}
|
|
155
|
+
`}function pl(e){return uo(e)}async function Zi(e,t){let i=Qi(e,"stateRef"),n=await fr(e,i,Oe.runStateBytes,"Native Run state",t);return n?uo(UE(n.text,"Native Run state")):null}async function po(e,t,i){let n=uo(t);await hl({changeDir:e,file:Qi(e,"stateRef"),content:Qp(n),maxBytes:Oe.runStateBytes,label:"Native Run state",hooks:i})}async function pi(e,t,i){let n=Qi(e,"trajectoryRef",t),r=await fr(e,n,Oe.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>Oe.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Oe.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 Zp(e,t,i){return(await fr(e,Qi(e,"trajectoryRef",t),Oe.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function em(e,t,i,n){let r=Qi(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
|
|
156
|
+
`;if(Buffer.byteLength(a,"utf8")>Oe.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Oe.trajectoryEventBytes} bytes`);let o=await fr(e,r,Oe.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Oe.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Oe.trajectoryEvents} events`);await hl({changeDir:e,file:r,content:`${o?.text??""}${a}`,maxBytes:Oe.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function tm(e,t,i,n){await hl({changeDir:e,file:Qi(e,"checkpointRef",t),content:Qp(i),maxBytes:Oe.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var GE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gl=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 ml(e){return KE("sha256").update(e).digest("hex")}function YE(e,t){if(!GE.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=vl.join(e.changesDir,t);if(!G(e.changesDir,i))throw new Error("Native change path escaped");return vl.join(i,"runtime","trajectory.jsonl")}function XE(e){let t=e.split(/\n/u),i=0;for(let n=0;n<t.length;n+=1){let r=t[n].endsWith("\r")?t[n].slice(0,-1):t[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 QE(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function ZE(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=XE(n.toString("utf8"));if(r.status==="invalid")return{status:"invalid",file:e,line:r.line,message:r.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.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([t,Buffer.from(`
|
|
157
|
+
`)])}catch(u){if(!QE(u,o))return{status:"invalid",file:e,line:s,message:u.message};c="incomplete-json",l=n}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:ml(t),targetHash:ml(l),tailHash:ml(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function eC(e,t){let i=YE(e,t);await H(e.nativeRoot,i);let n=vl.join(e.changesDir,t),r=await Zp(n,st.trajectoryRef);return r===null?{status:"clean",file:i}:ZE(i,Buffer.from(r))}async function tC(e,t){let i=await eC(e,t);return"inspection"in i?i.inspection:i}async function mo(e,t){let i=await tC(e,t);if(i.status!=="clean")throw new gl(i)}import en from"node:path";var dr=/^[a-f0-9]{64}$/u,iC=16*1024,nC=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function im(e){return nC.has(e)}function rC(e,t){let i=en.relative(e,t);return en.isAbsolute(i)||i===".."||i.startsWith(`..${en.sep}`)?null:i.replaceAll("\\","/")||"."}function aC(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function nm(e,t){if(e.length===0||aC(e)||e.includes("\\")||en.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=en.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function oC(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function sC(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash"]),n=Object.keys(t).filter(o=>!i.has(o));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(t.schema!=="comet.native.workspace.v2")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!dr.test(String(t.projectRootId))||!dr.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");oC(t.capturedAt),nm(t.nativeRootRef,"Native workspace root ref");let r=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(r!==a)throw new Error("Native workspace path identities must be provided together");if(r&&!dr.test(String(t.projectRootPathId))||a&&!dr.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!dr.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid")}function cC(e,t){return en.join(e.changesDir,t,"runtime","workspace.json")}function lC(e,t){let i=rC(e.nativeRoot,cC(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return nm(i,"Native workspace file ref")}async function uC(e,t){try{let i=await me({root:e.nativeRoot,ref:lC(e,t),maxBytes:iC});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function rm(e,t){let i=await uC(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(sC(i),i)}var Kt="comet.native.v3",mi="comet.native.v2",vi="comet.native.v1",tn="comet.native.transition.v3",nn="comet.native.transition.v2",hr="comet.native.transition.v1";var om=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],fC=new Set(om),sm=new Set([...om,"minimum_runtime_version","revision"]),dC=new Set([...sm,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),hC=new Set(["capability","operation","source","base_hash"]),pC=new Set(["shape","build","verify","archive"]),mC=new Set(["implicit","confirmed"]),vC=new Set(["pending","pass","fail"]),wt="comet-state.yaml",Nl=/^[a-f0-9]{64}$/u,cm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gC=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,pr=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"},gi=class extends Error{constructor(i,n){super(i!==Kt||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"},mr=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"},vo=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"},Oj=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
158
|
+
`);function gr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function lm(e,t,i){let n=Object.keys(e).filter(r=>!t.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function bl(e){if(!cm.test(e))throw new Error(`Invalid Native change name: ${e}`)}function wC(e){if(!cm.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function um(e,t){if(e.length===0||gt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function yC(e,t){let i=gr(e,`spec_changes[${t}]`);if(lm(i,hC,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(wC(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"&&um(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"||!Nl.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"||!Nl.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 NC(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Sl(e,t){if(lm(e,t,wt),typeof e.name!="string")throw new Error("Native change name is required");if(bl(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!pC.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!mC.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(yC),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 e.verification_result!="string"||!vC.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&um(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!NC(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function wr(e){let t=gr(e,wt);if(t.schema!==vi)throw new Error(`Expected ${vi}`);return{schema:vi,...Sl(t,fC)}}function vr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function wl(e,t,i){if(e===null)return null;let n=typeof e=="string"?gC.exec(e):null;if(!n||n[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function bC(e){if(e==null)return null;if(typeof e!="string"||!Nl.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function SC(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function yr(e){let t=gr(e,wt);if(t.schema!==mi)throw new Error(`Expected ${mi}`);if(vr(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${mi} minimum_runtime_version must be 2`);return{schema:mi,minimum_runtime_version:2,revision:vr(t.revision,"Native v2 revision"),...Sl(t,sm)}}function ct(e){let t=gr(e,wt);if(t.schema!==Kt){if(t.schema===vi||t.schema===mi){let o=t.schema===vi?wr(t):yr(t);throw new pr(o.name,o.schema)}throw new gi(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=vr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new gi(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=vr(t.revision,"Native revision"),r=Sl(t,dC),a=bC(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Kt,minimum_runtime_version:3,revision:n,verification_protocol:SC(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:wl(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:wl(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:wl(t.partial_allowance,"Native partial_allowance","allowances")}}function kC(e){let t=gr(e,wt);if(t.schema===vi){let r=wr(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Kt}`}}if(t.schema===mi){let r=yr(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Kt}`}}if(t.schema!==Kt){let r=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new gi(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=vr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new gi(t.schema,i).message};let n=ct(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function yl(e){let t=ct(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function W(e,t){bl(t);let i=gt.join(e.changesDir,t);if(!G(e.changesDir,i))throw new Error("Native change path escaped");return i}async function rn(e,t){let i=gt.join(W(e,t),"runtime","schema-migration.json");await H(e.nativeRoot,i);try{return await am.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function kl(e,t){let i=gt.join(W(e,t),"runtime","checkpoint-journal.json");await H(e.nativeRoot,i);try{return await am.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var EC=256*1024;async function El(e,t=gt.dirname(e)){let i=gt.relative(t,e).split(gt.sep).join("/"),n=await me({root:t,ref:i,maxBytes:EC}),r=(0,go.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${r.errors[0].message}`);return r.toJS()}async function CC(e,t){let i=gt.join(W(e,t),wt);await H(e.nativeRoot,i);let n=kC(await El(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await rn(e,t)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(n.status==="current"&&n.state&&await RC(e,n.state),n)}async function RC(e,t){if(await Up(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function ue(e,t){let i=await CC(e,t);if(i.status==="migration-required")throw new pr(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new gi(i.schema,i.minimumRuntimeVersion);return i.state}async function fm(e,t,i){let n={...t,schema:Kt,minimum_runtime_version:3,revision:i+1},r=await Ep({expectedRevision:i,next:n,read:async()=>{let a=ct(await El(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>pt(e,(0,go.stringify)(yl(a))),equals:(a,o)=>JSON.stringify(yl(a))===JSON.stringify(yl(o)),conflict:a=>new mr(t.name,i,a)});return Object.assign(t,r),r}async function wo(e,t,i,n){if(await Fi(e.projectRoot),await rn(e,t.name))throw new pr(t.name,t.schema);if(!n?.allowPendingCheckpointRecovery&&await kl(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await ue(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await mo(e,t.name);let a=gt.join(W(e,t.name),wt);return await H(e.nativeRoot,a),fm(a,t,i)}async function dm(e,t){return fm(e,t,t.revision)}async function hm(e){return ct(await El(e))}var mm=["Outcome","Scope","Non-goals","Acceptance examples"],PC=[...mm,"Constraints and invariants","Decisions","Open questions","Verification expectations"],AC=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],vm={maxFileBytes:Jn};function gm(e){let t=new Map,i=null,n=[],r=()=>{i!==null&&t.set(i,n.join(`
|
|
159
|
+
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(r(),i=o[1].trim(),n=[]):i!==null&&n.push(a)}return r(),t}async function xC(e,t){let i=pm.resolve(e,...t.split(/[\\/]/u));if(!G(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await Cl.realpath(e),r=await Cl.realpath(i);if(!G(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Cl.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function yo(e){return{valid:e.length===0,findings:e}}async function wm(e,t){let i=[],n;try{n=(await me({root:e,ref:t,maxBytes:vm.maxFileBytes})).text}catch(o){return yo([{code:"brief-missing",message:o.message,path:t}])}let r=gm(n);for(let o of PC)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of mm)(r.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=r.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),yo(i)}async function ym(e,t){let i=[],n;try{n=(await me({root:e,ref:t,maxBytes:vm.maxFileBytes})).text}catch(a){return yo([{code:"verification-missing",message:a.message,path:t}])}let r=gm(n);for(let a of AC)r.has(a)?(r.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return yo(i)}function Nr(e,t){return pm.join(e.specsDir,t,"spec.md")}async function Nm(e,t){return xC(e,t)}import{promises as BA}from"node:fs";import og from"node:path";import bm from"node:path";import{createHash as TC}from"crypto";function Xe(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function IC(e,t){t.has(e)&&Xe("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let n=0;n<e.length;n+=1)Object.prototype.hasOwnProperty.call(e,n)||Xe("sparse arrays are not supported");return(i.length!==e.length||i.some((n,r)=>n!==String(r)))&&Xe("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Xe("symbol properties are not supported"),`[${e.map(n=>Rl(n,t)).join(",")}]`}finally{t.delete(e)}}function _C(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Xe("only plain objects are supported"),t.has(e)&&Xe("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Xe("symbol properties are not supported"),t.add(e);try{let n=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&Xe("accessor properties are not supported"),`${JSON.stringify(o)}:${Rl(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Rl(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Xe("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?IC(e,t):_C(e,t);case"bigint":case"function":case"symbol":case"undefined":return Xe(`${typeof e} values are not supported`)}return Xe("unsupported value type")}function br(e){return Rl(e,new Set)}function D(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return TC("sha256").update(`${e}
|
|
160
|
+
${br(t)}`).digest("hex")}var OC="comet.native.archive-preflight.v1",jC="comet.native.archive-preflight.v1",$C="comet.native.archive-operation.v1",HC=/^[a-f0-9]{64}$/u,Sm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function No(e,t){return e<t?-1:e>t?1:0}function MC(e,t){if(typeof e!="string"||!HC.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yt(e,t){return e===null?null:MC(e,t)}function DC(e,t){let i=bm.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||bm.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function FC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function BC(e,t){if(!Sm.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=yt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=yt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=yt(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(r===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:n,proposedHash:r}}function qC(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:yt(e.contractHash,"Native archive contract hash"),acceptanceHash:yt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:yt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:yt(e.reportHash,"Native archive report hash"),envelopeHash:yt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:yt(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function VC(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!LC.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(No);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function zC(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(No)}function km(e){if(!Sm.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(BC).sort((c,l)=>No(c.capability,l.capability));if(new Set(t.map(c=>c.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(c=>({...c,operationHash:D($C,c)})),n=qC(e.evidence),r=[...new Set([...VC(e.findingCodes??[]),...zC({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(No),a=FC(e.revision),o=DC(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let s={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:a,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:o,targetExists:e.targetExists,operations:i,evidence:n,findingCodes:r};return{schema:OC,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:a,targetRef:o,ready:r.length===0,evidenceFreshness:n.freshness,operationCount:i.length,operations:i,findingCodes:r,preflightHash:D(jC,s)}}import{createHash as WC}from"node:crypto";import Em from"node:path";var JC="comet.native.conflict-radar.v1",Ce=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512}),UC="comet.native.conflict-radar.v1",KC="comet.native.conflict-radar-signals.v1",GC=/^[a-f0-9]{64}$/u,Pm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,YC=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),XC=new Set(["capability","operation","baseHash"]),QC=new Set(["path","kind"]);function an(e,t){return e<t?-1:e>t?1:0}function Pl(e){return Buffer.byteLength(e,"utf8")}function Al(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let n=e,r=Object.keys(n).filter(a=>!t.has(a));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);return n}function xl(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Pl(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function ZC(e,t){let i=xl(e,t,Ce.maxArtifactPathBytes),n=Em.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||Em.posix.isAbsolute(n)||i.split("/").includes("..")||n!==i||n==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Am(e,t){if(typeof e!="string"||!GC.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function eR(e,t){let i=Al(e,XC,t),n=xl(i.capability,`${t} capability`,Ce.maxCapabilityBytes);if(!Pm.test(n))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let r=i.baseHash===null?null:Am(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&r!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&r===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:n,operation:i.operation,baseHash:r}}function tR(e,t){let i=Al(e,QC,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:ZC(i.path,`${t} path`),kind:i.kind}}function iR(e,t){let i=Al(e,YC,`Conflict radar change ${t}`),n=xl(i.name,`Conflict radar change ${t} name`,Ce.maxNameBytes);if(!Pm.test(n))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${n} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${n} specs must be an array`);if(i.specs.length>Ce.maxSpecsPerChange)throw new Error(`Conflict radar change ${n} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${n} declared artifacts must be an array`);if(i.declaredArtifacts.length>Ce.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>eR(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>an(c.capability,l.capability));if(new Set(r.map(c=>c.capability)).size!==r.length)throw new Error(`Conflict radar change ${n} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>tR(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>an(c.path,l.path)||an(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${n} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:Am(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function nR(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Ce.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(iR).sort((r,a)=>an(r.name,a.name));if(new Set(t.map(r=>r.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((r,a)=>r+a.specs.length,0)>Ce.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>Ce.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function rR(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function aR(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),n=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),r=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!n&&!r?null:{kind:"artifact",certainty:r?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function oR(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function sR(e,t){let i=[],n=WC("sha256").update(`${KC}
|
|
161
|
+
[`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(br(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Ce.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let f=s.get(l.capability);f&&o(rR(l,f))}for(let l of e.declaredArtifacts)for(let f of t.declaredArtifacts){let u=aR(l,f);u&&o(u)}let c=a?"definite-conflict":r>0?"possible-overlap":"disjoint";return n.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:oR(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function Cm(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function cR(e,t){return Cm(e.classification)-Cm(t.classification)||an(e.left,t.left)||an(e.right,t.right)}function Rm(e,t,i,n){let r={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:JC,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:r,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:n}}function Tl(e){let t=nR(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(sR(t[s],t[c]));i.sort(cR);let n=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),r=D(UC,{changes:t,relationships:n}),a=i.slice(0,Ce.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Rm(t,i,a,r);for(;a.length>0&&Pl(JSON.stringify(o))>Ce.maxSerializedBytes;)a=a.slice(0,-1),o=Rm(t,i,a,r);if(Pl(JSON.stringify(o))>Ce.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as yP}from"node:crypto";import{promises as et}from"node:fs";import lt from"node:path";import{createHash as $m}from"node:crypto";import xm from"path";var Il="comet.native.implementation-scope.v2",Hm="comet.native.content-snapshot-projection.v1",Sr="comet.native.content-snapshot-projection.v1",Lm="comet.native.implementation-scope.v2",lR="comet.native.unresolved-scope-id.v1",uR="comet.native.scope-detail-overflow.v1",fR="comet.native.snapshot-projection-overflow.v2",$l=/^[a-f0-9]{64}$/u,yi=1024*1024,dR=128,hR=128;function pe(e,t){return e<t?-1:e>t?1:0}function _l(e){if(!$l.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function pR(e,t){return e===t?0:e===null?-1:t===null?1:pe(e,t)}function Yt(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=xm.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||xm.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Mm(e,t){return e==="."?e:Yt(e,t)}function on(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function mR(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:Yt(e.path,`${t} path`),hash:e.hash,size:on(e.size,`${t} size`),type:"file"}}function vR(e,t){return{path:Mm(e.path,`${t} path`),size:e.size===null?null:on(e.size,`${t} size`),type:e.type,reason:e.reason}}function gR(e,t){return pe(e.path,t.path)||pe(e.hash,t.hash)||e.size-t.size}function wR(e,t){return pe(e.path,t.path)||pe(e.reason,t.reason)||pe(e.type,t.type)||(e.size??-1)-(t.size??-1)}function kr(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
162
|
+
`,"utf8")}function Gt(e,t,i){let n=`${t}
|
|
163
|
+
${br(i)}`;e.update(`${Buffer.byteLength(n,"utf8")}:`),e.update(n)}function yR(e){if(kr(e)<=yi)return e;let t=[...e.entries],i=[...e.omitted],n=e.omittedCount,r=e.omissionOverflow?.count??0,a=$m("sha256");a.update(`${fR}
|
|
164
|
+
`),e.omissionOverflow&&Gt(a,"existing-overflow",e.omissionOverflow);let o=(d,p)=>{p||(n+=1),r+=1,Gt(a,"omission",d)},s=d=>{n+=1,r+=1,Gt(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=()=>({...e,complete:n===0,entries:t,omitted:i,omittedCount:n,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:r}}),f=l();for(;kr(f)>yi;){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(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let m of t.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 Ol(e){let t=or(e),i=t.entries.map((r,a)=>mR(r,`Snapshot entry ${a}`));if(i.sort(gR),new Set(i.map(r=>r.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let n=t.omitted.map((r,a)=>vR(r,`Snapshot omission ${a}`));return n.sort(wR),yR({schema:Hm,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:n,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function ko(e){let t=new Map;for(let[i,n]of e.entries()){if(n.kind!=="file"&&n.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let r={path:Yt(n.path,`Declared artifact ${i} path`),kind:n.kind},a=t.get(r.path);if(a&&a.kind!==r.kind)throw new Error(`Declared artifact path has conflicting kinds: ${r.path}`);t.set(r.path,r)}return[...t.values()].sort((i,n)=>pe(i.path,n.path)||pe(i.kind,n.kind))}function Eo(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Tm(e){return e?{hash:e.hash,size:e.size}:null}function Dm(e,t,i){let n=0,r=0;for(;n<e.entries.length||r<t.entries.length;){let a=e.entries[n],o=t.entries[r],s=a===void 0?1:o===void 0?-1:pe(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&&!t.complete)continue;let f=c?.path??l?.path;f!==void 0&&i({path:f,kind:c?l?"modified":"removed":"added",before:Tm(c),after:Tm(l)})}}function NR(e,t){return{...e,attributedTo:t.filter(i=>Eo(i,e.path))}}function Nt(e,t){return{id:`scope:${D(lR,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function bR(e,t){let i=t.omitted.map(n=>Nt({kind:"snapshot-omission",source:e,path:n.path,evidence:{reason:n.reason,size:n.size,type:n.type}},`${e} snapshot omitted ${n.path}: ${n.reason}`));return t.complete||i.push(Nt({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Nt({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function Im(e,t){return bR(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function jl(e,t){return pe(e.kind,t.kind)||pe(e.source,t.source)||pR(e.path,t.path)||pe(e.id,t.id)}function SR(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(jl)}function kR(e){return[...new Set(e.map((t,i)=>Yt(t,`Git path ${i}`)))].sort(pe)}function Fm(e){if(typeof e.contractHash!="string"||!$l.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:ko(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:kR(e.gitChangedPaths)}}}function ER(e,t,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,f=0;return Dm(e,t,u=>{let d=i.some(p=>Eo(p,u.path));if(l+=1,d||(f+=1),a?.has(u.path)&&o.push(u.path),!c&&r.length<dR){let p=NR(u,i),m=kr(p);s+m<=yi?(r.push(p),s+=m):c=!0}}),{candidates:r,gitPathsPresentInChanges:o,totalChanges:l,totalUnattributed:f}}function Bm(e,t){return Nt({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function CR(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let i={changes:on(Number(t[1]),"Scope overflow change count"),unresolved:on(Number(t[2]),"Scope overflow unresolved count"),unattributed:on(Number(t[3]),"Scope overflow unattributed count")},n=wi(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Bm(n,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:n}}function RR(e){let t=$m("sha256");t.update(`${uR}
|
|
165
|
+
`);let i=0;Dm(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){Gt(t,"change",r);let a=0;for(let o of e.declaredArtifacts)Eo(o,r.path)&&(a+=1,Gt(t,"change-attribution",o));Gt(t,"change-end",{attributionCount:a}),a===0&&Gt(t,"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",e.baseline],["current",e.current]])for(let o of a.omitted)n>=e.detailedOmissionCount&&Gt(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function qm(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=ER(e,t,r,i.gitChangedPaths),s=D(Sr,e),c=D(Sr,t),l=[];for(let[g,k]of[["baseline",e],["current",t]])for(let b of k.omitted){if(l.length>=hR)break;l.push(Nt({kind:"snapshot-omission",source:g,path:b.path,evidence:{reason:b.reason,size:b.size,type:b.type}},`${g} snapshot omitted ${b.path}: ${b.reason}`))}let f=e.omitted.length+t.omitted.length,u=[...Im("baseline",e),...Im("current",t),...o.totalChanges===0&&a===null?[Nt({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(k=>g.has(k)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(k=>!g.has(k))}},p=g=>{let k=o.candidates.slice(0,g.detailedChangeCount),b=k.filter(it=>it.attributedTo.length===0),C=o.totalChanges-k.length,B=o.totalUnattributed-b.length,Y=f-g.detailedOmissionCount,F=B+Y,U=[...b.map(it=>Nt({kind:"unattributed-change",source:"implementation-scope",path:it.path,evidence:{after:it.after,before:it.before,changeKind:it.kind}},`Changed path is not covered by a declared artifact: ${it.path}`)),...l.slice(0,g.detailedOmissionCount),...u,...C>0||F>0?[Bm(g.overflowHash,{changes:C,unattributed:B,unresolved:F})]:[]],X=SR(U),tt=g.includeGitAdvisory?d():void 0;return{schema:Il,contractHash:n,baselineProjectionRef:_l(s),baselineProjectionHash:s,currentProjectionRef:_l(c),currentProjectionHash:c,complete:X.length===0,declaredArtifacts:r,changes:k,unattributed:b,unresolvedScopes:X,noCodeReason:a,...tt?{gitAdvisory:tt}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let g=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:w});if(kr({...g,scopeHash:w})<=yi)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 N=o.totalChanges>m||f>h?RR({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):w,y=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:N}),E={...y,scopeHash:D(Lm,y)};if(kr(E)>yi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return E}function Hl(e){let t=Ol(e.baseline),i=Ol(e.current),n=Fm(e);return{authority:n,baseline:t,current:i,scope:qm(t,i,n)}}var PR=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function bt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function St(e,t,i,n){let r=new Set([...t,...i]),a=Object.keys(e).filter(s=>!r.has(s)),o=t.filter(s=>!(s in e));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 wi(e,t){if(typeof e!="string"||!$l.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function _m(e,t,i){let n=_l(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function So(e,t){let i=bt(e,"Native snapshot projection");if(St(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Hm)throw new Error("Native snapshot projection schema is invalid");let n=or({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=Ol(n);if(D(Sr,i)!==D(Sr,r))throw new Error("Native snapshot projection is not canonical");let a=D(Sr,r);if(t!==void 0&&wi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function Ll(e,t){let i=bt(e,`Declared artifact ${t}`);if(St(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Yt(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Om(e,t){if(e===null)return null;let i=bt(e,t);return St(i,["hash","size"],[],t),{hash:wi(i.hash,`${t} hash`),size:on(i.size,`${t} size`)}}function jm(e,t){let i=bt(e,`Implementation change ${t}`);if(St(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let n=i.attributedTo.map(Ll),r=ko(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Om(i.before,`Implementation change ${t} before`),o=Om(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:Yt(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function AR(e,t){let i=bt(e,`Unresolved scope ${t}`);St(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);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 ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Mm(i.path,`Unresolved scope ${t} path`):Yt(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function bo(e,t){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((r,a)=>Yt(r,`${t} ${a}`)),n=[...new Set(i)].sort(pe);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function Co(e){let t=bt(e,"Native implementation scope"),i=[...PR].filter(k=>k!=="gitAdvisory");if(St(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==Il)throw new Error("Native implementation scope schema is invalid");let n=wi(t.contractHash,"Implementation scope contractHash"),r=wi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=_m(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=wi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=_m(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Ll);if(JSON.stringify(c)!==JSON.stringify(ko(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(jm),f=[...l].sort((k,b)=>pe(k.path,b.path));if(JSON.stringify(l)!==JSON.stringify(f)||new Set(l.map(k=>k.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let u=new Set(c.map(k=>`${k.kind}:${k.path}`));if(l.some(k=>k.attributedTo.some(b=>!u.has(`${b.kind}:${b.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(k=>JSON.stringify(k.attributedTo)!==JSON.stringify(c.filter(b=>Eo(b,k.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=t.unattributed.map(jm),p=l.filter(k=>k.attributedTo.length===0);if(JSON.stringify(d)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(AR),h=m.filter(k=>k.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:CR(h[0]);if(v&&(v.changes+v.unresolved===0||v.unattributed>v.changes||v.unattributed>v.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let w=t.noCodeReason,S=[...p.map(k=>Nt({kind:"unattributed-change",source:"implementation-scope",path:k.path,evidence:{after:k.after,before:k.before,changeKind:k.kind}},`Changed path is not covered by a declared artifact: ${k.path}`)),...l.length+(v?.changes??0)===0&&w===null?[Nt({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")]:[]],N=m.filter(k=>k.kind==="unattributed-change"||k.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(jl))||new Set(m.map(k=>k.id)).size!==m.length||JSON.stringify(N)!==JSON.stringify(S.sort(jl))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let y;if(t.gitAdvisory!==void 0){let k=bt(t.gitAdvisory,"Implementation scope Git advisory");if(St(k,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),k.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let b=bo(k.changedPaths,"Git changed paths"),C=bo(k.pathsPresentInSnapshotChanges,"Git present paths"),B=bo(k.pathsAbsentFromSnapshotChanges,"Git absent paths"),Y=[...C,...B].sort(pe),F=new Set(l.map(U=>U.path));if(JSON.stringify(Y)!==JSON.stringify(b)||(v?.changes??0)===0&&C.some(U=>!F.has(U))||B.some(U=>F.has(U)))throw new Error("Implementation scope Git advisory partition is invalid");y={advisoryOnly:!0,changedPaths:b,pathsPresentInSnapshotChanges:C,pathsAbsentFromSnapshotChanges:B}}let E={schema:Il,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:m,noCodeReason:w,...y?{gitAdvisory:y}:{}},g=wi(t.scopeHash,"Implementation scope scopeHash");if(D(Lm,E)!==g)throw new Error("Implementation scope content hash mismatch");return{...E,scopeHash:g}}function xR(e){let t=bt(e,"Native implementation scope authority");if(St(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Ll);if(JSON.stringify(i)!==JSON.stringify(ko(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let n;t.gitChangedPaths!==void 0&&(n=bo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=Fm({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...n===void 0?{}:{gitChangedPaths:n}});if(r.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return r}function Ro(e){let t=bt(e,"Native implementation scope bundle");St(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=xR(t.authority),n=So(t.baseline),r=So(t.current),a=Co(t.scope),o=qm(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 Vm(e){let t=Co(e.scope);return Ro({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{}},baseline:e.baseline,current:e.current,scope:t})}import zm from"node:path";var TR=/\b(Bearer|Basic)\s+[^\s"']+/giu,IR=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,_R=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,OR=/\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,jR=/("(?:[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,$R=/(["'])((?:[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,HR=/\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(e){return e.replace(TR,"$1 [REDACTED]").replace(IR,"[REDACTED PRIVATE KEY]").replace(_R,"$1[REDACTED]@").replace(OR,"[REDACTED TOKEN]").replace(jR,'$1"[REDACTED]"').replace($R,"$1$2$1$3$4[REDACTED]$4").replace(HR,"$1$2[REDACTED]")}var Jm=/^[a-f0-9]{64}$/u;var LR="comet.native.acceptance-trace.v2",MR="comet.native.partial-allowance.v1",DR="comet.native.verification-evidence.v2";function kt(e,t){if(!Jm.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Um(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Km(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Ml(e,t,i=2e3){let n=Qe(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function Er(e,t){let i=zm.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||zm.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function FR(e,t,i){let n=Er(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=at(n),a=n.toLowerCase(),o=i?Er(i,"Native root ref").toLowerCase():null;if(r||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${r??"native-runtime"}): ${n}`);return n}function Dl(e){let t=Er(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function sn(e,t){return e<t?-1:e>t?1:0}function Po(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ao(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));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 Gm(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Wm(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let n=`runtime/evidence/${t}/${i}.json`;if(e!==n)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function BR(e){let t=Po(e,"Native acceptance trace");if(Ao(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!Jm.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=Er(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=Po(o,`Native acceptance trace entry ${s}`);if(Ao(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(u=>typeof u!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(u=>Dl(u)),f=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(sn))||f==="passed"&&(l.length===0||c.skippedReason!==null)||f==="failed"&&l.length===0&&c.skippedReason===null||f==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:f,kind:c.kind,source:Er(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Ml(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>sn(o.acceptanceId,s.acceptanceId)))||new Set(n.map(o=>o.acceptanceId)).size!==n.length||t.total!==n.length||t.evidenced!==n.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==n.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let r={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:n},a=kt(t.traceHash,"Native acceptance trace hash");if(D(LR,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function Ym(e){let t=Po(e,"Native partial allowance");if(Ao(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(r=>typeof r!="string"||!/^scope:[a-f0-9]{64}$/u.test(r))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(sn))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:Km(t.change),scopeHash:kt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Ml(t.reason,"Partial allowance reason"),confirmedSummary:Ml(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Um(t.sourceRevision),confirmedAt:Gm(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let n=kt(t.allowanceHash,"Native partial allowance hash");if(D(MR,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function Fl(e){let t=Po(e,"Native verification evidence");if(Ao(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=kt(t.implementationScopeHash,"Native verification implementation scope hash"),n=BR(t.acceptanceTrace),r=kt(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(n.criteriaHash!==r)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:kt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(d=>Dl(d));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(sn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(d=>d.evidenceRefs))].sort(sn);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(d=>Dl(d));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(sn)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let f={schema:"comet.native.verification-evidence.v2",change:Km(t.change),sourceRevision:Um(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:kt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:Wm(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:FR(t.reportRef,"Native verification report ref"),reportHash:kt(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:Wm(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Gm(t.createdAt,"Native verification timestamp")},u=kt(t.envelopeHash,"Native verification envelope hash");if(D(DR,f)!==u)throw new Error("Native verification evidence content hash mismatch");return{...f,envelopeHash:u}}import Xm from"node:path";var Qm="comet.native.check-receipt.v1",qR="comet.native.check-receipt.v1",cn="scoped-text-safety",Bl=1,Be=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),VR=/^[a-f0-9]{64}$/u,zR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WR="comet.native.checker-policy.v1",JR="comet.native.check-input.v1",UR=2048,Zm=D(WR,{policy:cn,version:Bl,limits:Be,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),KR=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),ev=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],iv=["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"],GR=new Set(iv);function bi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Si(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));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 Et(e,t){if(typeof e!="string"||!VR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ni(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function nv(e,t){let i=Ni(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function tv(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function YR(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>UR||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=Xm.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Xm.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function XR(e){let t=bi(e,"Native check receipt checker");Si(t,["policy","version","hash","limits"],"Native check receipt checker");let i=bi(t.limits,"Native check receipt limits");if(Si(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==cn||t.version!==Bl||t.hash!==Zm||i.maxFiles!==Be.maxFiles||i.maxFileBytes!==Be.maxFileBytes||i.maxTotalBytes!==Be.maxTotalBytes||i.maxIssues!==Be.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:cn,version:Bl,hash:Zm,limits:{...Be}}}function QR(e){let t=bi(e,"Native check receipt contract");return Si(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Et(t.expectedHash,"Native check expected contract hash"),beforeHash:Et(t.beforeHash,"Native check before contract hash"),afterHash:Et(t.afterHash,"Native check after contract hash")}}function ZR(e){let t=bi(e,"Native check receipt implementation");return Si(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Et(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Et(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Et(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Et(t.afterSnapshotHash,"Native check after snapshot hash")}}function eP(e){let t=bi(e,"Native check receipt counts");Si(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:Ni(t.filesSelected,"Native check filesSelected"),filesScanned:Ni(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Ni(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Ni(t.bytesScanned,"Native check bytesScanned"),issueCount:Ni(t.issueCount,"Native check issueCount"),recordedIssueCount:Ni(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>Be.maxFiles||i.bytesScanned>Be.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Be.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function tP(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||ev.indexOf(e.kind)-ev.indexOf(t.kind)}function iP(e){if(!Array.isArray(e)||e.length>Be.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=bi(n,`Native check issue ${r}`);if(Si(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!KR.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:YR(a.path,`Native check issue ${r} path`),line:nv(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(tP);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function nP(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!GR.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=iv.filter(n=>t.includes(n));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function rP(e){return D(JR,e)}function rv(e){let t=bi(e,"Native check receipt");if(Si(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Qm)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!zR.test(t.change))throw new Error("Native check receipt change name is invalid");let i=nv(t.sourceRevision,"Native check source revision"),n=XR(t.checker),r=QR(t.contract),a=ZR(t.implementation),o=rP({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Et(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=tv(t.startedAt,"Native check receipt startedAt"),c=tv(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=eP(t.counts),f=iP(t.issues);if(l.recordedIssueCount!==f.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>f.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let u=nP(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==u.length>0)throw new Error("Native check receipt stale flag is inconsistent");let d=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==d)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.filesSelected>Be.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>Be.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:Qm,change:t.change,sourceRevision:i,checker:n,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:r,implementation:a,counts:l,issues:f,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:u},m=Et(t.receiptHash,"Native check receipt content hash");if(D(qR,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var Vl="comet.native.verification-receipt.v3",aP=Vl,oP="comet.native.declared-artifacts.v1",sP=/^[a-f0-9]{64}$/u,cP=/^acceptance-[a-f0-9]{64}$/u,lP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uP=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,fP=4096,dP=256,hP=1024;function ln(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Xt(e,t,i){let n=Object.keys(e).sort(),r=[...t].sort();if(n.length!==r.length||n.some((a,o)=>a!==r[o]))throw new Error(`${i} fields are invalid`)}function Ct(e,t){if(typeof e!="string"||!sP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ze(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=Qe(e).trim();if(!i||i.length>fP||i!==e.trim())throw new Error(`${t} is invalid`);return i}function ql(e,t){let i=Ze(e,t),n=new Date(i);if(Number.isNaN(n.getTime())||n.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function Cr(e,t,i=Ze,n=!1,r=dP){if(!Array.isArray(e)||e.length>r||!n&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function pP(e,t){if(typeof e!="string"||!cP.test(e))throw new Error(`${t} is invalid`);return e}function mP(e){let t=ln(e,"Native verification receipt bindings");if(Xt(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!lP.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:Ct(t.contractHash,"Native verification receipt contract hash"),scopeHash:Ct(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Ct(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Ct(t.artifactHash,"Native verification receipt artifact hash")}}function vP(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=uP.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function gP(e,t,i,n){let r=ln(t,`Native ${e} evidence`);if(e==="automated-check"){if(Xt(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=ql(r.startedAt,"Native automated-check start time"),o=ql(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=ln(r.worktree,"Native automated-check worktree");if(Xt(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=ln(r.afterFence,"Native automated-check after fence");if(Xt(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:Ze(r.executable,"Native automated-check executable"),args:Cr(r.args,"Native automated-check arguments",Ze,!0),cwd:Ze(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:Ze(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Ct(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Ct(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Ct(r.outputHash,"Native automated-check output hash"),outputSummary:Ze(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){Xt(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=vP(r.checkReceiptRef);if(Ct(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Cr(r.subjects,"Native static inspection subjects",Ze,n==="required-check"),rule:Ze(r.rule,"Native static inspection rule"),resultSummary:Ze(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Xt(r,["steps","observations"],"Native manual-evidence evidence"),{steps:Cr(r.steps,"Native manual evidence steps"),observations:Cr(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function wP(e){let t=ln(e,"Native verification receipt");if(Xt(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,n=t.role,r=t.status,a=Ze(t.actor,"Native verification receipt actor"),o=Cr(t.acceptanceIds,"Native receipt acceptance IDs",pP,n==="required-check",hP).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:Vl,kind:i,role:n,status:r,bindings:mP(t.bindings),acceptanceIds:o,actor:a,issuedAt:ql(t.issuedAt,"Native verification receipt issue time"),evidence:gP(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==cn||s.actor!==`native-runtime:${cn}`))throw new Error("Native required check policy identity is invalid");return s}function av(e){let t=ln(e,"Native verification receipt");if(Xt(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Vl)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=wP(n),a=Ct(t.receiptHash,"Native verification receipt hash");if(D(aP,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function zl(e){return D(oP,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var lv=/^[a-f0-9]{64}$/u,un=yi,R0=3*un;function Wl(e,t){let i=lt.relative(e,t);return i===""||!lt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${lt.sep}`)}function NP(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function xo(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return de(i,n)?$(i,n):$(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ov(e){let t=await et.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await et.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function bP(e,t){let i=lt.resolve(e),n=lt.resolve(t);if(!Wl(i,n))throw new Error("Native evidence path is outside its change");let r=[await ov(i)],a=i;for(let o of lt.relative(i,n).split(lt.sep).filter(Boolean)){a=lt.join(a,o);let s=await ov(a);if(!Wl(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function sv(e){for(let t of e){let i=await et.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!NP(t,i)||await et.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function SP(e,t,i={}){let n=await bP(t,lt.dirname(e));await i.afterParentChainCaptured?.();let r=await et.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await et.realpath(e);if(!Wl(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await et.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),et.lstat(e),et.realpath(e)]);if(await sv(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!xo(s,r)||!xo(s,c))throw new Error("Native evidence document changed while opening");if(s.size>un)throw new Error(`Native evidence document exceeds ${un} bytes`);await i.afterOpen?.();let f=[],u=0,d=Buffer.allocUnsafe(64*1024);for(;;){let v=un+1-u,w=await o.read(d,0,Math.min(d.length,v),null);if(w.bytesRead===0)break;if(u+=w.bytesRead,u>un)throw new Error(`Native evidence document exceeds ${un} bytes`);f.push(Buffer.from(d.subarray(0,w.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),et.lstat(e),et.realpath(e)]);if(await sv(n),!m.isFile()||m.isSymbolicLink()||h!==a||!xo(s,p)||!xo(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 uv(e,t){if(!lv.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function kP(e,t,i,n,r){if(!lv.test(i))throw new Error("Native report evidence hash is invalid");let a=await ki({paths:e,name:t,kind:"reports",hash:i,hooks:n,changeDir:r});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||yP("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function fn(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function EP(e,t,i,n,r){return lt.join(r??W(e,t),...uv(i,n).split("/"))}async function ki(e){let t=e.changeDir??W(e.paths,e.name),i=EP(e.paths,e.name,e.kind,e.hash,t);return await H(e.paths.nativeRoot,i),SP(i,t,e.hooks)}function cv(e,t){return So(e,t)}function CP(e,t){let i=Co(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function RP(e,t,i){let n=Ym(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function PP(e,t,i){let n=Fl(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function AP(e,t,i,n=!1,r){let a=await Jl(e,t,i.implementationScopeRef,void 0,r);if(n&&await kP(e,t,i.reportHash,void 0,r),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await fv(e,t,i.partialAllowanceRef,void 0,r);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function To(e,t,i,n,r){let a=fn(i,"scopes"),o=CP(await ki({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=fn(o.baselineProjectionRef,"snapshots"),c=fn(o.currentProjectionRef,"snapshots"),[l,f]=await Promise.all([ki({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(u=>cv(u,s)),ki({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(u=>cv(u,c))]);return Vm({baseline:l,current:f,scope:o})}async function Jl(e,t,i,n,r){return(await To(e,t,i,n,r)).scope}async function fv(e,t,i,n,r){let a=fn(i,"allowances");return RP(await ki({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function dv(e,t,i,n,r){let a=fn(i,"receipts"),o=av(await ki({paths:e,name:t,kind:"receipts",hash:a,hooks:n,changeDir:r}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function hv(e,t,i,n,r){let a=fn(i,"verifications"),o=PP(await ki({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await AP(e,t,o,!1,r),o}async function xP(e){try{let t=await qt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:Ce.maxChanges});return await t.verify(),t.entries}catch(t){if(t.code==="ENOENT")return[];throw t}}async function TP(e,t){let i=await ue(e,t),[n,r]=await Promise.all([i.implementation_scope?Jl(e,t,i.implementation_scope):null,rm(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:n?.declaredArtifacts??[],workspaceIdentityHash:r?.nativeRootId??null}}async function IP(e){let i=(await xP(e)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();return Promise.all(i.map(n=>TP(e,n)))}async function pv(e,t){let i=await IP(e);Tl(i);let n=i.find(o=>o.name===t);if(!n)throw new Error(`Native conflict target is not visible: ${t}`);let r=0,a=0;for(let o of i){if(o.name===t)continue;let s=Tl([n,o]).relationships[0];s.classification==="definite-conflict"&&(r+=1),s.classification==="possible-overlap"&&(a+=1)}return{definiteConflictCount:r,possibleOverlapCount:a,findingCodes:[...r>0?["native-change-conflict"]:[],...a>0?["native-change-overlap"]:[]]}}import{promises as BP}from"fs";import qP from"path";import{isDeepStrictEqual as nu}from"util";var Ul={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var _P=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function OP(e,t){return e<t?-1:e>t?1:0}function jP(e,t,i,n){if(!Array.isArray(e)||e.length>i||!n&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let r=e.map(a=>{if(typeof a!="string"||!_P.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(OP)}function mv(e=[]){return jP(e,"Native repair failed check IDs",Ul.maxFailedCheckIds,!0)}function Kl(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var $P=/^[a-f0-9]{64}$/u;var vv=["disposition","overrideSummaryHash","signatureHash"],HP=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"];function Yl(e,t){return e<t?-1:e>t?1:0}function LP(e,t,i){let n=Object.keys(e).sort(Yl);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function MP(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Gl(e,t){if(typeof e!="string"||!$P.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function DP(e){if(!Array.isArray(e)||e.length>Ul.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Yl)}function gv(e){let t=MP(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Yl),n=i.length===vv.length&&i.every((l,f)=>l===vv[f]);n||LP(t,HP,"Native repair trajectory projection");let r=Gl(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Gl(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(n)return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Gl(t.contractHash,"Native repair trajectory contract hash"),s=DP(t.failedAcceptanceIds),c=mv(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}var Qt={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:[]},Xl=J("comet-native-runtime:v3:semantic-repair-budget"),FP=[{skillVersion:"2",skillHash:J("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:J("comet-native-runtime:v1")}];function wv(e){return e.skillVersion===Qt.definition.metadata.version&&e.skillHash===Xl||FP.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var Ql={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function Rr(e){let i={sequence:(await pi(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await em(e.changeDir,e.run.trajectoryRef,i),i}async function Io(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:J(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await tm(e.changeDir,e.run.checkpointRef,t),t}function yv(e){return J(JSON.stringify({summary:e.summary,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var Pv=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],VP=new Set(Pv),Av=new Set([...Pv,"minimum_runtime_version","revision"]),zP=new Set([...Av,"operation"]),WP=512*1024,eu=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),JP=new Set([...eu,"implementationScopeHash","repairScopeHash","repairStagnation"]),tu=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 Oo(e,t){return qP.join(W(e,t),"runtime","transition.json")}function UP(e){return`transition-${e}`}async function KP(e,t,i){let n=UP(t);return Bi(e,n,i)}async function jo(e,t,i,n){let r=await KP(e,t,i);try{return await n()}finally{await qi(r)}}function $o(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function ru(e,t){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function _o(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ut(e,t){return nu(e,t)}function iu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,n=Object.keys(i),r=n.find(f=>!JP.has(f)),a=[...eu].find(f=>!Object.hasOwn(i,f)),o=eu.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!==t)throw new Error("Native transition journal event evidence hash mismatch");if(Kl(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&&(Kl(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")?gv(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:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function GP(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,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 iu({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return iu(e,t)}function au(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let n=i?GP(e.eventData,e.evidenceHash):iu(e.eventData,e.evidenceHash),r=pl(e.nextRun),a=e.previousRun===null?null:pl(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function Nv(e,t,i=!1){if(e.skill!==Qt.definition.metadata.name||(i?!wv(e):e.skillVersion!==Qt.definition.metadata.version||e.skillHash!==Xl)||e.orchestration!==Qt.definition.orchestration.mode||e.pendingRef!==st.pendingRef||e.trajectoryRef!==st.trajectoryRef||e.contextRef!==st.contextRef||e.artifactsRef!==st.artifactsRef||e.checkpointRef!==st.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function bv(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Sv(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function ou(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(Nv(a,"next Run",n||r!==null),Sv(a,"next Run"),a.runId!==t.run_id||a.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(r===null){if(e.run_id!==null||e.phase!=="shape"||a.iteration!==1||Object.keys(a.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Nv(r,"previous Run",!0),Sv(r,"previous Run"),e.run_id!==r.runId||r.currentStep!==e.phase||t.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(!nu(bv(r),bv(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function YP(e,t,i){return J(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function xv(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function kv(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function su(e,t,i,n,r=!1){let a=i.eventData,o=kv(e),s=kv(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(n==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&nu(e.spec_changes,t.spec_changes),l=yv({summary:a.summary});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(n==="spec-rebase"){let c=YP(e.name,a.summary,t.spec_changes),l=J(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!r&&i.evidenceHash!==c||r&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function XP(e,t){let i=$o(e);if(ru(i,zP),i.schema!==tn)throw new Error(`Expected Native transition schema ${tn}`);let n=_o(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 ${tn} minimum_runtime_version must be ${3}`);let r=_o(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=au(i,t),o=ct(i.previousState),s=ct(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(su(o,s,a,i.operation),ou(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:tn,minimum_runtime_version:3,revision:r,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function QP(e,t){let i=$o(e);if(ru(i,VP),i.schema!==hr)throw new Error(`Expected Native transition schema ${hr}`);let n=au(i,t,!0),r=wr(i.previousState),a=wr(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return su(r,a,n,xv(r,a,n.eventData),!0),ou(r,a,n,!0),{schema:hr,id:n.id,change:t,evidenceHash:n.evidenceHash,createdAt:n.createdAt,previousState:r,nextState:a,previousRun:n.previousRun,nextRun:n.nextRun,eventData:n.eventData}}function ZP(e,t){let i=$o(e);if(ru(i,Av),i.schema!==nn)throw new Error(`Expected Native transition schema ${nn}`);if(_o(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${nn} minimum_runtime_version must be 2`);let r=_o(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=au(i,t,!0),o=yr(i.previousState),s=yr(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(su(o,s,a,xv(o,s,a.eventData),!0),ou(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:nn,minimum_runtime_version:2,revision:r,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function eA(e,t){let i=$o(e);if(i.schema===tn)return{status:"current",journal:XP(i,t)};if(i.schema===hr)return{status:"migration-required",journal:QP(i,t)};if(i.schema===nn)return{status:"migration-required",journal:ZP(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function tA(e,t){let i=Oo(e,t);await H(e.nativeRoot,i);try{let n=await ie({root:e.nativeRoot,file:i,maxBytes:WP,label:`Native transition journal ${t}`});return eA(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Zl(e,t){let i=await tA(e,t);if(!i)return null;if(i.status==="migration-required")throw new tu(t);return i.journal}function Ev(e,t){if(ut(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(ut(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function Cv(e,t){if(ut(e,t.nextState))return"next";if(ut(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function iA(e){let{journal:t}=e;return Tv({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function Tv(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Rv(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.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>(t.previousRun===null?1:0)||r.length>1||t.previousRun===null&&r.length===1&&(n.length!==1||n[0].index>=r[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...n,...r]){let o=iA({sequence:a.index+1,journal:t,type:a.event.type});if(!ut(Tv(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:n[0]?.event??null,transitioned:r[0]?.event??null}}async function cu(e,t,i){if(await rn(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await mo(e,t);let n=await Zl(e,t);if(!n)return null;let r=W(e,t),a=Rv(await pi(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([Zi(r),ue(e,t)]),c=Ev(o,n),l=Cv(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 po(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!ut(await Zi(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 wo(e,n.nextState,n.previousState.revision);if(!ut(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!ut(await ue(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let f=await Zl(e,t);if(!f||!ut(f,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let u=Rv(await pi(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(u.started||await Rr({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 Rr({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await Io({changeDir:r,run:n.nextRun,trajectoryOffset:d.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([Zi(r),ue(e,t)]);Ev(p,{...n,previousRun:n.nextRun}),Cv(m,{...n,previousState:n.nextState});let h=await Zl(e,t);if(!h||!ut(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await BP.rm(Oo(e,t),{force:!0}),n.nextState}import Iv from"node:path";var nA="comet.native.acceptance.v1",rA=/^acceptance-[a-f0-9]{64}$/u,aA=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),oA=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u;var C$=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Pr=Object.freeze({maxCriteria:1024}),_v="<!-- comet-native:acceptance-evidence:start -->",Ov="<!-- comet-native:acceptance-evidence:end -->";function fu(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function lu(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let n=i[1][0];return t===null?{marker:n,length:i[1].length}:n===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function jv(e){return e.includes("-->")||e.includes("--!>")}function*dn(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
166
|
+
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
167
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&n===null,index:s},s+=1,t!==null)t=lu(l,t);else if(i)jv(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let u=lu(l,null);if(u!==null)t=u;else{let d=l.trimStart();if(d.startsWith("<!--")&&!jv(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 sA(e){return[...dn(e)].map(({line:t,body:i})=>({line:t,body:i}))}function uu(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function cA(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function du(e,t,i,n=[]){let r=uu(i),a=t.replaceAll("\\","/").trim(),o=n.map(uu);if(r.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(a.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:`acceptance-${D(nA,{kind:e,source:a,context:o,text:r})}`,kind:e,source:a,context:o,text:r}}function hu(e,t){let i=new Set;for(let n of e){if(i.has(n.id))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(n.id)}return e}function lA(e){let t=null,i=null,n=0,r=0;for(let{line:a,body:o,index:s}of dn(e)){r=s+1;let c=o?fu(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(n+=1,n===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(n===0||t===null)return null;if(n!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??r}}function $v(e,t="brief.md",i=Pr.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=lA(e);if(n===null)return[];let r=null;for(let{line:c,body:l,index:f}of dn(e)){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 dn(e)){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(),hu(a.map(c=>du("brief-example",t,c.join(`
|
|
168
|
+
`))),"Brief")}function Hv(e,t="spec.md",i=Pr.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(du("spec-scenario",t,[a.title,...a.body].join(`
|
|
169
|
+
`),a.context)),a=null}};for(let{line:s,body:c}of dn(e)){let l=c?fu(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=uu(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(),hu(n,"Specification")}function Lv(e,t="spec.md",i=Pr.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(du("spec-must",t,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 dn(e)){let u=f?fu(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||lu(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(),hu(n,"Specification mandatory requirements")}function uA(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||cA(i)||Iv.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let n=Iv.posix.normalize(i);if(n==="."||n===".."||n.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(n.split("/").some(r=>r.toLowerCase()===".git"||r.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!oA.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function fA(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,n=Object.keys(i).filter(r=>!aA.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.join(", ")}`);return i}function Mv(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,n)=>{let r=fA(i,n),a=r.acceptance_id;if(typeof a!="string"||!rA.test(a))throw new Error(`Acceptance evidence entry ${n} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(r.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=r.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return uA(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=r.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(r,"skipped_reason")){if(typeof r.skipped_reason!="string"||r.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=r.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function Dv(e){let t=sA(e);if(t.some(({line:l,body:f})=>!f&&(l===_v||l===Ov)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:f},u)=>f&&l===_v?[u]:[]),r=t.flatMap(({line:l,body:f},u)=>f&&l===Ov?[u]:[]);if(n.length!==1||r.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(n[0]>=r[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(n[0]+1,r[0]).map(({line:l})=>l).join(`
|
|
170
|
+
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=Mv(o),c=dA(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function dA(e){let t=Mv([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,n)=>i.acceptance_id.localeCompare(n.acceptance_id));return JSON.stringify(t,null,2)}import Fv from"node:path";var hA="comet.native.contract.v1",pA="comet.native.acceptance-set.v1",Bv=/^[a-f0-9]{64}$/u,Ar={maxAcceptanceCriteria:Pr.maxCriteria};function qv(e,t){let i=Fv.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||Fv.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Vv(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
171
|
+
`))}function mA(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(Bv))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(Bv))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=qv(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Vv(e.markdown)},markdown:e.markdown}}function vA(e,t){return zv(e.id,t.id)}function zv(e,t){return e<t?-1:e>t?1:0}function Wv(e){let t=qv(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(mA).sort((u,d)=>zv(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=[t,...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=$v(e.briefMarkdown,t,Ar.maxAcceptanceCriteria);for(let{snapshot:u,markdown:d}of i)d===null||u.source===null||(a.push(...Hv(d,u.source,Ar.maxAcceptanceCriteria-a.length)),a.push(...Lv(d,u.source,Ar.maxAcceptanceCriteria-a.length)));if(a.sort(vA),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Ar.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Ar.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:t,contentHash:Vv(e.briefMarkdown)},c=i.map(({snapshot:u})=>u),l=D(pA,a),f={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...f,contractHash:D(hA,f)}}var Ho={maxSpecs:64,maxFileBytes:Jn,maxTotalBytes:4*1024*1024};async function pu(e){if(e.specChanges.length>Ho.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await me({root:e.changeDir,ref:e.briefRef,maxBytes:Ho.maxFileBytes}),i=t.size,n=[];for(let r of e.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 me({root:e.changeDir,ref:r.source,maxBytes:Ho.maxFileBytes});if(i+=a.size,i>Ho.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:Wv({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{execFile as IA,spawn as dH}from"node:child_process";import{promisify as _A}from"node:util";import{promises as SA}from"fs";import xr from"path";var Lo={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},hn=/^[a-f0-9]{64}$/u;function Mo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Do(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));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 Zt(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Jv(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function mu(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function gA(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||xr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=xr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function wA(e,t){return xr.join(W(e,t),"runtime","checkpoints","progress.json")}function vu(e,t){return xr.join(W(e,t),"runtime","checkpoint-journal.json")}function Uv(e,t,i){if(!hn.test(i))throw new Error("Native checkpoint manifest hash is invalid");return xr.join(W(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function yA(e){if(!hn.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Kv(e,t,i){let n=await ie({root:e,file:t,maxBytes:Lo.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function NA(e,t){let i=Mo(e,`checkpoint manifest artifact ${t}`);Do(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=gA(Zt(i.path,`checkpoint artifact ${t} path`,4096)),r=at(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!hn.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:mu(i.size,`checkpoint artifact ${t} size`)}}function Fo(e,t){let i=Mo(e,"Native checkpoint manifest");if(Do(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>Lo.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(NA),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=mu(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>Lo.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:n,totalBytes:a}}function gu(e){return J(JSON.stringify(Fo(e,e.change)))}function Gv(e,t){let i=Mo(e,"Native progress checkpoint");if(Do(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let n=i.phase;if(n!=="shape"&&n!=="build"&&n!=="verify"&&n!=="archive")throw new Error("Native checkpoint phase is invalid");let r=Jv(i.previousRevision,"Native checkpoint previousRevision"),a=Jv(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Zt(i.manifestHash,"Native checkpoint manifestHash",64);if(!hn.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=yA(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Zt(i.inputHash,"Native checkpoint inputHash",64);if(!hn.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Zt(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let f=mu(i.artifactCount,"Native checkpoint artifactCount");if(f>Lo.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let u=Zt(i.summary,"Native checkpoint summary"),d=Zt(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:Zt(i.id,"Native checkpoint id",128),change:t,phase:n,previousRevision:r,stateRevision:a,summary:u,nextAction:d,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:f,createdAt:l}}function bA(e,t){let i=Mo(e,"Native checkpoint journal");if(Do(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let n=ct(i.previousState),r=ct(i.nextState),a=Gv(i.checkpoint,t),o=Fo(i.manifest,t),s=Zt(i.inputHash,"Native checkpoint journal inputHash",64),c=J(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!hn.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!==t||r.name!==t||r.revision!==n.revision+1||a.previousRevision!==n.revision||a.stateRevision!==r.revision||a.phase!==r.phase||a.manifestHash!==gu(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:n,nextState:r,checkpoint:a,manifest:o}}async function Yv(e,t,i){let n=Uv(e,t,i);await H(e.nativeRoot,n);let r=await Kv(e.nativeRoot,n,"Native checkpoint manifest"),a=Fo(r,t);if(wu(e,a),gu(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Xv(e,t){let i=vu(e,t);await H(e.nativeRoot,i);try{let n=bA(await Kv(e.nativeRoot,i,"Native checkpoint journal"),t);return wu(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Qv(e,t,i,n){let r=Fo(i,t);wu(e,r);let a=gu(r),o=Uv(e,t,a);await H(e.nativeRoot,o);try{let s=await Yv(e,t,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 Se(o,r,{containedRoot:e.nativeRoot,beforeCommit:n?.beforeCommit}),a}function wu(e,t){for(let i of t.artifacts){let n=xh(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function Zv(e,t){let i=Gv(t,t.change),n=await Yv(e,i.change,i.manifestHash),r=J(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=wA(e,t.change);await H(e.nativeRoot,a),await Se(a,i,{containedRoot:e.nativeRoot})}async function eg(e,t,i){let n=await Xv(e,t);if(!n)return null;if(await Qv(e,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await wo(e,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await Zv(e,n.checkpoint),await i?.afterProgressWritten?.(n),await SA.rm(vu(e,t),{force:!0}),n}async function yu(e,t){await cu(e,t),await eg(e,t)}import{constants as Nu,promises as qe}from"node:fs";import Ei from"node:path";var kA=/^[a-f0-9]{64}$/u,EA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Tr=512*1024;function CA(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Bo(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return de(i,n)?$(i,n):$(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function RA(e,t){let i=Ei.resolve(e),n=Ei.resolve(t);if(!G(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...Ei.relative(i,n).split(Ei.sep).filter(Boolean)]){o&&(a=Ei.join(a,o));let s=await qe.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await qe.realpath(a);if(r.length>0&&!G(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 tg(e){for(let t of e){let i=await qe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!CA(t,i)||await qe.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function PA(e){if(!kA.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function AA(e){let t=EA.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function xA(e,t,i){return Ei.join(W(e,t),...PA(i).split("/"))}async function TA(e,t,i){let n=await RA(i,Ei.dirname(e)),r=await qe.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>Tr)throw new Error(`Native check receipt exceeds ${Tr} bytes`);let[a,o]=await Promise.all([qe.realpath(t),qe.realpath(e)]);if(!G(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Nu.O_RDONLY|Nu.O_NOFOLLOW|Nu.O_NONBLOCK,c=await qe.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,f,u]=await Promise.all([c.stat(),qe.lstat(e),qe.realpath(e)]);if(await tg(n),!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!Bo(r,l)||!Bo(l,f))throw new Error("Native check receipt changed while opening");let d=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let S=Tr+1-p,N=await c.read(m,0,Math.min(m.length,S),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,p>Tr)throw new Error(`Native check receipt exceeds ${Tr} bytes`);d.push(Buffer.from(m.subarray(0,N.bytesRead)))}let[h,v,w]=await Promise.all([c.stat(),qe.lstat(e),qe.realpath(e)]);if(await tg(n),!v.isFile()||v.isSymbolicLink()||w!==o||!G(a,w)||!Bo(l,h)||!Bo(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 ig(e,t,i){let n=AA(i),r=W(e,t),a=xA(e,t,n);await H(e.nativeRoot,a);let o=rv(await TA(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}var RH=64*1024;var PH=3600*1e3;var AH=_A(IA);var xH=["$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("; ");var OA=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function ng(e,t){let i=[];for(let n of OA){let r=e.bindings[n],a=t[n];r!==a&&i.push(`${n}: expected ${JSON.stringify(a)}, got ${JSON.stringify(r)}`)}return{ok:i.length===0,mismatches:i}}async function rg(e){if(e.receipt.kind!=="static-inspection")return null;let t=await ig(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var ei=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(n=>`${n.ref}${n.acceptanceId?`[${n.acceptanceId}]`:""} -> ${n.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function jA(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function $A(e){let t=jA(e.bundle.baseline),i=await fl(e.paths,t,{origin:"explicit",now:e.now});return Hl({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function HA(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await To(e.paths,e.state.name,e.state.implementation_scope),i=await pu({changeDir:W(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await $A({paths:e.paths,bundle:t,now:e.now}),r=[];return i.contract.contractHash!==t.scope.contractHash&&r.push("verification-contract-stale"),n!==t.scope.currentProjectionHash&&r.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:r}}async function LA(e){let t=await me({root:W(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Dv(t.text)}}function MA(e){let{receipt:t,implementationScope:i}=e,n=[],r=i.scope.changes.filter(o=>o.after!==null),a=r.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==r.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==r.length||t.counts.bytesScanned!==a))&&n.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&n.push("verification-receipt-outcome-mismatch"),n}function DA(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:zl(e.implementationScope.scope.declaredArtifacts)}}async function ag(e){let t=await dv(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=ng(t,e.expectedBindings);if(i.push(...n.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new ei([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let r=await rg({paths:e.paths,state:e.state,receipt:t});if(r){let a=MA({receipt:r,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function FA(e){let t=DA({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await ag({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof ei)return i.push(...a.details),null;throw a});if(r!==null&&r.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let n of e.trace.entries)if(n.status!=="missing")for(let r of n.evidenceRefs){let a=await ag({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof ei)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(n.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new ei(i)}function bu(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function qo(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:bu(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([HA(e),hv(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:bu(e.state.verification_result,"stale"),envelope:null};let n=await LA({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),r=[...t.findingCodes];(n.hash!==i.reportHash||n.ref!==i.reportRef)&&r.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&r.push("verification-state-mismatch");try{await FA({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{r.push("verification-receipt-invalid")}let a=[...new Set(r)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:bu(e.state.verification_result,"invalid"),envelope:null}}}function qA(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function sg(e){try{return await BA.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function VA(e,t){try{return(await me({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function zA(e,t,i){let n=Nr(e,i.capability);if(!G(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=og.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await VA(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await me({root:W(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function WA(e,t){return sg(Oo(e,t))}async function Ir(e){let t=e.now??new Date,i=await ue(e.paths,e.name),n=await Bt(e.paths.projectRoot),r=qA(i.name,t),a=og.resolve(e.paths.nativeRoot,...r.split("/"));if(!G(e.paths.nativeRoot,a))throw new Error("Native archive target escapes its root");let[o,s,c,l,f,u,d]=await Promise.all([Promise.all(i.spec_changes.map(p=>zA(e.paths,i.name,p))),qo({paths:e.paths,state:i,now:t}),pv(e.paths,i.name),rn(e.paths,i.name),kl(e.paths,i.name),WA(e.paths,i.name),sg(a)]);return km({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:l||f||u,targetRef:r,targetExists:d,specs:o,evidence:s.evidence,findingCodes:[...s.findingCodes,...c.findingCodes]})}import{promises as Su}from"node:fs";import Rt from"node:path";var JA="comet.native.archive-tree.v1",UA={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function ug(e){let t={...UA,...e};for(let[i,n]of Object.entries(t))if(!Number.isSafeInteger(n)||n<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function cg(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function lg(e,t,i,n){if(i.entryCount+=1,i.entryCount>n.maxEntries)throw new Error(`Native Archive content exceeds ${n.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>n.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${n.maxRefBytes} bytes: ${t.ref}`);let r=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=r+(e.length===0?0:1),i.manifestBytes+2>n.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${n.maxManifestBytes} bytes`);e.push(t)}async function fg(e,t,i,n,r,a){if(a>r.maxDepth)throw new Error(`Native Archive content exceeds depth ${r.maxDepth}`);let o=await qt({root:e,directory:t,label:`Native Archive content directory ${Rt.relative(e,t)||"."}`,maxEntries:r.maxEntries}),s=cg(o.entries),c=[...o.entries];c.sort((f,u)=>f.name.localeCompare(u.name));for(let f of c){await o.verify();let u=Rt.join(t,f.name),d=Rt.relative(e,u).replaceAll("\\","/"),p=await Su.lstat(u);if(f.isSymbolicLink()||p.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${d}`);if(f.isDirectory()&&p.isDirectory()){lg(i,{ref:d,kind:"directory"},n,r),await fg(e,u,i,n,r,a+1);continue}if(!f.isFile()||!p.isFile())throw new Error(`Native Archive content must contain only files and directories: ${d}`);let m=await ie({root:e,file:u,maxBytes:r.maxFileBytes,label:`Native Archive content file ${d}`});if(n.totalBytes+=m.size,n.totalBytes>r.maxTotalBytes)throw new Error(`Native Archive content exceeds ${r.maxTotalBytes} total file bytes`);lg(i,{ref:d,kind:"file",hash:m.hash,size:m.size},n,r),await o.verify()}await o.verify();let l=await qt({root:e,directory:t,label:`Native Archive content directory ${Rt.relative(e,t)||"."}`,maxEntries:r.maxEntries});if(cg(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Rt.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function ku(e,t={}){let i=ug(t);e=Rt.resolve(e);let n=await Su.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let r=[];await fg(e,e,r,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(r);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return J(`${JA}\0${o}`)}async function ti(e,t={}){let i=ug(t);e=Rt.resolve(e);let n;try{n=await Su.lstat(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(n.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(n.isFile())return{kind:"file",hash:(await ie({root:Rt.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Rt.basename(e)}`})).hash};if(n.isDirectory())return{kind:"directory",hash:await ku(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as Pe}from"node:fs";import oe from"node:path";var Cu=16*1024*1024,KA=256*1024,GA=16*1024,Or="comet.native.archive-cas.v1";function YA(e,t){let i=oe.resolve(e.nativeRoot,...t.split("/"));if(oe.relative(e.nativeRoot,i).split(oe.sep).includes(".."))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return i}async function Re(e,t){return H(e.nativeRoot,YA(e,t))}function jr(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function Vo(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function $e(e){let t=await ti(e.target);if(!jr(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Vo(t)}`);return t}async function vg(e,t){let i=rr(t),n=await Ge(e,i.id);await Pe.mkdir(n.staged,{recursive:!0}),await Pe.mkdir(n.backups,{recursive:!0}),await Se(n.journal,i,{containedRoot:e.nativeRoot}),await Vt(e,i.id,"prepared")}async function gg(e,t){let i=await Ge(e,t),n=await ie({root:e.nativeRoot,file:i.journal,maxBytes:KA,label:`Native Archive transaction journal ${t}`}),r=rr(JSON.parse(n.bytes.toString("utf8")));if(r.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return r}async function wg(e,t,i){let n=rr({...t,status:i}),r=await Ge(e,n.id);return await Se(r.journal,n,{containedRoot:e.nativeRoot}),n}function zo(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function dg(e){return{...zo(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ci(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function XA(e,t){return Ci(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function fe(e){try{return await Pe.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ii(e){let t=await Pe.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=dg(t),n=await ie({root:e.paths.nativeRoot,file:e.file,maxBytes:Cu,label:e.label}),r=await Pe.lstat(e.file);if(!r.isFile()||r.isSymbolicLink()||!XA(i,dg(r))||n.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:zo(r),size:n.size}}function QA(e,t,i,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let r=e;if(Object.keys(r).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=r.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(r.schema!==Or||r.operationId!==t.id||r.role!==i||r.hash!==n)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:Or,operationId:t.id,role:i,hash:n,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Pt(e,t,i,n){let r=await Ge(e,t.id),a=oe.join(r.backups,".cas"),o=`.${oe.basename(n)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:oe.join(a,`${i.id}.original.json`),postRecord:oe.join(a,`${i.id}.post.json`),candidate:oe.join(a,`${i.id}.candidate`),originalQuarantine:oe.join(oe.dirname(n),`${o}.original`),rollbackQuarantine:oe.join(oe.dirname(n),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>H(e.nativeRoot,c))),s}async function ft(e){if(!await fe(e.file))return null;let t=await ie({root:e.paths.nativeRoot,file:e.file,maxBytes:GA,label:`Archive CAS ${e.operation.id} ${e.role} record`});return QA(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Eu(e){let t=await ft(e);if(t){if(!Ci(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await di({root:e.paths.nativeRoot,directory:oe.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:Or,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await Se(e.file,i,{containedRoot:e.paths.nativeRoot,exclusive:!0})}catch(r){if(r.code!=="EEXIST")throw r}let n=await ft(e);if(!n||!Ci(n.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return n}async function ye(e){let t=await ii({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Ci(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function ZA(e){let t=await ii({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Eu({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await ye({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function ex(e){if(!await fe(e.quarantine)||await fe(e.target))return;let t=await er({root:e.paths.nativeRoot,directory:oe.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Pe.link(e.quarantine,e.target)}catch(r){if(r.code==="EEXIST")return;throw r}await t.verify();let[i,n]=await Promise.all([Pe.lstat(e.quarantine),Pe.lstat(e.target)]);if(!Ci(zo(i),zo(n)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Pe.unlink(e.quarantine),await t.verify()}async function tx(e){if(await fe(e.quarantine)){await ye({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await er({root:e.paths.nativeRoot,directory:oe.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await ye({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await ye({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Pe.rename(e.target,e.quarantine),await t.verify(),await ye({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await ex(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function _r(e){if(!await fe(e.file))return;await ye(e);let t=await er({root:e.paths.nativeRoot,directory:oe.dirname(e.file),label:e.label});await t.verify(),await ye(e),await Pe.unlink(e.file),await t.verify()}async function hg(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let n=await Re(e,t.target),r=await Re(e,t.backup),a=await ti(r);if(a!==null){if(!jr(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await $e({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await hi({sourceRoot:e.nativeRoot,source:n,targetRoot:e.nativeRoot,target:r,maxBytes:Cu,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await $e({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function yg(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await Pt(e.paths,e.journal,e.operation,e.target),n=await ft({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await fe(i.originalQuarantine)){if(!n)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await ye({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:n,label:`Archive apply quarantine ${e.operation.target}`}),await hg(e.paths,e.operation,e.hooks),{record:n,quarantine:i.originalQuarantine}}if(!await fe(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return n??=await ZA({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await ye({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive apply target ${e.operation.target}`}),await hg(e.paths,e.operation,e.hooks),await tx({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:n,hooks:e.hooks}),{record:n,quarantine:i.originalQuarantine}}async function pg(e){let t=await Pt(e.paths,e.journal,e.operation,e.target);return await fe(t.candidate)?(await ii({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await di({root:e.paths.nativeRoot,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await hi({sourceRoot:e.paths.nativeRoot,source:e.staged,targetRoot:e.paths.nativeRoot,target:t.candidate,maxBytes:Cu,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function ix(e){let t=e.operation.stagedHash,i=await Pt(e.paths,e.journal,e.operation,e.target),n=await ft({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(n&&await fe(e.target))return await ye({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive write target ${e.operation.target}`}),await fe(i.candidate)&&await _r({paths:e.paths,file:i.candidate,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n;if(await fe(e.target)){let c=await pg(e),l=await ii({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),f=await ii({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Ci(l.identity,f.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return n=await Eu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:f.identity}),await _r({paths:e.paths,file:c,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}let r=await pg(e),a=await ii({paths:e.paths,file:r,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await di({root:e.paths.nativeRoot,directory:oe.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await er({root:e.paths.nativeRoot,directory:oe.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await ye({paths:e.paths,file:r,operation:e.operation,record:{schema:Or,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await Pe.link(r,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await ii({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Ci(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return n=await Eu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await _r({paths:e.paths,file:r,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}async function nx(e,t,i,n){let r=await Re(e,i.target),a=await Re(e,i.staged);if(await $e({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Pt(e,t,i,r);(!await ft({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await fe(r))&&await yg({paths:e,journal:t,operation:i,target:r,hooks:n})}else{let o=await ti(r);if(o!==null&&!jr(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${Vo(o)}`)}await ix({paths:e,journal:t,operation:i,staged:a,target:r,hooks:n}),await $e({target:r,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function rx(e,t,i,n){let r=await Re(e,i.target);await yg({paths:e,journal:t,operation:i,target:r,hooks:n}),await $e({target:r,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function ax(e,t){let i=await Re(e,t.source),n=await Re(e,t.target),[r,a]=await Promise.all([ti(i),ti(n)]);if(!(r===null&&jr(a,t.expectedSourceHash,"directory"))){if(!jr(r,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Vo(r)}, target=${Vo(a)}`);await Pe.mkdir(oe.dirname(n),{recursive:!0}),await Pe.rename(i,n),await $e({target:n,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function ox(e,t,i,n){return i.type==="write"?nx(e,t,i,n):i.type==="remove"?rx(e,t,i,n):ax(e,i)}function sx(e){let t=0,i=!1,n=[];for(let r of e.events){if(r.type!=="operation-started"&&r.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||r.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(r.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);n.push(a.id),t+=1,i=!1}return n}async function cx(e,t,i,n){let r=await Re(e,i.target);if(i.type==="write"){let a=await Re(e,i.staged);await $e({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Pt(e,t,i,r),s=await ft({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await ye({paths:e,file:r,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await $e({target:await Re(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await ft({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await fe(o.originalQuarantine))await ye({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await $e({target:r,expectedHash:null,label:`Completed Archive target ${i.target}`}),await $e({target:await Re(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Pt(e,t,i,r),o=await ft({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await fe(a.originalQuarantine))await ye({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}n||(await $e({target:await Re(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await $e({target:r,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function Ng(e,t,i){let n=t.status==="prepared"?await wg(e,t,"applying"):t;if(n.status!=="applying")throw new Error(`Native Archive transaction ${n.id} cannot apply from ${n.status}`);let r=await Ki(e,n.id),a=sx({journal:n,events:r}),o=new Set(a),s=r.some(l=>l.type==="archive-finalization-started");for(let l of n.operations.slice(0,a.length))await cx(e,n,l,s);let c=o.size;for(let l of n.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await Vt(e,n.id,"operation-started",l.id),await ox(e,n,l,i),await Vt(e,n.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return n=await gg(e,n.id),n}async function lx(e){if(e.operation.type!=="write")return;let t=await Pt(e.paths,e.journal,e.operation,e.target);if(!await fe(t.candidate))return;let i=await ii({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await _r({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Or,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function mg(e,t,i){let n=await Re(e,i.target);if(i.type==="write"){let r=await Pt(e,t,i,n),a=await ft({paths:e,file:r.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await ye({paths:e,file:n,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await $e({target:n,expectedHash:null,label:`Archive commit target ${i.target}`})}async function ux(e,t){for(let i of t.operations){if(i.type==="move")continue;let n=await Re(e,i.target),r=await Pt(e,t,i,n);if(await fe(r.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await mg(e,t,i),i.expectedTargetHash!==null){let a=await ft({paths:e,file:r.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await fe(r.originalQuarantine)&&await _r({paths:e,file:r.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await lx({paths:e,journal:t,operation:i,target:n})}for(let i of t.operations)i.type!=="move"&&await mg(e,t,i)}async function Wo(e,t,i){return i==="commit"&&await ux(e,t),await Vt(e,t.id,i),i==="commit"?wg(e,t,"committed"):t}import{promises as fx}from"fs";import dx from"path";var Ru="comet.selection.v2",hx=16*1024;function Pu(e){return dx.join(e,".comet","current-change.json")}function px(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function bg(e){return e===null||typeof e=="string"}function mx(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!px(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!bg(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Ru,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Ru)throw new Error(`current change selection schema must be ${Ru}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!bg(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Sg(e){let t;try{let n=Pu(e),{bytes:r}=await fi(n,hx,{label:"current change selection"});t=r.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...mx(t)}}async function kg(e){await fx.rm(Pu(e),{force:!0})}async function Eg(e,t,i){let n=await Sg(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==i?!1:(await kg(e),!0)}var P1=16*1024;async function Cg(e,t){return await Fi(e.projectRoot),Eg(e.projectRoot,"native",t)}var yx=16*1024*1024,$r=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"},mn=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"};async function Nx(e){try{return await il(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function bx(e){if(e.phase!=="archive")throw new Error(`Native change ${e.name} is not in Archive`);if(e.verification_result!=="pass")throw new Error(`Native change ${e.name} has not passed verification`);if(!e.verification_report)throw new Error(`Native change ${e.name} has no verification report`);if(e.archived)throw new Error(`Native change ${e.name} is already archived`)}async function Sx(e,t){let i=W(e,t.name),n=await wm(i,t.brief),r=await ym(i,t.verification_report),a=[...n.findings,...r.findings];if(a.length>0)throw new Error(`Native archive artifacts are invalid: ${a[0].message}`)}async function kx(e,t){let i=Nr(e,t.capability);await H(e.nativeRoot,i);let n=await Nx(i),r=t.operation==="create"?null:t.base_hash;if(n!==r)throw new $r(t.capability,r,n,i)}function Ex(e,t,i){return pn.join(e.archiveDir,`${i.toISOString().slice(0,10)}-${t}`)}async function Cx(e){try{return await gx.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Rx(e){let{paths:t,state:i,now:n,transactionId:r,preflight:a}=e,o=Ex(t,i.name,n);if(await Cx(o))throw new Error(`Native archive target already exists: ${o}`);if(vt(t,o)!==a.targetRef)throw new Error("Native Archive target changed after preflight");let s=await Ge(t,r),c=[];for(let[f,u]of i.spec_changes.entries()){await kx(t,u);let d=Nr(t,u.capability),p=a.operations.find(y=>y.capability===u.capability&&y.operation===u.operation);if(!p)throw new Error(`Native Archive preflight has no operation for ${u.capability}`);if(u.operation!=="remove"&&p.proposedHash===null)throw new Error(`Native Archive preflight has no proposed hash for ${u.capability}`);let m=pn.join(s.backups,"specs",u.capability,"spec.md");if(u.operation==="remove"){c.push({id:`spec-${f+1}-${u.capability}`,type:"remove",target:vt(t,d),backup:vt(t,m),expectedTargetHash:u.base_hash});continue}let h=W(t,i.name);await Nm(h,u.source);let v=pn.resolve(h,...u.source.split(/[\\/]/u)),w=pn.join(s.staged,"specs",u.capability,"spec.md"),N=(await hi({sourceRoot:h,source:v,targetRoot:t.nativeRoot,target:w,maxBytes:yx,label:`Native Archive proposed spec ${u.capability}`,expectedHash:p.proposedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("stage",u.source)}})).hash;if(N!==p.proposedHash)throw new Error(`Proposed Native spec changed after preflight: ${u.capability}`);c.push({id:`spec-${f+1}-${u.capability}`,type:"write",target:vt(t,d),staged:vt(t,w),...u.operation==="replace"?{backup:vt(t,m)}:{},expectedTargetHash:u.operation==="create"?null:u.base_hash,stagedHash:N})}let l=W(t,i.name);return c.push({id:"archive-change",type:"move",source:vt(t,l),target:vt(t,o),expectedSourceHash:await ku(l),expectedTargetHash:null}),{schema:"comet.native.transaction.v2",id:r,kind:"archive",status:"prepared",change:i.name,createdAt:n.toISOString(),preflightHash:a.preflightHash,operations:c}}function Au(e,t){let i=t.operations.find(n=>n.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return pn.resolve(e.nativeRoot,...i.target.split("/"))}async function Rg(e,t,i){let n=await Ki(e,t.id);if(n.some(h=>h.type==="archive-finalized"))return;let r=n.some(h=>h.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!r){let h=t.operations.find(w=>w.id==="archive-change");if(!h||h.type!=="move"||!h.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let v=await ti(Au(e,t));if(v?.kind!=="directory"||v.hash!==h.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=Au(e,t),o=pn.join(a,wt),s=await hm(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=await Zi(a);if(!c||c.runId!==s.run_id||c.currentStep!=="archive"&&!(c.currentStep===null&&c.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let l=c;if(c.currentStep==="archive"){let h=Mu(Qt,c,new Set,Ql,void 0);if(!h.action)throw new Error(h.reason??"Native archive produced no action");l=Du(Qt,h.state,{actionId:h.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},Ql,void 0)}let f=J(`archive:${t.id}:${s.name}`),u=await pi(a,l.trajectoryRef),d=u.filter(h=>h.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(d.length>1||d.some(h=>h.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let p=d.find(h=>h.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:f,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(p&&t.schema==="comet.native.transaction.v2"&&(!wx(p.data,m)||p.runId!==l.runId||p.timestamp!==t.createdAt||p!==u.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!r&&(s.archived||c.currentStep===null||d.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(r||(t.schema==="comet.native.transaction.v2"?(await Wo(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await ro(e,t,"archive-finalization-started")),!s.archived){let h={...s,archived:!0};await dm(o,h)}p||(p=await Rr({changeDir:a,run:l,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await Io({changeDir:a,run:l,trajectoryOffset:p.sequence,evidenceHash:f,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await po(a,l),await Cg(e,s.name),t.schema==="comet.native.transaction.v2"?await Wo(e,t,"archive-finalized"):await ro(e,t,"archive-finalized")}async function Px(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Ki(e,t.id)).some(o=>o.type==="operation-started")){let o=await Ir({paths:e,name:t.change,now:new Date(t.createdAt)});if(!o.ready||o.preflightHash!==t.preflightHash)throw new mn(o,"Native Archive facts changed before the first transaction operation")}let a=await Ng(e,t,{...i,beforeArchiveChangeMove:async o=>{await i?.beforeArchiveChangeMove?.(o);let s=await ue(e,t.change),c=await qo({paths:e,state:s,now:new Date(t.createdAt)});if(s.phase!=="archive"||s.archived||s.verification_result!=="pass"||!["complete","partial"].includes(c.freshness)||c.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${c.findingCodes.join(", ")||c.freshness}`)}});return await Rg(e,a,i),Wo(e,a,"commit")}let n=await Sp(e,t);return await Rg(e,n,i),ro(e,n,"commit")}async function Pg(e){return zt(e.paths,`archive ${e.name}`,()=>jo(e.paths,e.name,`archive ${e.name}`,async()=>{await yu(e.paths,e.name);let t=await Bi(e.paths,"archive",`archive ${e.name}`);try{if(!/^[a-f0-9]{64}$/u.test(e.expectedPreflightHash))throw new Error("Native Archive expected preflight must be a SHA-256 hash");let i=e.now??new Date,n=await Ir({paths:e.paths,name:e.name,now:i});if(!n.ready||n.preflightHash!==e.expectedPreflightHash)throw new mn(n);let r=await ue(e.paths,e.name);bx(r),await Sx(e.paths,r);let a=vx(),o=await Rx({paths:e.paths,state:r,now:i,transactionId:a,preflight:n,hooks:e.hooks});return await vg(e.paths,o),await e.hooks?.afterPrepared?.(o),await Px(e.paths,o,e.hooks),{archiveDir:Au(e.paths,o),transactionId:a,preflightHash:n.preflightHash}}finally{await qi(t)}}))}var Ax=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function xx(e){return e.phase==="shape"?["summary","shared-understanding-confirmation"]:e.phase==="build"?e.approval==="confirmed"?["summary","artifact-or-no-code-reason"]:["summary","artifact-or-no-code-reason","shared-understanding-confirmation"]:e.phase==="verify"?["summary","verification-result","verification-report"]:[]}function xu(e){let i=(e.findings??[]).filter(l=>!im(l.code)),n=i.find(l=>l.requiresUserDecision),r=i.find(l=>l.repairCommand!==null||Ax.test(l.code)),a=i.find(l=>l.code==="repair-iteration-limit"||l.code==="repair-override-exhausted"),o=i.find(l=>l.code==="repair-stagnation-stop"),s=[...new Set(i.map(l=>l.requiredAction))].sort();if(e.done)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"done",action:"none",command:null,requiresUserDecision:!1,requiredInputs:[]};if(a)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"work-phase",command:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"]};if(n)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"work-phase",command:null,requiresUserDecision:!0,requiredInputs:s};if(o)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"repair",command:null,requiresUserDecision:!1,requiredInputs:["new-repair-hypothesis"]};if(r)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"repair",command:r.repairCommand,requiresUserDecision:!1,requiredInputs:s};if(e.evidenceRetreat)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"advance-phase",command:`comet native next ${e.state.name} --summary "<summary>"`,requiresUserDecision:!1,requiredInputs:["summary"]};if(e.state.phase==="build"&&e.state.verification_result==="fail")return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:null,requiresUserDecision:!1,requiredInputs:["repair-verification-gaps"]};if(i.length>0)return e.state.phase==="archive"?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"none",command:null,requiresUserDecision:!1,requiredInputs:s}:s.includes("refresh-verification-receipts")?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:`comet native receipt refresh ${e.state.name} --apply`,requiresUserDecision:!1,requiredInputs:s}:{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:null,requiresUserDecision:!1,requiredInputs:s};if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");return e.archiveConfirmation==="required"?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"archive",command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"]}:{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"archive",command:`comet native archive ${e.state.name} --expect-preflight ${e.archivePreflightHash}`,requiresUserDecision:!1,requiredInputs:[]}}return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",command:e.archiveReady?`comet native archive ${e.state.name} --dry-run`:null,requiresUserDecision:!1,requiredInputs:e.archiveReady?[]:["archive-readiness"]}}let c=e.state.phase==="shape"||e.state.phase==="build"&&e.state.approval!=="confirmed"?" --confirmed":"";return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"advance-phase",command:`comet native next ${e.state.name} --summary "<summary>"${c}`,requiresUserDecision:!1,requiredInputs:xx(e.state)}}import Tx from"path";var uL=10*1024*1024,Ae=class extends Error{};function Hr(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new Ae(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Jo(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Ae(`${t} may only be provided once`);if(i.length===0)return;let n=i[0],r=e[n+1];if(r===void 0||r.startsWith("--"))throw new Ae(`${t} requires a value`);return e.splice(n,2),r}function Ag(e){if(e.length>0)throw new Ae(`Unexpected argument: ${e[0]}`)}function xg(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new Ae(`${t} is required`);return i}async function Tg(e){return e?Tx.resolve(e):Ga(process.cwd())}async function Ig(e){let t=await Wh({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Tu(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
|
|
172
|
+
`}}function _g(e,t){if(t instanceof Ae)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof $r)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof mn)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof mr)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof vo)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof ei)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Og(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
173
|
+
`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function jg(e,t){let i=xg(e,"change name"),n=Hr(e,"--dry-run"),r=Jo(e,"--expect-preflight"),a=Hr(e,"--confirmed");if(n&&r)throw new Ae("--dry-run and --expect-preflight cannot be combined");if(n&&a)throw new Ae("--confirmed is only valid with --expect-preflight");if(!n&&!r)throw new Ae("archive requires --dry-run or --expect-preflight <sha256>");if(r&&!/^[a-f0-9]{64}$/u.test(r))throw new Ae("--expect-preflight must be a SHA-256 hash");Ag(e);let{config:o,paths:s}=await Ig(t);if(n){let f=await Ir({paths:s,name:i}),u=await ue(s,i);return Tu("archive --dry-run",{...f,continuation:xu({state:u,archiveReady:f.ready,archiveConfirmation:f.archiveConfirmation,archivePreflightHash:f.preflightHash})},`Native Archive preview ${f.preflightHash}: ${f.ready?"ready":"blocked"}
|
|
174
|
+
`)}if(o.native.archive_confirmation==="required"&&!a)throw new Ae("archive requires --confirmed when native.archive_confirmation is required");let c=await ue(s,i),l=await Pg({paths:s,name:i,expectedPreflightHash:r});return Tu("archive",{...l,continuation:xu({state:c,done:!0})},`Archived Native change ${i} to ${l.archiveDir}
|
|
175
|
+
`)}function Ix(e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
176
|
+
`}}async function $g(e,t,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{Hr(r,"--json"),s=Jo(r,"--project-root");let f=[...r,...a],u=await Tg(s);c=await t(f,u)}catch(f){c=_g(e,f)}let l=o?Ix(c):Og(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
|
|
177
|
+
`)?"":`
|
|
178
|
+
`)),l.exitCode}process.exitCode=await $g("archive",jg);
|