@rpamis/comet 0.4.0-beta.15 → 0.4.0-beta.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -33
- package/assets/eval-reports/comet-native-vs-beta16-beta17-20260810/native-benchmark-report.html +8 -0
- package/assets/eval-reports/comet-native-vs-beta16-beta17-20260810/native-benchmark-report.json +286 -0
- package/assets/manifest.json +25 -17
- package/assets/skills/comet/SKILL.md +1 -1
- package/assets/skills/comet/agents/openai.yaml +3 -0
- package/assets/skills/comet/rules/comet-phase-guard.en.md +1 -1
- package/assets/skills/comet/rules/comet-phase-guard.md +1 -1
- package/assets/skills/comet/rules/comet-workflow-guard.en.md +2 -2
- package/assets/skills/comet/rules/comet-workflow-guard.md +2 -2
- package/assets/skills/comet/scripts/comet-archive.mjs +75 -75
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +47 -47
- package/assets/skills/comet/scripts/comet-guard.mjs +119 -119
- package/assets/skills/comet/scripts/comet-handoff.mjs +80 -80
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +78 -78
- package/assets/skills/comet/scripts/comet-hook-router.mjs +142 -140
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +89 -89
- package/assets/skills/comet/scripts/comet-runtime.mjs +148 -148
- package/assets/skills/comet/scripts/comet-state.mjs +72 -72
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +94 -94
- package/assets/skills/comet-any/SKILL.md +2 -1
- package/assets/skills/comet-any/agents/openai.yaml +5 -0
- package/assets/skills/comet-archive/SKILL.md +7 -6
- package/assets/skills/comet-archive/agents/openai.yaml +5 -0
- package/assets/skills/comet-build/SKILL.md +14 -13
- package/assets/skills/comet-build/agents/openai.yaml +5 -0
- package/assets/skills/comet-classic/SKILL.md +14 -14
- package/assets/skills/comet-classic/agents/openai.yaml +3 -0
- package/assets/skills/{comet → comet-classic}/reference/auto-transition.md +1 -1
- package/assets/skills/{comet → comet-classic}/reference/comet-yaml-fields.md +2 -2
- package/assets/skills/{comet → comet-classic}/reference/context-recovery.md +5 -5
- package/assets/skills/{comet → comet-classic}/reference/debug-gate.md +2 -2
- package/assets/skills/{comet → comet-classic}/reference/decision-point.md +1 -1
- package/assets/skills/{comet → comet-classic}/reference/dirty-worktree.md +1 -1
- package/assets/skills/{comet → comet-classic}/reference/file-structure.md +1 -1
- package/assets/skills/{comet → comet-classic}/reference/intent-frame.md +1 -1
- package/assets/skills/{comet → comet-classic}/reference/scripts.md +1 -1
- package/assets/skills/{comet → comet-classic}/reference/subagent-dispatch.md +1 -1
- package/assets/skills/comet-design/SKILL.md +7 -6
- package/assets/skills/comet-design/agents/openai.yaml +5 -0
- package/assets/skills/comet-hotfix/SKILL.md +10 -9
- package/assets/skills/comet-hotfix/agents/openai.yaml +5 -0
- package/assets/skills/comet-native/SKILL.md +54 -168
- package/assets/skills/comet-native/agents/openai.yaml +3 -0
- package/assets/skills/comet-native/reference/artifacts.md +23 -89
- package/assets/skills/comet-native/reference/clarification.md +54 -29
- package/assets/skills/comet-native/reference/commands.md +30 -173
- package/assets/skills/comet-native/reference/recovery.md +38 -88
- package/assets/skills/comet-native/reference/workspace.md +23 -0
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +184 -152
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +219 -163
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +125 -116
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +134 -124
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +170 -163
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +179 -148
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +152 -147
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +247 -202
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +153 -146
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +117 -110
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +133 -151
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +146 -139
- package/assets/skills/comet-open/SKILL.md +7 -6
- package/assets/skills/comet-open/agents/openai.yaml +5 -0
- package/assets/skills/comet-tweak/SKILL.md +11 -10
- package/assets/skills/comet-tweak/agents/openai.yaml +5 -0
- package/assets/skills/comet-verify/SKILL.md +9 -8
- package/assets/skills/comet-verify/agents/openai.yaml +5 -0
- package/assets/skills-zh/comet/SKILL.md +1 -1
- package/assets/skills-zh/comet/agents/openai.yaml +3 -0
- package/assets/skills-zh/comet-any/SKILL.md +2 -1
- package/assets/skills-zh/comet-any/agents/openai.yaml +5 -0
- package/assets/skills-zh/comet-archive/SKILL.md +7 -6
- package/assets/skills-zh/comet-archive/agents/openai.yaml +5 -0
- package/assets/skills-zh/comet-build/SKILL.md +14 -13
- package/assets/skills-zh/comet-build/agents/openai.yaml +5 -0
- package/assets/skills-zh/comet-classic/SKILL.md +15 -15
- package/assets/skills-zh/comet-classic/agents/openai.yaml +3 -0
- package/assets/skills-zh/{comet → comet-classic}/reference/auto-transition.md +1 -1
- package/assets/skills-zh/{comet → comet-classic}/reference/comet-yaml-fields.md +2 -2
- package/assets/skills-zh/{comet → comet-classic}/reference/context-recovery.md +5 -5
- package/assets/skills-zh/{comet → comet-classic}/reference/debug-gate.md +2 -2
- package/assets/skills-zh/{comet → comet-classic}/reference/decision-point.md +1 -1
- package/assets/skills-zh/{comet → comet-classic}/reference/dirty-worktree.md +1 -1
- package/assets/skills-zh/{comet → comet-classic}/reference/file-structure.md +1 -1
- package/assets/skills-zh/{comet → comet-classic}/reference/intent-frame.md +1 -1
- package/assets/skills-zh/{comet → comet-classic}/reference/scripts.md +1 -1
- package/assets/skills-zh/{comet → comet-classic}/reference/subagent-dispatch.md +1 -1
- package/assets/skills-zh/comet-design/SKILL.md +7 -6
- package/assets/skills-zh/comet-design/agents/openai.yaml +5 -0
- package/assets/skills-zh/comet-hotfix/SKILL.md +10 -9
- package/assets/skills-zh/comet-hotfix/agents/openai.yaml +5 -0
- package/assets/skills-zh/comet-native/SKILL.md +54 -168
- package/assets/skills-zh/comet-native/agents/openai.yaml +3 -0
- package/assets/skills-zh/comet-native/reference/artifacts.md +23 -89
- package/assets/skills-zh/comet-native/reference/clarification.md +40 -15
- package/assets/skills-zh/comet-native/reference/commands.md +30 -173
- package/assets/skills-zh/comet-native/reference/recovery.md +36 -86
- package/assets/skills-zh/comet-native/reference/workspace.md +23 -0
- package/assets/skills-zh/comet-open/SKILL.md +7 -6
- package/assets/skills-zh/comet-open/agents/openai.yaml +5 -0
- package/assets/skills-zh/comet-tweak/SKILL.md +11 -10
- package/assets/skills-zh/comet-tweak/agents/openai.yaml +5 -0
- package/assets/skills-zh/comet-verify/SKILL.md +9 -8
- package/assets/skills-zh/comet-verify/agents/openai.yaml +5 -0
- package/bin/fast-runtime-router.js +0 -4
- package/dist/app/commands/doctor.d.ts.map +1 -1
- package/dist/app/commands/doctor.js +16 -2
- package/dist/app/commands/doctor.js.map +1 -1
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +9 -1
- package/dist/app/commands/init.js.map +1 -1
- package/dist/app/commands/update.d.ts.map +1 -1
- package/dist/app/commands/update.js +9 -2
- package/dist/app/commands/update.js.map +1 -1
- package/dist/config/repository-layout.json +0 -8
- package/dist/domains/bundle/bundle-platform.d.ts.map +1 -1
- package/dist/domains/bundle/bundle-platform.js +8 -0
- package/dist/domains/bundle/bundle-platform.js.map +1 -1
- package/dist/domains/bundle/types.d.ts +1 -1
- package/dist/domains/bundle/types.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-evidence.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-evidence.js +45 -9
- package/dist/domains/comet-classic/classic-evidence.js.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.d.ts +4 -3
- package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.js +13 -9
- package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
- package/dist/domains/comet-classic/classic-layout.d.ts +2 -11
- package/dist/domains/comet-classic/classic-layout.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout.js +22 -28
- package/dist/domains/comet-classic/classic-layout.js.map +1 -1
- package/dist/domains/comet-classic/classic-root-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-root-command.js +6 -1
- package/dist/domains/comet-classic/classic-root-command.js.map +1 -1
- package/dist/domains/comet-entry/hook-adapter.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-adapter.js +6 -0
- package/dist/domains/comet-entry/hook-adapter.js.map +1 -1
- package/dist/domains/comet-entry/hook-router-entry.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-router-entry.js +11 -2
- package/dist/domains/comet-entry/hook-router-entry.js.map +1 -1
- package/dist/domains/comet-entry/project-activation.d.ts.map +1 -1
- package/dist/domains/comet-entry/project-activation.js +2 -1
- package/dist/domains/comet-entry/project-activation.js.map +1 -1
- package/dist/domains/comet-entry/resume-probe.d.ts.map +1 -1
- package/dist/domains/comet-entry/resume-probe.js +48 -4
- package/dist/domains/comet-entry/resume-probe.js.map +1 -1
- package/dist/domains/comet-native/native-acceptance.d.ts +4 -3
- package/dist/domains/comet-native/native-acceptance.d.ts.map +1 -1
- package/dist/domains/comet-native/native-acceptance.js +23 -18
- package/dist/domains/comet-native/native-acceptance.js.map +1 -1
- package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-archive-command.js +204 -61
- package/dist/domains/comet-native/native-archive-command.js.map +1 -1
- package/dist/domains/comet-native/native-archive-transaction.d.ts.map +1 -1
- package/dist/domains/comet-native/native-archive-transaction.js +28 -23
- package/dist/domains/comet-native/native-archive-transaction.js.map +1 -1
- package/dist/domains/comet-native/native-archive.d.ts +1 -0
- package/dist/domains/comet-native/native-archive.d.ts.map +1 -1
- package/dist/domains/comet-native/native-archive.js +56 -12
- package/dist/domains/comet-native/native-archive.js.map +1 -1
- package/dist/domains/comet-native/native-bounded-file.d.ts +32 -2
- package/dist/domains/comet-native/native-bounded-file.d.ts.map +1 -1
- package/dist/domains/comet-native/native-bounded-file.js +87 -6
- package/dist/domains/comet-native/native-bounded-file.js.map +1 -1
- package/dist/domains/comet-native/native-build-evidence.d.ts.map +1 -1
- package/dist/domains/comet-native/native-build-evidence.js +23 -1
- package/dist/domains/comet-native/native-build-evidence.js.map +1 -1
- package/dist/domains/comet-native/native-change.d.ts +1 -0
- package/dist/domains/comet-native/native-change.d.ts.map +1 -1
- package/dist/domains/comet-native/native-change.js +96 -8
- package/dist/domains/comet-native/native-change.js.map +1 -1
- package/dist/domains/comet-native/native-check-executor.d.ts +36 -0
- package/dist/domains/comet-native/native-check-executor.d.ts.map +1 -0
- package/dist/domains/comet-native/native-check-executor.js +132 -0
- package/dist/domains/comet-native/native-check-executor.js.map +1 -0
- package/dist/domains/comet-native/native-check-receipt-model.d.ts +9 -0
- package/dist/domains/comet-native/native-check-receipt-model.d.ts.map +1 -1
- package/dist/domains/comet-native/native-check-receipt-model.js +70 -8
- package/dist/domains/comet-native/native-check-receipt-model.js.map +1 -1
- package/dist/domains/comet-native/native-check-receipt-storage.d.ts.map +1 -1
- package/dist/domains/comet-native/native-check-receipt-storage.js +9 -8
- package/dist/domains/comet-native/native-check-receipt-storage.js.map +1 -1
- package/dist/domains/comet-native/native-check-receipt.d.ts.map +1 -1
- package/dist/domains/comet-native/native-check-receipt.js +123 -60
- package/dist/domains/comet-native/native-check-receipt.js.map +1 -1
- package/dist/domains/comet-native/native-checkpoint-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-checkpoint-command.js +0 -6
- package/dist/domains/comet-native/native-checkpoint-command.js.map +1 -1
- package/dist/domains/comet-native/native-checkpoint-storage.d.ts.map +1 -1
- package/dist/domains/comet-native/native-checkpoint-storage.js +27 -19
- package/dist/domains/comet-native/native-checkpoint-storage.js.map +1 -1
- package/dist/domains/comet-native/native-cli-help.d.ts +6 -0
- package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -0
- package/dist/domains/comet-native/native-cli-help.js +192 -0
- package/dist/domains/comet-native/native-cli-help.js.map +1 -0
- package/dist/domains/comet-native/native-cli-shared.d.ts +2 -2
- package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-shared.js +46 -24
- package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
- package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli.js +18 -11
- package/dist/domains/comet-native/native-cli.js.map +1 -1
- package/dist/domains/comet-native/native-config.d.ts +2 -1
- package/dist/domains/comet-native/native-config.d.ts.map +1 -1
- package/dist/domains/comet-native/native-config.js +2 -1
- package/dist/domains/comet-native/native-config.js.map +1 -1
- package/dist/domains/comet-native/native-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-continuation.js +175 -147
- package/dist/domains/comet-native/native-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-diagnostics.d.ts.map +1 -1
- package/dist/domains/comet-native/native-diagnostics.js +96 -13
- package/dist/domains/comet-native/native-diagnostics.js.map +1 -1
- package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-doctor-command.js +327 -0
- package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
- package/dist/domains/comet-native/native-doctor.d.ts +1 -0
- package/dist/domains/comet-native/native-doctor.d.ts.map +1 -1
- package/dist/domains/comet-native/native-doctor.js +116 -22
- package/dist/domains/comet-native/native-doctor.js.map +1 -1
- package/dist/domains/comet-native/native-evidence-projection.d.ts +50 -0
- package/dist/domains/comet-native/native-evidence-projection.d.ts.map +1 -0
- package/dist/domains/comet-native/native-evidence-projection.js +284 -0
- package/dist/domains/comet-native/native-evidence-projection.js.map +1 -0
- package/dist/domains/comet-native/native-evidence-retention.d.ts.map +1 -1
- package/dist/domains/comet-native/native-evidence-retention.js +14 -12
- package/dist/domains/comet-native/native-evidence-retention.js.map +1 -1
- package/dist/domains/comet-native/native-evidence-storage.d.ts.map +1 -1
- package/dist/domains/comet-native/native-evidence-storage.js +14 -11
- 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-git-provenance.d.ts +16 -0
- package/dist/domains/comet-native/native-git-provenance.d.ts.map +1 -0
- package/dist/domains/comet-native/native-git-provenance.js +171 -0
- package/dist/domains/comet-native/native-git-provenance.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 +159 -18
- package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
- package/dist/domains/comet-native/native-init-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-init-command.js +14 -2
- package/dist/domains/comet-native/native-init-command.js.map +1 -1
- package/dist/domains/comet-native/native-local-execution.d.ts +25 -0
- package/dist/domains/comet-native/native-local-execution.d.ts.map +1 -0
- package/dist/domains/comet-native/native-local-execution.js +241 -0
- package/dist/domains/comet-native/native-local-execution.js.map +1 -0
- package/dist/domains/comet-native/native-lock.d.ts +1 -1
- package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
- package/dist/domains/comet-native/native-lock.js +9 -9
- package/dist/domains/comet-native/native-lock.js.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.d.ts +63 -0
- package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -0
- package/dist/domains/comet-native/native-loop-runtime.js +580 -0
- package/dist/domains/comet-native/native-loop-runtime.js.map +1 -0
- package/dist/domains/comet-native/native-mutation-lock.d.ts +2 -0
- package/dist/domains/comet-native/native-mutation-lock.d.ts.map +1 -1
- package/dist/domains/comet-native/native-mutation-lock.js +23 -2
- package/dist/domains/comet-native/native-mutation-lock.js.map +1 -1
- package/dist/domains/comet-native/native-new-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-new-command.js +27 -20
- package/dist/domains/comet-native/native-new-command.js.map +1 -1
- package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-next-command.js +114 -63
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-paths.d.ts +18 -0
- package/dist/domains/comet-native/native-paths.d.ts.map +1 -1
- package/dist/domains/comet-native/native-paths.js +125 -13
- package/dist/domains/comet-native/native-paths.js.map +1 -1
- package/dist/domains/comet-native/native-portable-acceptance.d.ts +28 -0
- package/dist/domains/comet-native/native-portable-acceptance.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-acceptance.js +73 -0
- package/dist/domains/comet-native/native-portable-acceptance.js.map +1 -0
- package/dist/domains/comet-native/native-portable-archive.d.ts +37 -0
- package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-archive.js +492 -0
- package/dist/domains/comet-native/native-portable-archive.js.map +1 -0
- package/dist/domains/comet-native/native-portable-continuation.d.ts +29 -0
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-continuation.js +341 -0
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -0
- package/dist/domains/comet-native/native-portable-migration-runtime.d.ts +9 -0
- package/dist/domains/comet-native/native-portable-migration-runtime.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-migration-runtime.js +213 -0
- package/dist/domains/comet-native/native-portable-migration-runtime.js.map +1 -0
- package/dist/domains/comet-native/native-portable-migration.d.ts +42 -0
- package/dist/domains/comet-native/native-portable-migration.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-migration.js +212 -0
- package/dist/domains/comet-native/native-portable-migration.js.map +1 -0
- package/dist/domains/comet-native/native-portable-recovery.d.ts +15 -0
- package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-recovery.js +203 -0
- package/dist/domains/comet-native/native-portable-recovery.js.map +1 -0
- package/dist/domains/comet-native/native-portable-runtime.d.ts +150 -0
- package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-runtime.js +1444 -0
- package/dist/domains/comet-native/native-portable-runtime.js.map +1 -0
- package/dist/domains/comet-native/native-portable-state.d.ts +30 -0
- package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-state.js +688 -0
- package/dist/domains/comet-native/native-portable-state.js.map +1 -0
- package/dist/domains/comet-native/native-portable-status.d.ts +62 -0
- package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-status.js +125 -0
- package/dist/domains/comet-native/native-portable-status.js.map +1 -0
- package/dist/domains/comet-native/native-portable-text.d.ts +8 -0
- package/dist/domains/comet-native/native-portable-text.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-text.js +28 -0
- package/dist/domains/comet-native/native-portable-text.js.map +1 -0
- package/dist/domains/comet-native/native-portable-transactions.d.ts +41 -0
- package/dist/domains/comet-native/native-portable-transactions.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-transactions.js +204 -0
- package/dist/domains/comet-native/native-portable-transactions.js.map +1 -0
- package/dist/domains/comet-native/native-portable-types.d.ts +165 -0
- package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-types.js +18 -0
- package/dist/domains/comet-native/native-portable-types.js.map +1 -0
- package/dist/domains/comet-native/native-repair-integration.js +5 -5
- package/dist/domains/comet-native/native-repair-integration.js.map +1 -1
- package/dist/domains/comet-native/native-resume-view.d.ts.map +1 -1
- package/dist/domains/comet-native/native-resume-view.js +1 -5
- package/dist/domains/comet-native/native-resume-view.js.map +1 -1
- package/dist/domains/comet-native/native-root-move.d.ts.map +1 -1
- package/dist/domains/comet-native/native-root-move.js +4 -20
- package/dist/domains/comet-native/native-root-move.js.map +1 -1
- package/dist/domains/comet-native/native-run-consistency.d.ts.map +1 -1
- package/dist/domains/comet-native/native-run-consistency.js +8 -12
- package/dist/domains/comet-native/native-run-consistency.js.map +1 -1
- package/dist/domains/comet-native/native-run-store.js +4 -4
- package/dist/domains/comet-native/native-run-store.js.map +1 -1
- package/dist/domains/comet-native/native-runner-input.d.ts +160 -0
- package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -0
- package/dist/domains/comet-native/native-runner-input.js +347 -0
- package/dist/domains/comet-native/native-runner-input.js.map +1 -0
- package/dist/domains/comet-native/native-runner-protocol.d.ts +40 -0
- package/dist/domains/comet-native/native-runner-protocol.d.ts.map +1 -0
- package/dist/domains/comet-native/native-runner-protocol.js +55 -0
- package/dist/domains/comet-native/native-runner-protocol.js.map +1 -0
- package/dist/domains/comet-native/native-runtime-package.d.ts +3 -0
- package/dist/domains/comet-native/native-runtime-package.d.ts.map +1 -1
- package/dist/domains/comet-native/native-runtime-package.js +5 -1
- package/dist/domains/comet-native/native-runtime-package.js.map +1 -1
- package/dist/domains/comet-native/native-schema-migration.d.ts.map +1 -1
- package/dist/domains/comet-native/native-schema-migration.js +30 -27
- package/dist/domains/comet-native/native-schema-migration.js.map +1 -1
- package/dist/domains/comet-native/native-select-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-select-command.js +8 -4
- package/dist/domains/comet-native/native-select-command.js.map +1 -1
- package/dist/domains/comet-native/native-selection.d.ts.map +1 -1
- package/dist/domains/comet-native/native-selection.js +11 -2
- package/dist/domains/comet-native/native-selection.js.map +1 -1
- package/dist/domains/comet-native/native-show-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-show-command.js +36 -0
- package/dist/domains/comet-native/native-show-command.js.map +1 -1
- package/dist/domains/comet-native/native-snapshot.d.ts.map +1 -1
- package/dist/domains/comet-native/native-snapshot.js +13 -10
- package/dist/domains/comet-native/native-snapshot.js.map +1 -1
- package/dist/domains/comet-native/native-spec-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-spec-command.js +14 -28
- package/dist/domains/comet-native/native-spec-command.js.map +1 -1
- package/dist/domains/comet-native/native-specs.js +3 -3
- package/dist/domains/comet-native/native-specs.js.map +1 -1
- package/dist/domains/comet-native/native-status-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-status-command.js +7 -17
- package/dist/domains/comet-native/native-status-command.js.map +1 -1
- package/dist/domains/comet-native/native-status-discovery.d.ts +51 -0
- package/dist/domains/comet-native/native-status-discovery.d.ts.map +1 -0
- package/dist/domains/comet-native/native-status-discovery.js +299 -0
- package/dist/domains/comet-native/native-status-discovery.js.map +1 -0
- package/dist/domains/comet-native/native-trajectory-recovery.d.ts.map +1 -1
- package/dist/domains/comet-native/native-trajectory-recovery.js +6 -9
- package/dist/domains/comet-native/native-trajectory-recovery.js.map +1 -1
- package/dist/domains/comet-native/native-transaction.d.ts.map +1 -1
- package/dist/domains/comet-native/native-transaction.js +31 -20
- package/dist/domains/comet-native/native-transaction.js.map +1 -1
- package/dist/domains/comet-native/native-transition-evidence.d.ts.map +1 -1
- package/dist/domains/comet-native/native-transition-evidence.js +1 -0
- package/dist/domains/comet-native/native-transition-evidence.js.map +1 -1
- package/dist/domains/comet-native/native-transition-journal.d.ts.map +1 -1
- package/dist/domains/comet-native/native-transition-journal.js +71 -22
- package/dist/domains/comet-native/native-transition-journal.js.map +1 -1
- package/dist/domains/comet-native/native-transitions.d.ts.map +1 -1
- package/dist/domains/comet-native/native-transitions.js +167 -15
- package/dist/domains/comet-native/native-transitions.js.map +1 -1
- package/dist/domains/comet-native/native-types.d.ts +36 -1
- package/dist/domains/comet-native/native-types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-verification-receipt-runtime.js +18 -100
- package/dist/domains/comet-native/native-verification-receipt-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-verification-report-v2.d.ts +12 -0
- package/dist/domains/comet-native/native-verification-report-v2.d.ts.map +1 -0
- package/dist/domains/comet-native/native-verification-report-v2.js +141 -0
- package/dist/domains/comet-native/native-verification-report-v2.js.map +1 -0
- package/dist/domains/comet-native/native-verification-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-verification-runtime.js +7 -2
- package/dist/domains/comet-native/native-verification-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-verification-scope.d.ts +23 -0
- package/dist/domains/comet-native/native-verification-scope.d.ts.map +1 -1
- package/dist/domains/comet-native/native-verification-scope.js +106 -19
- package/dist/domains/comet-native/native-verification-scope.js.map +1 -1
- package/dist/domains/comet-native/native-verifier-protocol.d.ts +49 -0
- package/dist/domains/comet-native/native-verifier-protocol.d.ts.map +1 -0
- package/dist/domains/comet-native/native-verifier-protocol.js +157 -0
- package/dist/domains/comet-native/native-verifier-protocol.js.map +1 -0
- package/dist/domains/comet-native/native-workspace-finish.d.ts +61 -0
- package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -0
- package/dist/domains/comet-native/native-workspace-finish.js +332 -0
- package/dist/domains/comet-native/native-workspace-finish.js.map +1 -0
- package/dist/domains/comet-native/native-workspace-preparation.d.ts +32 -0
- package/dist/domains/comet-native/native-workspace-preparation.d.ts.map +1 -0
- package/dist/domains/comet-native/native-workspace-preparation.js +265 -0
- package/dist/domains/comet-native/native-workspace-preparation.js.map +1 -0
- package/dist/domains/comet-native/native-workspace.d.ts +9 -1
- package/dist/domains/comet-native/native-workspace.d.ts.map +1 -1
- package/dist/domains/comet-native/native-workspace.js +109 -11
- package/dist/domains/comet-native/native-workspace.js.map +1 -1
- package/dist/domains/dashboard/native-adapter.d.ts +136 -127
- package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
- package/dist/domains/dashboard/native-adapter.js +157 -271
- package/dist/domains/dashboard/native-adapter.js.map +1 -1
- package/dist/domains/dashboard/native-collector.d.ts +4 -4
- package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
- package/dist/domains/dashboard/native-collector.js +230 -412
- package/dist/domains/dashboard/native-collector.js.map +1 -1
- package/dist/domains/dashboard/native-legacy-adapter.d.ts +30 -0
- package/dist/domains/dashboard/native-legacy-adapter.d.ts.map +1 -0
- package/dist/domains/dashboard/native-legacy-adapter.js +115 -0
- package/dist/domains/dashboard/native-legacy-adapter.js.map +1 -0
- package/dist/domains/dashboard/web/assets/{arc-ClrSujVb.js → arc-CkuYweSh.js} +1 -1
- package/dist/domains/dashboard/web/assets/{architectureDiagram-3BPJPVTR-B4A_t84A.js → architectureDiagram-3BPJPVTR--tTGrKam.js} +1 -1
- package/dist/domains/dashboard/web/assets/{blockDiagram-GPEHLZMM-D72u2953.js → blockDiagram-GPEHLZMM-DLKYOixs.js} +1 -1
- package/dist/domains/dashboard/web/assets/{c4Diagram-AAUBKEIU-Ca5zba3N.js → c4Diagram-AAUBKEIU-BL17BIb8.js} +1 -1
- package/dist/domains/dashboard/web/assets/channel-Cg__FSMr.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-2J33WTMH-CCVPBm0J.js → chunk-2J33WTMH-B_DDS2IK.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-4BX2VUAB-JYluRsP-.js → chunk-4BX2VUAB-vQyyh3eG.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-55IACEB6-DfYm7pN7.js → chunk-55IACEB6-Cug8J1Qa.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-727SXJPM-CwghIMO9.js → chunk-727SXJPM-pMreYMW7.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-AQP2D5EJ-BA_zgMXZ.js → chunk-AQP2D5EJ-BUkV_rb7.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-FMBD7UC4-BAJLB5V6.js → chunk-FMBD7UC4-CQXqBSqQ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-ND2GUHAM-Bj6HWRwi.js → chunk-ND2GUHAM-XWLMOyd4.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-QZHKN3VN-B1kXfg5N.js → chunk-QZHKN3VN-4drjXzHQ.js} +1 -1
- package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-CsC-pvu9.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-CsC-pvu9.js +1 -0
- package/dist/domains/dashboard/web/assets/{cose-bilkent-S5V4N54A-BBrkuiAU.js → cose-bilkent-S5V4N54A-IQKP-hgj.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-DlFhgQHt.js → cynefin-VYW2F7L2-CvvRO4J2.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dagre-BM42HDAG-B0Bk5oiP.js → dagre-BM42HDAG-DeOQo7bP.js} +1 -1
- package/dist/domains/dashboard/web/assets/demo-CeIDHUFJ.js +24 -0
- package/dist/domains/dashboard/web/assets/{diagram-2AECGRRQ-tvTUiBA2.js → diagram-2AECGRRQ-IQd_jQwB.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-5GNKFQAL-BZfcK29q.js → diagram-5GNKFQAL-Dllkdt0m.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-KO2AKTUF-BQahyP-C.js → diagram-KO2AKTUF-CN_LYqvT.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-LMA3HP47-D5bJnW2C.js → diagram-LMA3HP47-DK36WkNN.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-OG6HWLK6-DTwWdzWJ.js → diagram-OG6HWLK6-iqUnMYEh.js} +1 -1
- package/dist/domains/dashboard/web/assets/{erDiagram-TEJ5UH35-BbvrdCp9.js → erDiagram-TEJ5UH35-Bc64lzy8.js} +1 -1
- package/dist/domains/dashboard/web/assets/{flowDiagram-I6XJVG4X-DgbR7Tcc.js → flowDiagram-I6XJVG4X-UfOqef9j.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ganttDiagram-6RSMTGT7-wWMOA7F4.js → ganttDiagram-6RSMTGT7-D-u6Aauc.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraphDiagram-PVQCEYII-DCxvMAUJ.js → gitGraphDiagram-PVQCEYII-CaWEk3PM.js} +1 -1
- package/dist/domains/dashboard/web/assets/index-BFwKBVTJ.css +1 -0
- package/dist/domains/dashboard/web/assets/{index-Blit0P5Z.js → index-BNyOfAhu.js} +1 -1
- package/dist/domains/dashboard/web/assets/index-COZ_03uK.js +257 -0
- package/dist/domains/dashboard/web/assets/{infoDiagram-5YYISTIA-9qXEkzDe.js → infoDiagram-5YYISTIA-BK07mNG0.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ishikawaDiagram-YF4QCWOH-Dkf5othW.js → ishikawaDiagram-YF4QCWOH-mWnmaWfZ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{journeyDiagram-JHISSGLW-C2_IkO4s.js → journeyDiagram-JHISSGLW-BPy-P7xx.js} +1 -1
- package/dist/domains/dashboard/web/assets/{kanban-definition-UN3LZRKU-BxWgu4DL.js → kanban-definition-UN3LZRKU-3Jq9c_lo.js} +1 -1
- package/dist/domains/dashboard/web/assets/{linear-Dkr6p-Ro.js → linear-kQyEW-4G.js} +1 -1
- package/dist/domains/dashboard/web/assets/{mermaid.core-DZUcsoG4.js → mermaid.core-COBBjtVH.js} +4 -4
- package/dist/domains/dashboard/web/assets/{mindmap-definition-RKZ34NQL-C9xyxGfa.js → mindmap-definition-RKZ34NQL-CyyurUpv.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pieDiagram-4H26LBE5-Dn67tdOF.js → pieDiagram-4H26LBE5-CJro_XKk.js} +1 -1
- package/dist/domains/dashboard/web/assets/{quadrantDiagram-W4KKPZXB-Cy6iOcxc.js → quadrantDiagram-W4KKPZXB-CpayUMjH.js} +1 -1
- package/dist/domains/dashboard/web/assets/{requirementDiagram-4Y6WPE33-B_gZONhx.js → requirementDiagram-4Y6WPE33-Bi8YpfnA.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sankeyDiagram-5OEKKPKP-C3u-4dOk.js → sankeyDiagram-5OEKKPKP-Wx60WwHe.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sequenceDiagram-3UESZ5HK-Xd3ByTVF.js → sequenceDiagram-3UESZ5HK-BiMsRFbc.js} +1 -1
- package/dist/domains/dashboard/web/assets/{stateDiagram-AJRCARHV-CJGHL7Up.js → stateDiagram-AJRCARHV-BrURMY0R.js} +1 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-BpEE-yEg.js +1 -0
- package/dist/domains/dashboard/web/assets/{timeline-definition-PNZ67QCA-DvONX2YQ.js → timeline-definition-PNZ67QCA-aHrrtV-b.js} +1 -1
- package/dist/domains/dashboard/web/assets/{vennDiagram-CIIHVFJN-B-L4qWy4.js → vennDiagram-CIIHVFJN-DGB16bvR.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardleyDiagram-YWT4CUSO-cf39WX2o.js → wardleyDiagram-YWT4CUSO-RVQbcySh.js} +1 -1
- package/dist/domains/dashboard/web/assets/{xychartDiagram-2RQKCTM6-Dk1vcm3u.js → xychartDiagram-2RQKCTM6-DMzzwDVX.js} +1 -1
- package/dist/domains/dashboard/web/index.html +2 -2
- package/dist/domains/factory/package.d.ts.map +1 -1
- package/dist/domains/factory/package.js +7 -22
- package/dist/domains/factory/package.js.map +1 -1
- package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
- package/dist/domains/skill/platform-inspect.js +11 -3
- package/dist/domains/skill/platform-inspect.js.map +1 -1
- package/dist/domains/skill/platform-install.d.ts +7 -1
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +114 -33
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/domains/skill/uninstall.d.ts.map +1 -1
- package/dist/domains/skill/uninstall.js +69 -15
- package/dist/domains/skill/uninstall.js.map +1 -1
- package/dist/domains/workflow-contract/index.d.ts +1 -0
- package/dist/domains/workflow-contract/index.d.ts.map +1 -1
- package/dist/domains/workflow-contract/index.js +1 -0
- package/dist/domains/workflow-contract/index.js.map +1 -1
- package/dist/domains/workflow-contract/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 +77 -17
- package/dist/domains/workflow-contract/project-config.js.map +1 -1
- package/dist/domains/workflow-contract/project-gitignore.d.ts +9 -0
- package/dist/domains/workflow-contract/project-gitignore.d.ts.map +1 -0
- package/dist/domains/workflow-contract/project-gitignore.js +108 -0
- package/dist/domains/workflow-contract/project-gitignore.js.map +1 -0
- package/dist/platform/install/platforms.d.ts +3 -1
- package/dist/platform/install/platforms.d.ts.map +1 -1
- package/dist/platform/install/platforms.js +9 -0
- package/dist/platform/install/platforms.js.map +1 -1
- package/dist/platform/paths/git-worktree.d.ts +2 -1
- package/dist/platform/paths/git-worktree.d.ts.map +1 -1
- package/dist/platform/paths/git-worktree.js +14 -1
- package/dist/platform/paths/git-worktree.js.map +1 -1
- package/dist/platform/process/external-command.d.ts +13 -0
- package/dist/platform/process/external-command.d.ts.map +1 -0
- package/dist/platform/process/external-command.js +45 -0
- package/dist/platform/process/external-command.js.map +1 -0
- package/dist/platform/process/git.d.ts +12 -0
- package/dist/platform/process/git.d.ts.map +1 -0
- package/dist/platform/process/git.js +86 -0
- package/dist/platform/process/git.js.map +1 -0
- package/dist/platform/process/spawn-command.d.ts +8 -0
- package/dist/platform/process/spawn-command.d.ts.map +1 -0
- package/dist/platform/process/spawn-command.js +113 -0
- package/dist/platform/process/spawn-command.js.map +1 -0
- package/eval/local/tasks/comet-native-clarification/validation/test_native_clarification.py +9 -21
- package/eval/local/tasks/comet-native-clarification-depth/validation/test_native_clarification_depth.py +4 -7
- package/eval/local/tasks/comet-native-clarification-modes/validation/test_native_clarification_modes.py +4 -10
- package/eval/local/tasks/comet-native-interrupted-transition/instruction.md +1 -1
- package/eval/local/tasks/comet-native-interrupted-transition/validation/test_native_interrupted_transition.py +15 -16
- package/eval/local/tasks/comet-native-repository-fact/instruction.md +2 -2
- package/eval/local/tasks/comet-native-repository-fact/validation/test_native_repository_fact.py +8 -2
- package/eval/local/tasks/comet-native-wave-b-decision-resume/instruction.md +8 -4
- package/eval/local/tasks/comet-native-wave-b-decision-resume/task.toml +6 -6
- package/eval/local/tasks/comet-native-wave-b-decision-resume/validation/test_native_wave_b_decision_resume.py +126 -135
- package/eval/local/tasks/comet-native-wave-c-verification-integrity/instruction.md +6 -6
- package/eval/local/tasks/comet-native-wave-c-verification-integrity/task.toml +8 -8
- package/eval/local/tasks/comet-native-wave-c-verification-integrity/validation/test_native_wave_c_verification_integrity.py +97 -317
- package/eval/local/tasks/comet-native-wave-d-stagnation-stop/instruction.md +7 -7
- package/eval/local/tasks/comet-native-wave-d-stagnation-stop/task.toml +4 -4
- package/eval/local/tasks/comet-native-wave-d-stagnation-stop/validation/test_native_wave_d_stagnation_stop.py +130 -199
- package/eval/local/tasks/comet-native-wave-e-parallel-safety/instruction.md +5 -5
- package/eval/local/tasks/comet-native-wave-e-parallel-safety/task.toml +8 -8
- package/eval/local/tasks/comet-native-wave-e-parallel-safety/validation/test_native_wave_e_parallel_safety.py +135 -239
- package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/instruction.md +3 -3
- package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/task.toml +6 -6
- package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/validation/test_native_wave_f_dashboard_readonly.py +81 -439
- package/eval/local/tasks/comet-native-workflow/instruction.md +5 -4
- package/eval/local/tasks/comet-native-workflow/validation/test_native_workflow.py +145 -502
- package/eval/local/tasks/index.yaml +5 -5
- package/eval/local/tests/scaffold/test_native_aligned_eval.py +146 -35
- package/eval/local/tests/scaffold/test_native_wave_evaluations.py +75 -2054
- package/eval/local/tests/scaffold/test_tasks.py +38 -52
- package/eval/local/tests/tasks/test_tasks.py +3 -3
- package/eval/local/treatments/comet/comet_native_phase1.yaml +7 -4
- package/eval/scaffold/python/native_eval.py +10 -5
- package/eval/scaffold/python/validation/native_v4.py +249 -0
- package/eval/scaffold/python/validation/native_wave.py +4 -5
- package/eval/scaffold/python/validation/native_workflow.py +193 -97
- package/eval/scaffold/python/validation/rubric.py +114 -1
- package/package.json +8 -5
- package/assets/skills/comet-native/scripts/comet-native-check.mjs +0 -179
- package/assets/skills/comet-native/scripts/comet-native-checkpoint.mjs +0 -179
- package/assets/skills/comet-native/scripts/comet-native-evidence.mjs +0 -151
- package/assets/skills/comet-native/scripts/comet-native-receipt.mjs +0 -187
- package/dist/domains/comet-native/native-check-entry.d.ts +0 -2
- package/dist/domains/comet-native/native-check-entry.d.ts.map +0 -1
- package/dist/domains/comet-native/native-check-entry.js +0 -4
- package/dist/domains/comet-native/native-check-entry.js.map +0 -1
- package/dist/domains/comet-native/native-checkpoint-entry.d.ts +0 -2
- package/dist/domains/comet-native/native-checkpoint-entry.d.ts.map +0 -1
- package/dist/domains/comet-native/native-checkpoint-entry.js +0 -4
- package/dist/domains/comet-native/native-checkpoint-entry.js.map +0 -1
- package/dist/domains/comet-native/native-evidence-entry.d.ts +0 -2
- package/dist/domains/comet-native/native-evidence-entry.d.ts.map +0 -1
- package/dist/domains/comet-native/native-evidence-entry.js +0 -4
- package/dist/domains/comet-native/native-evidence-entry.js.map +0 -1
- package/dist/domains/comet-native/native-receipt-entry.d.ts +0 -2
- package/dist/domains/comet-native/native-receipt-entry.d.ts.map +0 -1
- package/dist/domains/comet-native/native-receipt-entry.js +0 -4
- package/dist/domains/comet-native/native-receipt-entry.js.map +0 -1
- package/dist/domains/dashboard/web/assets/channel-B_u-_i2t.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-BpA7BPgX.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-BpA7BPgX.js +0 -1
- package/dist/domains/dashboard/web/assets/demo-DZYPLZpF.js +0 -25
- package/dist/domains/dashboard/web/assets/index-Bk1o-4VO.css +0 -1
- package/dist/domains/dashboard/web/assets/index-g8vyW0R_.js +0 -257
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-rKvBgr6I.js +0 -1
- /package/assets/skills/{comet → comet-classic}/reference/classic-layout.md +0 -0
- /package/assets/skills-zh/{comet → comet-classic}/reference/classic-layout.md +0 -0
|
@@ -1,200 +1,207 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`)}};
|
|
6
|
-
`)?
|
|
4
|
+
var yf=Object.create;var ws=Object.defineProperty;var Nf=Object.getOwnPropertyDescriptor;var bf=Object.getOwnPropertyNames;var kf=Object.getPrototypeOf,Sf=Object.prototype.hasOwnProperty;var Wi=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,i)=>(typeof require<"u"?require:e)[i]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var w=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(i){throw e=0,i}};var Ef=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of bf(e))!Sf.call(t,n)&&n!==i&&ws(t,n,{get:()=>e[n],enumerable:!(r=Nf(e,n))||r.enumerable});return t};var zi=(t,e,i)=>(i=t!=null?yf(kf(t)):{},Ef(e||!t||!t.__esModule?ws(i,"default",{value:t,enumerable:!0}):i,t));var P=w(H=>{"use strict";var Fn=Symbol.for("yaml.alias"),ys=Symbol.for("yaml.document"),Ji=Symbol.for("yaml.map"),Ns=Symbol.for("yaml.pair"),Vn=Symbol.for("yaml.scalar"),Gi=Symbol.for("yaml.seq"),Ce=Symbol.for("yaml.node.type"),Pf=t=>!!t&&typeof t=="object"&&t[Ce]===Fn,xf=t=>!!t&&typeof t=="object"&&t[Ce]===ys,Cf=t=>!!t&&typeof t=="object"&&t[Ce]===Ji,Rf=t=>!!t&&typeof t=="object"&&t[Ce]===Ns,bs=t=>!!t&&typeof t=="object"&&t[Ce]===Vn,Af=t=>!!t&&typeof t=="object"&&t[Ce]===Gi;function ks(t){if(t&&typeof t=="object")switch(t[Ce]){case Ji:case Gi:return!0}return!1}function _f(t){if(t&&typeof t=="object")switch(t[Ce]){case Fn:case Ji:case Vn:case Gi:return!0}return!1}var Tf=t=>(bs(t)||ks(t))&&!!t.anchor;H.ALIAS=Fn;H.DOC=ys;H.MAP=Ji;H.NODE_TYPE=Ce;H.PAIR=Ns;H.SCALAR=Vn;H.SEQ=Gi;H.hasAnchor=Tf;H.isAlias=Pf;H.isCollection=ks;H.isDocument=xf;H.isMap=Cf;H.isNode=_f;H.isPair=Rf;H.isScalar=bs;H.isSeq=Af});var Vt=w(qn=>{"use strict";var O=P(),q=Symbol("break visit"),Ss=Symbol("skip children"),be=Symbol("remove node");function Ui(t,e){let i=Es(e);O.isDocument(t)?wt(null,t.contents,i,Object.freeze([t]))===be&&(t.contents=null):wt(null,t,i,Object.freeze([]))}Ui.BREAK=q;Ui.SKIP=Ss;Ui.REMOVE=be;function wt(t,e,i,r){let n=Ps(t,e,i,r);if(O.isNode(n)||O.isPair(n))return xs(t,r,n),wt(t,n,i,r);if(typeof n!="symbol"){if(O.isCollection(e)){r=Object.freeze(r.concat(e));for(let a=0;a<e.items.length;++a){let o=wt(a,e.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===q)return q;o===be&&(e.items.splice(a,1),a-=1)}}}else if(O.isPair(e)){r=Object.freeze(r.concat(e));let a=wt("key",e.key,i,r);if(a===q)return q;a===be&&(e.key=null);let o=wt("value",e.value,i,r);if(o===q)return q;o===be&&(e.value=null)}}return n}async function Ki(t,e){let i=Es(e);O.isDocument(t)?await yt(null,t.contents,i,Object.freeze([t]))===be&&(t.contents=null):await yt(null,t,i,Object.freeze([]))}Ki.BREAK=q;Ki.SKIP=Ss;Ki.REMOVE=be;async function yt(t,e,i,r){let n=await Ps(t,e,i,r);if(O.isNode(n)||O.isPair(n))return xs(t,r,n),yt(t,n,i,r);if(typeof n!="symbol"){if(O.isCollection(e)){r=Object.freeze(r.concat(e));for(let a=0;a<e.items.length;++a){let o=await yt(a,e.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===q)return q;o===be&&(e.items.splice(a,1),a-=1)}}}else if(O.isPair(e)){r=Object.freeze(r.concat(e));let a=await yt("key",e.key,i,r);if(a===q)return q;a===be&&(e.key=null);let o=await yt("value",e.value,i,r);if(o===q)return q;o===be&&(e.value=null)}}return n}function Es(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function Ps(t,e,i,r){if(typeof i=="function")return i(t,e,r);if(O.isMap(e))return i.Map?.(t,e,r);if(O.isSeq(e))return i.Seq?.(t,e,r);if(O.isPair(e))return i.Pair?.(t,e,r);if(O.isScalar(e))return i.Scalar?.(t,e,r);if(O.isAlias(e))return i.Alias?.(t,e,r)}function xs(t,e,i){let r=e[e.length-1];if(O.isCollection(r))r.items[t]=i;else if(O.isPair(r))t==="key"?r.key=i:r.value=i;else if(O.isDocument(r))r.contents=i;else{let n=O.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}qn.visit=Ui;qn.visitAsync=Ki});var Wn=w(Rs=>{"use strict";var Cs=P(),If=Vt(),jf={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},$f=t=>t.replace(/[!,[\]{}]/g,e=>jf[e]),qt=class t{constructor(e,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,i)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,i){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(e,i){if(e==="!")return"!";if(e[0]!=="!")return i(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=e.match(/^(.*!)([^!]*)$/s);n||i(`The ${e} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?e:(i(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[i,r]of Object.entries(this.tags))if(e.startsWith(r))return i+$f(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(e&&r.length>0&&Cs.isNode(e.contents)){let a={};If.visit(e.contents,(o,s)=>{Cs.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!e||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
|
|
5
|
+
`)}};qt.defaultYaml={explicit:!1,version:"1.2"};qt.defaultTags={"!!":"tag:yaml.org,2002:"};Rs.Directives=qt});var Yi=w(Wt=>{"use strict";var As=P(),Of=Vt();function Hf(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(i)}return!0}function _s(t){let e=new Set;return Of.visit(t,{Value(i,r){r.anchor&&e.add(r.anchor)}}),e}function Ts(t,e){for(let i=1;;++i){let r=`${t}${i}`;if(!e.has(r))return r}}function Df(t,e){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=_s(t));let o=Ts(e,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(As.isScalar(o.node)||As.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:r}}Wt.anchorIsValid=Hf;Wt.anchorNames=_s;Wt.createNodeAnchors=Df;Wt.findNewAnchor=Ts});var zn=w(Is=>{"use strict";function zt(t,e,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=zt(t,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=zt(t,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=zt(t,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=zt(t,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return t.call(e,i,r)}Is.applyReviver=zt});var De=w($s=>{"use strict";var Bf=P();function js(t,e,i){if(Array.isArray(t))return t.map((r,n)=>js(r,String(n),i));if(t&&typeof t.toJSON=="function"){if(!i||!Bf.hasAnchor(t))return t.toJSON(e,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(t,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=t.toJSON(e,i);return i.onCreate&&i.onCreate(n),n}return typeof t=="bigint"&&!i?.keep?Number(t):t}$s.toJS=js});var Xi=w(Hs=>{"use strict";var Lf=zn(),Os=P(),Mf=De(),Jn=class{constructor(e){Object.defineProperty(this,Os.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!Os.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=Mf.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Lf.applyReviver(a,{"":s},"",s):s}};Hs.NodeBase=Jn});var Jt=w(Ds=>{"use strict";var Ff=Yi(),Vf=Vt(),Nt=P(),qf=Xi(),Wf=De(),Gn=class extends qf.NodeBase{constructor(e){super(Nt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],Vf.visit(e,{Node:(a,o)=>{(Nt.isAlias(o)||Nt.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(e,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(Wf.toJS(o,null,i),s=r.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Qi(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(e,i,r){let n=`*${this.source}`;if(e){if(Ff.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(e.implicitKey)return`${n} `}return n}};function Qi(t,e,i){if(Nt.isAlias(e)){let r=e.resolve(t),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Nt.isCollection(e)){let r=0;for(let n of e.items){let a=Qi(t,n,i);a>r&&(r=a)}return r}else if(Nt.isPair(e)){let r=Qi(t,e.key,i),n=Qi(t,e.value,i);return Math.max(r,n)}return 1}Ds.Alias=Gn});var j=w(Un=>{"use strict";var zf=P(),Jf=Xi(),Gf=De(),Uf=t=>!t||typeof t!="function"&&typeof t!="object",Be=class extends Jf.NodeBase{constructor(e){super(zf.SCALAR),this.value=e}toJSON(e,i){return i?.keep?this.value:Gf.toJS(this.value,e,i)}toString(){return String(this.value)}};Be.BLOCK_FOLDED="BLOCK_FOLDED";Be.BLOCK_LITERAL="BLOCK_LITERAL";Be.PLAIN="PLAIN";Be.QUOTE_DOUBLE="QUOTE_DOUBLE";Be.QUOTE_SINGLE="QUOTE_SINGLE";Un.Scalar=Be;Un.isScalarValue=Uf});var Gt=w(Ls=>{"use strict";var Kf=Jt(),rt=P(),Bs=j(),Yf="tag:yaml.org,2002:";function Xf(t,e,i){if(e){let r=i.filter(a=>a.tag===e),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return i.find(r=>r.identify?.(t)&&!r.format)}function Qf(t,e,i){if(rt.isDocument(t)&&(t=t.contents),rt.isNode(t))return t;if(rt.isPair(t)){let u=i.schema[rt.MAP].createNode?.(i.schema,null,i);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=n(t)),new Kf.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=Yf+e.slice(2));let l=Xf(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new Bs.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[rt.MAP]:Symbol.iterator in Object(t)?o[rt.SEQ]:o[rt.MAP]}a&&(a(l),delete i.onTagObj);let d=l?.createNode?l.createNode(i.schema,t,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,t,i):new Bs.Scalar(t);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}Ls.createNode=Qf});var er=w(Zi=>{"use strict";var Zf=Gt(),ke=P(),eh=Xi();function Kn(t,e,i){let r=i;for(let n=e.length-1;n>=0;--n){let a=e[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return Zf.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Ms=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Yn=class extends eh.NodeBase{constructor(e,i){super(e),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(e){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(i.schema=e),i.items=i.items.map(r=>ke.isNode(r)||ke.isPair(r)?r.clone(e):r),this.range&&(i.range=this.range.slice()),i}addIn(e,i){if(Ms(e))this.add(i);else{let[r,...n]=e,a=this.get(r,!0);if(ke.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Kn(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(e){let[i,...r]=e;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(ke.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(e,i){let[r,...n]=e,a=this.get(r,!0);return n.length===0?!i&&ke.isScalar(a)?a.value:a:ke.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(e){return this.items.every(i=>{if(!ke.isPair(i))return!1;let r=i.value;return r==null||e&&ke.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[i,...r]=e;if(r.length===0)return this.has(i);let n=this.get(i,!0);return ke.isCollection(n)?n.hasIn(r):!1}setIn(e,i){let[r,...n]=e;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(ke.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Kn(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};Zi.Collection=Yn;Zi.collectionFromPath=Kn;Zi.isEmptyPath=Ms});var Ut=w(tr=>{"use strict";var th=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Xn(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var ih=(t,e,i)=>t.endsWith(`
|
|
6
|
+
`)?Xn(i,e):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)i===
|
|
10
|
-
`&&p!==" "){let
|
|
11
|
-
`&&
|
|
12
|
-
${
|
|
13
|
-
${
|
|
14
|
-
`);
|
|
15
|
-
`){if(a-o>
|
|
8
|
+
`+Xn(i,e):(t.endsWith(" ")?"":" ")+i;tr.indentComment=Xn;tr.lineComment=ih;tr.stringifyComment=th});var Vs=w(Kt=>{"use strict";var rh="flow",Qn="block",ir="quoted";function nh(t,e,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return t;n<a&&(a=0);let c=Math.max(1+a,1+n-e.length);if(t.length<=c)return t;let l=[],d={},u=n-e.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):u=n-r);let f,p,g=!1,h=-1,m=-1,y=-1;i===Qn&&(h=Fs(t,h,e.length),h!==-1&&(u=h+c));for(let k;k=t[h+=1];){if(i===ir&&k==="\\"){switch(m=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}y=h}if(k===`
|
|
9
|
+
`)i===Qn&&(h=Fs(t,h,e.length)),u=h+e.length+c,f=void 0;else{if(k===" "&&p&&p!==" "&&p!==`
|
|
10
|
+
`&&p!==" "){let S=t[h+1];S&&S!==" "&&S!==`
|
|
11
|
+
`&&S!==" "&&(f=h)}if(h>=u)if(f)l.push(f),u=f+c,f=void 0;else if(i===ir){for(;p===" "||p===" ";)p=k,k=t[h+=1],g=!0;let S=h>y+1?h-2:m-1;if(d[S])return t;l.push(S),d[S]=!0,u=S+c,f=void 0}else g=!0}p=k}if(g&&s&&s(),l.length===0)return t;o&&o();let N=t.slice(0,l[0]);for(let k=0;k<l.length;++k){let S=l[k],E=l[k+1]||t.length;S===0?N=`
|
|
12
|
+
${e}${t.slice(0,E)}`:(i===ir&&d[S]&&(N+=`${t[S]}\\`),N+=`
|
|
13
|
+
${e}${t.slice(S+1,E)}`)}return N}function Fs(t,e,i){let r=e,n=e+1,a=t[n];for(;a===" "||a===" ";)if(e<n+i)a=t[++e];else{do a=t[++e];while(a&&a!==`
|
|
14
|
+
`);r=e,n=e+1,a=t[n]}return r}Kt.FOLD_BLOCK=Qn;Kt.FOLD_FLOW=rh;Kt.FOLD_QUOTED=ir;Kt.foldFlowLines=nh});var Xt=w(qs=>{"use strict";var ce=j(),Le=Vs(),nr=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),ar=t=>/^(%|---|\.\.\.)/m.test(t);function ah(t,e,i){if(!e||e<0)return!1;let r=e-i,n=t.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(t[a]===`
|
|
15
|
+
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Yt(t,e){let i=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=e,n=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(ar(t)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let d=i.substr(c+2,4);switch(d){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(
|
|
20
|
-
${i}`)+"'";return
|
|
18
|
+
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:Le.foldFlowLines(o,a,Le.FOLD_QUOTED,nr(e,!1))}function Zn(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(t))return Yt(t,e);let i=e.indent||(ar(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return e.implicitKey?r:Le.foldFlowLines(r,i,Le.FOLD_FLOW,nr(e,!1))}function bt(t,e){let{singleQuote:i}=e.options,r;if(i===!1)r=Yt;else{let n=t.includes('"'),a=t.includes("'");n&&!a?r=Zn:a&&!n?r=Yt:r=i?Zn:Yt}return r(t,e)}var ea;try{ea=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{ea=/\n+(?!\n|$)/g}function rr({comment:t,type:e,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return bt(i,r);let l=r.indent||(r.forceBlockIndent||ar(i)?" ":""),d=o==="literal"?!0:o==="folded"||e===ce.Scalar.BLOCK_FOLDED?!1:e===ce.Scalar.BLOCK_LITERAL?!0:!ah(i,c,l.length);if(!i)return d?`|
|
|
24
24
|
`:`>
|
|
25
|
-
`;let
|
|
26
|
-
`&&
|
|
27
|
-
`);
|
|
28
|
-
`&&(p=p.slice(0,-1)),p=p.replace(
|
|
29
|
-
`)
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),
|
|
31
|
-
${l}${
|
|
32
|
-
${l}${N}${i}${p}`}function
|
|
33
|
-
`)||
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(
|
|
37
|
-
${
|
|
38
|
-
${s}:`):(
|
|
39
|
-
`:"",N){let
|
|
40
|
-
${
|
|
41
|
-
`&&k&&(
|
|
25
|
+
`;let u,f;for(f=i.length;f>0;--f){let E=i[f-1];if(E!==`
|
|
26
|
+
`&&E!==" "&&E!==" ")break}let p=i.substring(f),g=p.indexOf(`
|
|
27
|
+
`);g===-1?u="-":i===p||g!==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(ea,`$&${l}`));let h=!1,m,y=-1;for(m=0;m<i.length;++m){let E=i[m];if(E===" ")h=!0;else if(E===`
|
|
29
|
+
`)y=m;else break}let N=i.substring(0,y<m?y+1:m);N&&(i=i.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let S=(h?l?"2":"1":"")+u;if(t&&(S+=" "+s(t.replace(/ ?[\r\n]+/g," ")),n&&n()),!d){let E=i.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),v=!1,x=nr(r,!0);o!=="folded"&&e!==ce.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{v=!0});let b=Le.foldFlowLines(`${N}${E}${p}`,l,Le.FOLD_BLOCK,x);if(!v)return`>${S}
|
|
31
|
+
${l}${b}`}return i=i.replace(/\n+/g,`$&${l}`),`|${S}
|
|
32
|
+
${l}${N}${i}${p}`}function oh(t,e,i,r){let{type:n,value:a}=t,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:d}=e;if(s&&a.includes(`
|
|
33
|
+
`)||d&&/[[\]{},]/.test(a))return bt(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||d||!a.includes(`
|
|
34
|
+
`)?bt(a,e):rr(t,e,i,r);if(!s&&!d&&n!==ce.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return rr(t,e,i,r);if(ar(a)){if(c==="")return e.forceBlockIndent=!0,rr(t,e,i,r);if(s&&c===l)return bt(a,e)}let u=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:p,tags:g}=e.doc.schema;if(g.some(f)||p?.some(f))return bt(a,e)}return s?u:Le.foldFlowLines(u,c,Le.FOLD_FLOW,nr(e,!1))}function sh(t,e,i,r){let{implicitKey:n,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==ce.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=ce.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case ce.Scalar.BLOCK_FOLDED:case ce.Scalar.BLOCK_LITERAL:return n||a?bt(o.value,e):rr(o,e,i,r);case ce.Scalar.QUOTE_DOUBLE:return Yt(o.value,e);case ce.Scalar.QUOTE_SINGLE:return Zn(o.value,e);case ce.Scalar.PLAIN:return oh(o,e,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=n&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}qs.stringifyString=sh});var Qt=w(ta=>{"use strict";var ch=Yi(),Me=P(),lh=Ut(),uh=Xt();function dh(t,e){let i=Object.assign({blockQuote:!0,commentString:lh.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function fh(t,e){if(e.tag){let n=t.filter(a=>a.tag===e.tag);if(n.length>0)return n.find(a=>a.format===e.format)??n[0]}let i,r;if(Me.isScalar(e)){r=e.value;let n=t.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===e.format)??n.find(a=>!a.format)}else r=e,i=t.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function hh(t,e,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Me.isScalar(t)||Me.isCollection(t))&&t.anchor;a&&ch.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function ph(t,e,i,r){if(Me.isPair(t))return t.toString(e,i,r);if(Me.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let n,a=Me.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>n=c});n??(n=fh(e.doc.schema.tags,a));let o=hh(a,n,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,e,i,r):Me.isScalar(a)?uh.stringifyString(a,e,i,r):a.toString(e,i,r);return o?Me.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${e.indent}${s}`:s}ta.createStringifyContext=dh;ta.stringify=ph});var Gs=w(Js=>{"use strict";var Re=P(),Ws=j(),zs=Qt(),Zt=Ut();function mh({key:t,value:e},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=i,f=Re.isNode(t)&&t.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Re.isCollection(t)||!Re.isNode(t)&&typeof t=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!u&&(!t||f&&e==null&&!i.inFlow||Re.isCollection(t)||(Re.isScalar(t)?t.type===Ws.Scalar.BLOCK_FOLDED||t.type===Ws.Scalar.BLOCK_LITERAL:typeof t=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(u||!a),indent:s+c});let g=!1,h=!1,m=zs.stringify(t,i,()=>g=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||e==null)return g&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!u||e==null&&p)return m=`? ${m}`,f&&!g?m+=Zt.lineComment(m,i.indent,l(f)):h&&n&&n(),m;g&&(f=null),p?(f&&(m+=Zt.lineComment(m,i.indent,l(f))),m=`? ${m}
|
|
38
|
+
${s}:`):(m=`${m}:`,f&&(m+=Zt.lineComment(m,i.indent,l(f))));let y,N,k;Re.isNode(e)?(y=!!e.spaceBefore,N=e.commentBefore,k=e.comment):(y=!1,N=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),i.implicitKey=!1,!p&&!f&&Re.isScalar(e)&&(i.indentAtStart=m.length+1),h=!1,!d&&c.length>=2&&!i.inFlow&&!p&&Re.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(i.indent=i.indent.substring(2));let S=!1,E=zs.stringify(e,i,()=>S=!0,()=>h=!0),v=" ";if(f||y||N){if(v=y?`
|
|
39
|
+
`:"",N){let x=l(N);v+=`
|
|
40
|
+
${Zt.indentComment(x,i.indent)}`}E===""&&!i.inFlow?v===`
|
|
41
|
+
`&&k&&(v=`
|
|
42
42
|
|
|
43
|
-
`):
|
|
44
|
-
${i.indent}`}else if(!p&&
|
|
45
|
-
`),
|
|
46
|
-
${i.indent}`)}}else(
|
|
47
|
-
`)&&(
|
|
43
|
+
`):v+=`
|
|
44
|
+
${i.indent}`}else if(!p&&Re.isCollection(e)){let x=E[0],b=E.indexOf(`
|
|
45
|
+
`),_=b!==-1,U=i.inFlow??e.flow??e.items.length===0;if(_||!U){let gt=!1;if(_&&(x==="&"||x==="!")){let $=E.indexOf(" ");x==="&"&&$!==-1&&$<b&&E[$+1]==="!"&&($=E.indexOf(" ",$+1)),($===-1||b<$)&&(gt=!0)}gt||(v=`
|
|
46
|
+
${i.indent}`)}}else(E===""||E[0]===`
|
|
47
|
+
`)&&(v="");return m+=v+E,i.inFlow?S&&r&&r():k&&!S?m+=Zt.lineComment(m,i.indent,l(k)):h&&n&&n(),m}Js.stringifyPair=mh});var ra=w(ia=>{"use strict";var Us=Wi("process");function vh(t,...e){t==="debug"&&console.log(...e)}function gh(t,e){(t==="debug"||t==="warn")&&(typeof Us.emitWarning=="function"?Us.emitWarning(e):console.warn(e))}ia.debug=vh;ia.warn=gh});var ur=w(lr=>{"use strict";var cr=P(),Ks=j(),or="<<",sr={identify:t=>t===or||typeof t=="symbol"&&t.description===or,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ks.Scalar(Symbol(or)),{addToJSMap:Ys}),stringify:()=>or},wh=(t,e)=>(sr.identify(e)||cr.isScalar(e)&&(!e.type||e.type===Ks.Scalar.PLAIN)&&sr.identify(e.value))&&t?.doc.schema.tags.some(i=>i.tag===sr.tag&&i.default);function Ys(t,e,i){let r=Xs(t,i);if(cr.isSeq(r))for(let n of r.items)na(t,e,n);else if(Array.isArray(r))for(let n of r)na(t,e,n);else na(t,e,r)}function na(t,e,i){let r=Xs(t,i);if(!cr.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,t,Map);for(let[a,o]of n)e instanceof Map?e.has(a)||e.set(a,o):e instanceof Set?e.add(a):Object.prototype.hasOwnProperty.call(e,a)||Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Xs(t,e){return t&&cr.isAlias(e)?e.resolve(t.doc,t):e}lr.addMergeToJSMap=Ys;lr.isMergeKey=wh;lr.merge=sr});var oa=w(ec=>{"use strict";var yh=ra(),Qs=ur(),Nh=Qt(),Zs=P(),aa=De();function bh(t,e,{key:i,value:r}){if(Zs.isNode(i)&&i.addToJSMap)i.addToJSMap(t,e,r);else if(Qs.isMergeKey(t,i))Qs.addMergeToJSMap(t,e,r);else{let n=aa.toJS(i,"",t);if(e instanceof Map)e.set(n,aa.toJS(r,n,t));else if(e instanceof Set)e.add(n);else{let a=kh(i,n,t),o=aa.toJS(r,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function kh(t,e,i){if(e===null)return"";if(typeof e!="object")return String(e);if(Zs.isNode(t)&&i?.doc){let r=Nh.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=t.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),yh.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(e)}ec.addPairToJSMap=bh});var Fe=w(sa=>{"use strict";var tc=Gt(),Sh=Gs(),Eh=oa(),dr=P();function Ph(t,e,i){let r=tc.createNode(t,void 0,i),n=tc.createNode(e,void 0,i);return new fr(r,n)}var fr=class t{constructor(e,i=null){Object.defineProperty(this,dr.NODE_TYPE,{value:dr.PAIR}),this.key=e,this.value=i}clone(e){let{key:i,value:r}=this;return dr.isNode(i)&&(i=i.clone(e)),dr.isNode(r)&&(r=r.clone(e)),new t(i,r)}toJSON(e,i){let r=i?.mapAsMap?new Map:{};return Eh.addPairToJSMap(i,r,this)}toString(e,i,r){return e?.doc?Sh.stringifyPair(this,e,i,r):JSON.stringify(this)}};sa.Pair=fr;sa.createPair=Ph});var ca=w(rc=>{"use strict";var nt=P(),ic=Qt(),hr=Ut();function xh(t,e,i){return(e.inFlow??t.flow?Rh:Ch)(t,e,i)}function Ch({comment:t,items:e},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,d=Object.assign({},i,{indent:a,type:null}),u=!1,f=[];for(let g=0;g<e.length;++g){let h=e[g],m=null;if(nt.isNode(h))!u&&h.spaceBefore&&f.push(""),pr(i,f,h.commentBefore,u),h.comment&&(m=h.comment);else if(nt.isPair(h)){let N=nt.isNode(h.key)?h.key:null;N&&(!u&&N.spaceBefore&&f.push(""),pr(i,f,N.commentBefore,u))}u=!1;let y=ic.stringify(h,d,()=>m=null,()=>u=!0);m&&(y+=hr.lineComment(y,a,l(m))),u&&m&&(u=!1),f.push(r+y)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let g=1;g<f.length;++g){let h=f[g];p+=h?`
|
|
48
48
|
${c}${h}`:`
|
|
49
|
-
`}}return
|
|
50
|
-
`+
|
|
51
|
-
`)),
|
|
52
|
-
${a}${
|
|
53
|
-
`;return`${
|
|
54
|
-
${
|
|
55
|
-
`:" ")}return
|
|
56
|
-
${
|
|
57
|
-
${a.comment}`:n.comment}n=r}e.items[i]=ea.isPair(n)?n:new Ns.Pair(n)}}else t("Expected a sequence for this tag");return e}function Sd(e,t,i){let{replacer:n}=i,r=new py.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(Ns.createPair(s,c,i))}return r}var my={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:kd,createNode:Sd};ta.createPairs=Sd;ta.pairs=my;ta.resolvePairs=kd});var Ss=R(ks=>{"use strict";var Ed=M(),bs=Nt(),mn=Rt(),vy=Pt(),Cd=ia(),Gt=class e extends vy.YAMLSeq{constructor(){super(),this.add=mn.YAMLMap.prototype.add.bind(this),this.delete=mn.YAMLMap.prototype.delete.bind(this),this.get=mn.YAMLMap.prototype.get.bind(this),this.has=mn.YAMLMap.prototype.has.bind(this),this.set=mn.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(Ed.isPair(r)?(a=bs.toJS(r.key,"",i),o=bs.toJS(r.value,a,i)):a=bs.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=Cd.createPairs(t,i,n),a=new this;return a.items=r.items,a}};Gt.tag="tag:yaml.org,2002:omap";var gy={collection:"seq",identify:e=>e instanceof Map,nodeClass:Gt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Cd.resolvePairs(e,t),n=[];for(let{key:r}of i.items)Ed.isScalar(r)&&(n.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Gt,i)},createNode:(e,t,i)=>Gt.from(e,t,i)};ks.YAMLOMap=Gt;ks.omap=gy});var Td=R(Es=>{"use strict";var Rd=te();function Pd({value:e,source:t},i){return t&&(e?Ad:xd).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Ad={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 Rd.Scalar(!0),stringify:Pd},xd={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 Rd.Scalar(!1),stringify:Pd};Es.falseTag=xd;Es.trueTag=Ad});var Id=R(na=>{"use strict";var wy=te(),Cs=bi(),yy={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:Cs.stringifyNumber},Ny={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():Cs.stringifyNumber(e)}},by={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 wy.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:Cs.stringifyNumber};na.float=by;na.floatExp=Ny;na.floatNaN=yy});var jd=R(gn=>{"use strict";var _d=bi(),vn=e=>typeof e=="bigint"||Number.isInteger(e);function ra(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 Rs(e,t,i){let{value:n}=e;if(vn(n)){let r=n.toString(t);return n<0?"-"+i+r.substr(1):i+r}return _d.stringifyNumber(e)}var ky={identify:vn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>ra(e,2,2,i),stringify:e=>Rs(e,2,"0b")},Sy={identify:vn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>ra(e,1,8,i),stringify:e=>Rs(e,8,"0")},Ey={identify:vn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>ra(e,0,10,i),stringify:_d.stringifyNumber},Cy={identify:vn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>ra(e,2,16,i),stringify:e=>Rs(e,16,"0x")};gn.int=Ey;gn.intBin=ky;gn.intHex=Cy;gn.intOct=Sy});var As=R(Ps=>{"use strict";var sa=M(),aa=Et(),oa=Rt(),Ut=class e extends oa.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;sa.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new aa.Pair(t.key,null):i=new aa.Pair(t,null),oa.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let n=oa.findPair(this.items,t);return!i&&sa.isPair(n)?sa.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=oa.findPair(this.items,t);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new aa.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(aa.createPair(o,null,n));return a}};Ut.tag="tag:yaml.org,2002:set";var Ry={collection:"map",identify:e=>e instanceof Set,nodeClass:Ut,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Ut.from(e,t,i),resolve(e,t){if(sa.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Ut,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Ps.YAMLSet=Ut;Ps.set=Ry});var Ts=R(ca=>{"use strict";var Py=bi();function xs(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 Od(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Py.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 Ay={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})=>xs(e,i),stringify:Od},xy={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=>xs(e,!1),stringify:Od},$d={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($d.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),u=t[8];if(u&&u!=="Z"){let d=xs(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ca.floatTime=xy;ca.intTime=Ay;ca.timestamp=$d});var Dd=R(Fd=>{"use strict";var Ty=yi(),Iy=Kr(),_y=Ni(),jy=hn(),Oy=ys(),Hd=Td(),Is=Id(),la=jd(),$y=Br(),Hy=Ss(),Fy=ia(),Dy=As(),_s=Ts(),Ly=[Ty.map,_y.seq,jy.string,Iy.nullTag,Hd.trueTag,Hd.falseTag,la.intBin,la.intOct,la.int,la.intHex,Is.floatNaN,Is.floatExp,Is.float,Oy.binary,$y.merge,Hy.omap,Fy.pairs,Dy.set,_s.intTime,_s.floatTime,_s.timestamp];Fd.schema=Ly});var Ud=R($s=>{"use strict";var qd=yi(),My=Kr(),Vd=Ni(),By=hn(),qy=ds(),js=hs(),Os=ms(),Vy=gd(),Wy=Nd(),Wd=ys(),wn=Br(),zd=Ss(),Jd=ia(),Ld=Dd(),Gd=As(),ua=Ts(),Md=new Map([["core",Vy.schema],["failsafe",[qd.map,Vd.seq,By.string]],["json",Wy.schema],["yaml11",Ld.schema],["yaml-1.1",Ld.schema]]),Bd={binary:Wd.binary,bool:qy.boolTag,float:js.float,floatExp:js.floatExp,floatNaN:js.floatNaN,floatTime:ua.floatTime,int:Os.int,intHex:Os.intHex,intOct:Os.intOct,intTime:ua.intTime,map:qd.map,merge:wn.merge,null:My.nullTag,omap:zd.omap,pairs:Jd.pairs,seq:Vd.seq,set:Gd.set,timestamp:ua.timestamp},zy={"tag:yaml.org,2002:binary":Wd.binary,"tag:yaml.org,2002:merge":wn.merge,"tag:yaml.org,2002:omap":zd.omap,"tag:yaml.org,2002:pairs":Jd.pairs,"tag:yaml.org,2002:set":Gd.set,"tag:yaml.org,2002:timestamp":ua.timestamp};function Jy(e,t,i){let n=Md.get(t);if(n&&!e)return i&&!n.includes(wn.merge)?n.concat(wn.merge):n.slice();let r=n;if(!r)if(Array.isArray(e))r=[];else{let a=Array.from(Md.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(wn.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?Bd[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Bd).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}$s.coreKnownTags=zy;$s.getTags=Jy});var Ds=R(Kd=>{"use strict";var Hs=M(),Gy=yi(),Uy=Ni(),Ky=hn(),da=Ud(),Yy=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Fs=class e{constructor({compat:t,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?da.getTags(t,"compat"):t?da.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?da.coreKnownTags:{},this.tags=da.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,Hs.MAP,{value:Gy.map}),Object.defineProperty(this,Hs.SCALAR,{value:Ky.string}),Object.defineProperty(this,Hs.SEQ,{value:Uy.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Yy:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Kd.Schema=Fs});var Xd=R(Yd=>{"use strict";var Xy=M(),Ls=un(),yn=on();function Qy(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=Ls.createStringifyContext(e,t),{commentString:a}=r.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(yn.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Xy.isNode(e.contents)){if(e.contents.spaceBefore&&n&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(yn.indentComment(u,""))}r.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Ls.stringify(e.contents,r,()=>s=null,c);s&&(l+=yn.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Ls.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
-
`)?(i.push("..."),i.push(
|
|
49
|
+
`}}return t?(p+=`
|
|
50
|
+
`+hr.indentComment(l(t),c),s&&s()):u&&o&&o(),p}function Rh({items:t},e,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=e;r+=a;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),l=!1,d=0,u=[];for(let g=0;g<t.length;++g){let h=t[g],m=null;if(nt.isNode(h))h.spaceBefore&&u.push(""),pr(e,u,h.commentBefore,!1),h.comment&&(m=h.comment);else if(nt.isPair(h)){let N=nt.isNode(h.key)?h.key:null;N&&(N.spaceBefore&&u.push(""),pr(e,u,N.commentBefore,!1),N.comment&&(l=!0));let k=nt.isNode(h.value)?h.value:null;k?(k.comment&&(m=k.comment),k.commentBefore&&(l=!0)):h.value==null&&N?.comment&&(m=N.comment)}m&&(l=!0);let y=ic.stringify(h,c,()=>m=null);l||(l=u.length>d||y.includes(`
|
|
51
|
+
`)),g<t.length-1?y+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=u.reduce((N,k)=>N+k.length+2,2)+(y.length+2)>e.options.lineWidth)),l&&(y+=",")),m&&(y+=hr.lineComment(y,r,s(m))),u.push(y),d=u.length}let{start:f,end:p}=i;if(u.length===0)return f+p;if(!l){let g=u.reduce((h,m)=>h+m.length+2,2);l=e.options.lineWidth>0&&g>e.options.lineWidth}if(l){let g=f;for(let h of u)g+=h?`
|
|
52
|
+
${a}${n}${h}`:`
|
|
53
|
+
`;return`${g}
|
|
54
|
+
${n}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function pr({indent:t,options:{commentString:e}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=hr.indentComment(e(r),t);i.push(a.trimStart())}}rc.stringifyCollection=xh});var qe=w(ua=>{"use strict";var Ah=ca(),_h=oa(),Th=er(),Ve=P(),mr=Fe(),Ih=j();function ei(t,e){let i=Ve.isScalar(e)?e.value:e;for(let r of t)if(Ve.isPair(r)&&(r.key===e||r.key===i||Ve.isScalar(r.key)&&r.key.value===i))return r}var la=class extends Th.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ve.MAP,e),this.items=[]}static from(e,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(e),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(mr.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,i){let r;Ve.isPair(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new mr.Pair(e,e?.value):r=new mr.Pair(e.key,e.value);let n=ei(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Ve.isScalar(n.value)&&Ih.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(e){let i=ei(this.items,e);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(e,i){let n=ei(this.items,e)?.value;return(!i&&Ve.isScalar(n)?n.value:n)??void 0}has(e){return!!ei(this.items,e)}set(e,i){this.add(new mr.Pair(e,i),!0)}toJSON(e,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)_h.addPairToJSMap(i,n,a);return n}toString(e,i,r){if(!e)return JSON.stringify(this);for(let n of this.items)if(!Ve.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ah.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:i})}};ua.YAMLMap=la;ua.findPair=ei});var kt=w(ac=>{"use strict";var jh=P(),nc=qe(),$h={collection:"map",default:!0,nodeClass:nc.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return jh.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,i)=>nc.YAMLMap.from(t,e,i)};ac.map=$h});var We=w(oc=>{"use strict";var Oh=Gt(),Hh=ca(),Dh=er(),gr=P(),Bh=j(),Lh=De(),da=class extends Dh.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(gr.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let i=vr(e);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(e,i){let r=vr(e);if(typeof r!="number")return;let n=this.items[r];return!i&&gr.isScalar(n)?n.value:n}has(e){let i=vr(e);return typeof i=="number"&&i<this.items.length}set(e,i){let r=vr(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let n=this.items[r];gr.isScalar(n)&&Bh.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(e,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(Lh.toJS(a,String(n++),i));return r}toString(e,i,r){return e?Hh.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(e,i,r){let{replacer:n}=r,a=new this(e);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(Oh.createNode(s,void 0,r))}}return a}};function vr(t){let e=gr.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}oc.YAMLSeq=da});var St=w(cc=>{"use strict";var Mh=P(),sc=We(),Fh={collection:"seq",default:!0,nodeClass:sc.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Mh.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,i)=>sc.YAMLSeq.from(t,e,i)};cc.seq=Fh});var ti=w(lc=>{"use strict";var Vh=Xt(),qh={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,i,r){return e=Object.assign({actualString:!0},e),Vh.stringifyString(t,e,i,r)}};lc.string=qh});var wr=w(fc=>{"use strict";var uc=j(),dc={identify:t=>t==null,createNode:()=>new uc.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new uc.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&dc.test.test(t)?t:e.options.nullStr};fc.nullTag=dc});var fa=w(pc=>{"use strict";var Wh=j(),hc={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Wh.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},i){if(t&&hc.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?i.options.trueStr:i.options.falseStr}};pc.boolTag=hc});var Et=w(mc=>{"use strict";function zh({format:t,minFractionDigits:e,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=e-(a.length-o-1);for(;s-- >0;)a+="0"}return a}mc.stringifyNumber=zh});var pa=w(yr=>{"use strict";var Jh=j(),ha=Et(),Gh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ha.stringifyNumber},Uh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():ha.stringifyNumber(t)}},Kh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new Jh.Scalar(parseFloat(t)),i=t.indexOf(".");return i!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-i-1),e},stringify:ha.stringifyNumber};yr.float=Kh;yr.floatExp=Uh;yr.floatNaN=Gh});var va=w(br=>{"use strict";var vc=Et(),Nr=t=>typeof t=="bigint"||Number.isInteger(t),ma=(t,e,i,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),i);function gc(t,e,i){let{value:r}=t;return Nr(r)&&r>=0?i+r.toString(e):vc.stringifyNumber(t)}var Yh={identify:t=>Nr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,i)=>ma(t,2,8,i),stringify:t=>gc(t,8,"0o")},Xh={identify:Nr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,i)=>ma(t,0,10,i),stringify:vc.stringifyNumber},Qh={identify:t=>Nr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,i)=>ma(t,2,16,i),stringify:t=>gc(t,16,"0x")};br.int=Xh;br.intHex=Qh;br.intOct=Yh});var yc=w(wc=>{"use strict";var Zh=kt(),ep=wr(),tp=St(),ip=ti(),rp=fa(),ga=pa(),wa=va(),np=[Zh.map,tp.seq,ip.string,ep.nullTag,rp.boolTag,wa.intOct,wa.int,wa.intHex,ga.floatNaN,ga.floatExp,ga.float];wc.schema=np});var kc=w(bc=>{"use strict";var ap=j(),op=kt(),sp=St();function Nc(t){return typeof t=="bigint"||Number.isInteger(t)}var kr=({value:t})=>JSON.stringify(t),cp=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:kr},{identify:t=>t==null,createNode:()=>new ap.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:kr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:kr},{identify:Nc,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:i})=>i?BigInt(t):parseInt(t,10),stringify:({value:t})=>Nc(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:kr}],lp={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},up=[op.map,sp.seq].concat(cp,lp);bc.schema=up});var Na=w(Sc=>{"use strict";var ii=Wi("buffer"),ya=j(),dp=Xt(),fp={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof ii.Buffer=="function")return ii.Buffer.from(t,"base64");if(typeof atob=="function"){let i=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof ii.Buffer=="function")s=o instanceof ii.Buffer?o.toString("base64"):ii.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=ya.Scalar.BLOCK_LITERAL),e!==ya.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),d=new Array(l);for(let u=0,f=0;u<l;++u,f+=c)d[u]=s.substr(f,c);s=d.join(e===ya.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return dp.stringifyString({comment:t,type:e,value:s},r,n,a)}};Sc.binary=fp});var Pr=w(Er=>{"use strict";var Sr=P(),ba=Fe(),hp=j(),pp=We();function Ec(t,e){if(Sr.isSeq(t))for(let i=0;i<t.items.length;++i){let r=t.items[i];if(!Sr.isPair(r)){if(Sr.isMap(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let n=r.items[0]||new ba.Pair(new hp.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
|
|
56
|
+
${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
|
|
57
|
+
${a.comment}`:r.comment}r=n}t.items[i]=Sr.isPair(r)?r:new ba.Pair(r)}}else e("Expected a sequence for this tag");return t}function Pc(t,e,i){let{replacer:r}=i,n=new pp.YAMLSeq(t);n.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof r=="function"&&(o=r.call(e,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(ba.createPair(s,c,i))}return n}var mp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ec,createNode:Pc};Er.createPairs=Pc;Er.pairs=mp;Er.resolvePairs=Ec});var Ea=w(Sa=>{"use strict";var xc=P(),ka=De(),ri=qe(),vp=We(),Cc=Pr(),at=class t extends vp.YAMLSeq{constructor(){super(),this.add=ri.YAMLMap.prototype.add.bind(this),this.delete=ri.YAMLMap.prototype.delete.bind(this),this.get=ri.YAMLMap.prototype.get.bind(this),this.has=ri.YAMLMap.prototype.has.bind(this),this.set=ri.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,i){if(!i)return super.toJSON(e);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(xc.isPair(n)?(a=ka.toJS(n.key,"",i),o=ka.toJS(n.value,a,i)):a=ka.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(e,i,r){let n=Cc.createPairs(e,i,r),a=new this;return a.items=n.items,a}};at.tag="tag:yaml.org,2002:omap";var gp={collection:"seq",identify:t=>t instanceof Map,nodeClass:at,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=Cc.resolvePairs(t,e),r=[];for(let{key:n}of i.items)xc.isScalar(n)&&(r.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new at,i)},createNode:(t,e,i)=>at.from(t,e,i)};Sa.YAMLOMap=at;Sa.omap=gp});var Ic=w(Pa=>{"use strict";var Rc=j();function Ac({value:t,source:e},i){return e&&(t?_c:Tc).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var _c={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Rc.Scalar(!0),stringify:Ac},Tc={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Rc.Scalar(!1),stringify:Ac};Pa.falseTag=Tc;Pa.trueTag=_c});var jc=w(xr=>{"use strict";var wp=j(),xa=Et(),yp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:xa.stringifyNumber},Np={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():xa.stringifyNumber(t)}},bp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new wp.Scalar(parseFloat(t.replace(/_/g,""))),i=t.indexOf(".");if(i!==-1){let r=t.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:xa.stringifyNumber};xr.float=bp;xr.floatExp=Np;xr.floatNaN=yp});var Oc=w(ai=>{"use strict";var $c=Et(),ni=t=>typeof t=="bigint"||Number.isInteger(t);function Cr(t,e,i,{intAsBigInt:r}){let n=t[0];if((n==="-"||n==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(i){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return n==="-"?BigInt(-1)*o:o}let a=parseInt(t,i);return n==="-"?-1*a:a}function Ca(t,e,i){let{value:r}=t;if(ni(r)){let n=r.toString(e);return r<0?"-"+i+n.substr(1):i+n}return $c.stringifyNumber(t)}var kp={identify:ni,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>Cr(t,2,2,i),stringify:t=>Ca(t,2,"0b")},Sp={identify:ni,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>Cr(t,1,8,i),stringify:t=>Ca(t,8,"0")},Ep={identify:ni,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>Cr(t,0,10,i),stringify:$c.stringifyNumber},Pp={identify:ni,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>Cr(t,2,16,i),stringify:t=>Ca(t,16,"0x")};ai.int=Ep;ai.intBin=kp;ai.intHex=Pp;ai.intOct=Sp});var Aa=w(Ra=>{"use strict";var _r=P(),Rr=Fe(),Ar=qe(),ot=class t extends Ar.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;_r.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new Rr.Pair(e.key,null):i=new Rr.Pair(e,null),Ar.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let r=Ar.findPair(this.items,e);return!i&&_r.isPair(r)?_r.isScalar(r.key)?r.key.value:r.key:r}set(e,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Ar.findPair(this.items,e);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Rr.Pair(e))}toJSON(e,i){return super.toJSON(e,i,Set)}toString(e,i,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(e,i,r){let{replacer:n}=r,a=new this(e);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Rr.createPair(o,null,r));return a}};ot.tag="tag:yaml.org,2002:set";var xp={collection:"map",identify:t=>t instanceof Set,nodeClass:ot,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>ot.from(t,e,i),resolve(t,e){if(_r.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new ot,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Ra.YAMLSet=ot;Ra.set=xp});var Ta=w(Tr=>{"use strict";var Cp=Et();function _a(t,e){let i=t[0],r=i==="-"||i==="+"?t.substring(1):t,n=o=>e?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Hc(t){let{value:e}=t,i=o=>o;if(typeof e=="bigint")i=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Cp.stringifyNumber(t);let r="";e<0&&(r="-",e*=i(-1));let n=i(60),a=[e%n];return e<60?a.unshift(0):(e=(e-a[0])/n,a.unshift(e%n),e>=60&&(e=(e-a[0])/n,a.unshift(e))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Rp={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:i})=>_a(t,i),stringify:Hc},Ap={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>_a(t,!1),stringify:Hc},Dc={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Dc.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),d=e[8];if(d&&d!=="Z"){let u=_a(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Tr.floatTime=Ap;Tr.intTime=Rp;Tr.timestamp=Dc});var Mc=w(Lc=>{"use strict";var _p=kt(),Tp=wr(),Ip=St(),jp=ti(),$p=Na(),Bc=Ic(),Ia=jc(),Ir=Oc(),Op=ur(),Hp=Ea(),Dp=Pr(),Bp=Aa(),ja=Ta(),Lp=[_p.map,Ip.seq,jp.string,Tp.nullTag,Bc.trueTag,Bc.falseTag,Ir.intBin,Ir.intOct,Ir.int,Ir.intHex,Ia.floatNaN,Ia.floatExp,Ia.float,$p.binary,Op.merge,Hp.omap,Dp.pairs,Bp.set,ja.intTime,ja.floatTime,ja.timestamp];Lc.schema=Lp});var Yc=w(Ha=>{"use strict";var Wc=kt(),Mp=wr(),zc=St(),Fp=ti(),Vp=fa(),$a=pa(),Oa=va(),qp=yc(),Wp=kc(),Jc=Na(),oi=ur(),Gc=Ea(),Uc=Pr(),Fc=Mc(),Kc=Aa(),jr=Ta(),Vc=new Map([["core",qp.schema],["failsafe",[Wc.map,zc.seq,Fp.string]],["json",Wp.schema],["yaml11",Fc.schema],["yaml-1.1",Fc.schema]]),qc={binary:Jc.binary,bool:Vp.boolTag,float:$a.float,floatExp:$a.floatExp,floatNaN:$a.floatNaN,floatTime:jr.floatTime,int:Oa.int,intHex:Oa.intHex,intOct:Oa.intOct,intTime:jr.intTime,map:Wc.map,merge:oi.merge,null:Mp.nullTag,omap:Gc.omap,pairs:Uc.pairs,seq:zc.seq,set:Kc.set,timestamp:jr.timestamp},zp={"tag:yaml.org,2002:binary":Jc.binary,"tag:yaml.org,2002:merge":oi.merge,"tag:yaml.org,2002:omap":Gc.omap,"tag:yaml.org,2002:pairs":Uc.pairs,"tag:yaml.org,2002:set":Kc.set,"tag:yaml.org,2002:timestamp":jr.timestamp};function Jp(t,e,i){let r=Vc.get(e);if(r&&!t)return i&&!r.includes(oi.merge)?r.concat(oi.merge):r.slice();let n=r;if(!n)if(Array.isArray(t))n=[];else{let a=Array.from(Vc.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)n=n.concat(a);else typeof t=="function"&&(n=t(n.slice()));return i&&(n=n.concat(oi.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?qc[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(qc).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Ha.coreKnownTags=zp;Ha.getTags=Jp});var La=w(Xc=>{"use strict";var Da=P(),Gp=kt(),Up=St(),Kp=ti(),$r=Yc(),Yp=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,Ba=class t{constructor({compat:e,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?$r.getTags(e,"compat"):e?$r.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?$r.coreKnownTags:{},this.tags=$r.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Da.MAP,{value:Gp.map}),Object.defineProperty(this,Da.SCALAR,{value:Kp.string}),Object.defineProperty(this,Da.SEQ,{value:Up.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Yp:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Xc.Schema=Ba});var Zc=w(Qc=>{"use strict";var Xp=P(),Ma=Qt(),si=Ut();function Qp(t,e){let i=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(i.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&i.push("---");let n=Ma.createStringifyContext(t,e),{commentString:a}=n.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=a(t.commentBefore);i.unshift(si.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(Xp.isNode(t.contents)){if(t.contents.spaceBefore&&r&&i.push(""),t.contents.commentBefore){let d=a(t.contents.commentBefore);i.push(si.indentComment(d,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Ma.stringify(t.contents,n,()=>s=null,c);s&&(l+=si.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Ma.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
|
|
58
|
+
`)?(i.push("..."),i.push(si.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(si.indentComment(a(c),"")))}return i.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
61
|
-
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===
|
|
60
|
+
`}Qc.stringifyDocument=Qp});var ci=w(el=>{"use strict";var Zp=Jt(),Pt=er(),ee=P(),em=Fe(),tm=De(),im=La(),rm=Zc(),Fa=Yi(),nm=zn(),am=Gt(),Va=Wn(),qa=class t{constructor(e,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ee.NODE_TYPE,{value:ee.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Va.Directives({version:o}),this.setSchema(o,r),this.contents=e===void 0?null:this.createNode(e,n,r)}clone(){let e=Object.create(t.prototype,{[ee.NODE_TYPE]:{value:ee.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=ee.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){xt(this.contents)&&this.contents.add(e)}addIn(e,i){xt(this.contents)&&this.contents.addIn(e,i)}createAlias(e,i){if(!e.anchor){let r=Fa.anchorNames(this);e.anchor=!i||r.has(i)?Fa.findNewAnchor(i||"a",r):i}return new Zp.Alias(e.anchor)}createNode(e,i,r){let n;if(typeof i=="function")e=i.call({"":e},"",e),n=i;else if(Array.isArray(i)){let m=N=>typeof N=="number"||N instanceof String||N instanceof Number,y=i.filter(m).map(String);y.length>0&&(i=i.concat(y)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:d}=r??{},{onAnchor:u,setAnchors:f,sourceObjects:p}=Fa.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=am.createNode(e,d,g);return s&&ee.isCollection(h)&&(h.flow=!0),f(),h}createPair(e,i,r={}){let n=this.createNode(e,null,r),a=this.createNode(i,null,r);return new em.Pair(n,a)}delete(e){return xt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Pt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):xt(this.contents)?this.contents.deleteIn(e):!1}get(e,i){return ee.isCollection(this.contents)?this.contents.get(e,i):void 0}getIn(e,i){return Pt.isEmptyPath(e)?!i&&ee.isScalar(this.contents)?this.contents.value:this.contents:ee.isCollection(this.contents)?this.contents.getIn(e,i):void 0}has(e){return ee.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Pt.isEmptyPath(e)?this.contents!==void 0:ee.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,i){this.contents==null?this.contents=Pt.collectionFromPath(this.schema,[e],i):xt(this.contents)&&this.contents.set(e,i)}setIn(e,i){Pt.isEmptyPath(e)?this.contents=i:this.contents==null?this.contents=Pt.collectionFromPath(this.schema,Array.from(e),i):xt(this.contents)&&this.contents.setIn(e,i)}setSchema(e,i={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Va.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Va.Directives({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new im.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=tm.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:d}of s.anchors.values())a(d,l);return typeof o=="function"?nm.applyReviver(o,{"":c},"",c):c}toJSON(e,i){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:i})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let i=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return rm.stringifyDocument(this,e)}};function xt(t){if(ee.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}el.Document=qa});var di=w(ui=>{"use strict";var li=class extends Error{constructor(e,i,r,n){super(),this.name=e,this.code=r,this.message=n,this.pos=i}},Wa=class extends li{constructor(e,i,r){super("YAMLParseError",e,i,r)}},za=class extends li{constructor(e,i,r){super("YAMLWarning",e,i,r)}},om=(t,e)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>e.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=t.substring(e.lineStarts[r-2],e.lineStarts[r-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===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};
|
|
66
|
-
`))return!0;if(
|
|
67
|
-
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||
|
|
68
|
-
`+k.comment:N.comment=k.comment);let
|
|
69
|
-
`+
|
|
70
|
-
`+
|
|
71
|
-
`+
|
|
72
|
-
`+
|
|
73
|
-
`.repeat(Math.max(1,o.length-1)):"",
|
|
74
|
-
`;for(let h=
|
|
75
|
-
`):
|
|
65
|
+
`}};ui.YAMLError=li;ui.YAMLParseError=Wa;ui.YAMLWarning=za;ui.prettifyError=om});var fi=w(tl=>{"use strict";function sm(t,{flow:e,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,d=s,u="",f="",p=!1,g=!1,h=null,m=null,y=null,N=null,k=null,S=null,E=null;for(let b of t)switch(g&&(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"),g=!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":!e&&(i!=="doc-start"||r?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),d=!0;break;case"comment":{d||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let _=b.source.substring(1)||" ";u?u+=f+_:u=_,f="",l=!1;break}case"newline":l?u?u+=b.source:(!S||i!=="seq-item-ind")&&(c=!0):f+=b.source,l=!0,p=!0,(m||y)&&(N=b),d=!0;break;case"anchor":m&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=b,E??(E=b.offset),l=!1,d=!1,g=!0;break;case"tag":{y&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),y=b,E??(E=b.offset),l=!1,d=!1,g=!0;break}case i:(m||y)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),S&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${e??"collection"}`),S=b,l=i==="seq-item-ind"||i==="explicit-key-ind",d=!1;break;case"comma":if(e){k&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=b,l=!1,d=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,d=!1}let v=t[t.length-1],x=v?v.offset+v.source.length:n;return g&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:u,hasNewline:p,anchor:m,tag:y,newlineAfterProp:N,end:x,start:E??x}}tl.resolveProps=sm});var Or=w(il=>{"use strict";function Ja(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
|
|
66
|
+
`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let i of e.start)if(i.type==="newline")return!0;if(e.sep){for(let i of e.sep)if(i.type==="newline")return!0}if(Ja(e.key)||Ja(e.value))return!0}return!1;default:return!0}}il.containsNewline=Ja});var Ga=w(rl=>{"use strict";var cm=Or();function lm(t,e,i){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&cm.containsNewline(e)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}rl.flowIndentCheck=lm});var Ua=w(al=>{"use strict";var nl=P();function um(t,e,i){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||nl.isScalar(a)&&nl.isScalar(o)&&a.value===o.value;return e.some(a=>n(a.key,i))}al.mapIncludes=um});var dl=w(ul=>{"use strict";var ol=Fe(),dm=qe(),sl=fi(),fm=Or(),cl=Ga(),hm=Ua(),ll="All mapping items must start at the same column";function pm({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=a?.nodeClass??dm.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let d of r.items){let{start:u,key:f,sep:p,value:g}=d,h=sl.resolveProps(u,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",ll)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||fm.containsNewline(f))&&n(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",ll);i.atKey=!0;let y=h.end,N=f?t(i,f,h,n):e(i,y,u,null,h,n);i.schema.compat&&cl.flowIndentCheck(r.indent,f,n),i.atKey=!1,hm.mapIncludes(i,s.items,N)&&n(y,"DUPLICATE_KEY","Map keys must be unique");let k=sl.resolveProps(p??[],{indicator:"map-value-ind",next:g,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){m&&(g?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<k.found.offset-1024&&n(N.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let S=g?t(i,g,k,n):e(i,c,p,null,k,n);i.schema.compat&&cl.flowIndentCheck(r.indent,g,n),c=S.range[2];let E=new ol.Pair(N,S);i.options.keepSourceTokens&&(E.srcToken=d),s.items.push(E)}else{m&&n(N.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(N.comment?N.comment+=`
|
|
68
|
+
`+k.comment:N.comment=k.comment);let S=new ol.Pair(N);i.options.keepSourceTokens&&(S.srcToken=d),s.items.push(S)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}ul.resolveBlockMap=pm});var hl=w(fl=>{"use strict";var mm=We(),vm=fi(),gm=Ga();function wm({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=a?.nodeClass??mm.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:d,value:u}of r.items){let f=vm.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=u?t(i,u,f,n):e(i,f.end,d,null,f,n);i.schema.compat&&gm.flowIndentCheck(r.indent,u,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}fl.resolveBlockSeq=wm});var Ct=w(pl=>{"use strict";function ym(t,e,i,r){let n="";if(t){let a=!1,o="";for(let s of t){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";n?n+=o+d:n=d,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:n,offset:e}}pl.resolveEnd=ym});var wl=w(gl=>{"use strict";var Nm=P(),bm=Fe(),ml=qe(),km=We(),Sm=Ct(),vl=fi(),Em=Or(),Pm=Ua(),Ka="Block collections are not allowed within flow collections",Ya=t=>t&&(t.type==="block-map"||t.type==="block-seq");function xm({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?ml.YAMLMap:km.YAMLSeq),l=new c(i.schema);l.flow=!0;let d=i.atRoot;d&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let u=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let y=r.items[m],{start:N,key:k,sep:S,value:E}=y,v=vl.resolveProps(N,{flow:s,indicator:"explicit-key-ind",next:k??S?.[0],offset:u,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!v.found){if(!v.anchor&&!v.tag&&!S&&!E){m===0&&v.comma?n(v.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(v.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),v.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+v.comment:l.comment=v.comment),u=v.end;continue}!o&&i.options.strict&&Em.containsNewline(k)&&n(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)v.comma&&n(v.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(v.comma||n(v.start,"MISSING_CHAR",`Missing , between ${s} items`),v.comment){let x="";e:for(let b of N)switch(b.type){case"comma":case"space":break;case"comment":x=b.source.substring(1);break e;default:break e}if(x){let b=l.items[l.items.length-1];Nm.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
|
|
70
|
+
`+x:b.comment=x,v.comment=v.comment.substring(x.length+1)}}if(!o&&!S&&!v.found){let x=E?t(i,E,v,n):e(i,v.end,S,null,v,n);l.items.push(x),u=x.range[2],Ya(E)&&n(x.range,"BLOCK_IN_FLOW",Ka)}else{i.atKey=!0;let x=v.end,b=k?t(i,k,v,n):e(i,x,N,null,v,n);Ya(k)&&n(b.range,"BLOCK_IN_FLOW",Ka),i.atKey=!1;let _=vl.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:E,offset:b.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!v.found&&i.options.strict){if(S)for(let $ of S){if($===_.found)break;if($.type==="newline"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}v.start<_.found.offset-1024&&n(_.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]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(_.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let U=E?t(i,E,_,n):_.found?e(i,_.end,S,null,_,n):null;U?Ya(E)&&n(U.range,"BLOCK_IN_FLOW",Ka):_.comment&&(b.comment?b.comment+=`
|
|
71
|
+
`+_.comment:b.comment=_.comment);let gt=new bm.Pair(b,U);if(i.options.keepSourceTokens&&(gt.srcToken=y),o){let $=l;Pm.mapIncludes(i,$.items,b)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(gt)}else{let $=new ml.YAMLMap(i.schema);$.flow=!0,$.items.push(gt);let gs=(U??b).range;$.range=[b.range[0],gs[1],gs[2]],l.items.push($)}u=U?U.range[2]:_.end}}let f=o?"}":"]",[p,...g]=r.end,h=u;if(p?.source===f)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),y=d?`${m} must end with a ${f}`:`${m} in block collection must be sufficiently indented and end with a ${f}`;n(u,d?"MISSING_CHAR":"BAD_INDENT",y),p&&p.source.length!==1&&g.unshift(p)}if(g.length>0){let m=Sm.resolveEnd(g,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}gl.resolveFlowCollection=xm});var Nl=w(yl=>{"use strict";var Cm=P(),Rm=j(),Am=qe(),_m=We(),Tm=dl(),Im=hl(),jm=wl();function Xa(t,e,i,r,n,a){let o=i.type==="block-map"?Tm.resolveBlockMap(t,e,i,r,a):i.type==="block-seq"?Im.resolveBlockSeq(t,e,i,r,a):jm.resolveFlowCollection(t,e,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function $m(t,e,i,r,n){let a=r.tag,o=a?e.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,g=f&&a?f.offset>a.offset?f:a:f??a;g&&(!p||p.offset<g.offset)&&n(g,"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===Am.YAMLMap.tagName&&s==="map"||o===_m.YAMLSeq.tagName&&s==="seq")return Xa(t,e,i,n,o);let c=e.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=e.schema.knownTags[o];if(f?.collection===s)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Xa(t,e,i,n,o)}let l=Xa(t,e,i,n,o,c),d=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),e.options)??l,u=Cm.isNode(d)?d:new Rm.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}yl.composeCollection=$m});var Za=w(bl=>{"use strict";var Qa=j();function Om(t,e,i){let r=e.offset,n=Hm(e,t.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Qa.Scalar.BLOCK_FOLDED:Qa.Scalar.BLOCK_LITERAL,o=e.source?Dm(e.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return e.source&&(m+=e.source.length),{value:h,type:a,comment:n.comment,range:[r,m,m]}}let c=e.indent+n.indent,l=e.offset+n.length,d=0;for(let h=0;h<s;++h){let[m,y]=o[h];if(y===""||y==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&i(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=m.length),d=h,c===0&&!t.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+y.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let u="",f="",p=!1;for(let h=0;h<d;++h)u+=o[h][0].slice(c)+`
|
|
74
|
+
`;for(let h=d;h<s;++h){let[m,y]=o[h];l+=m.length+y.length+1;let N=y[y.length-1]==="\r";if(N&&(y=y.slice(0,-1)),y&&m.length<c){let S=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-y.length-(N?2:1),"BAD_INDENT",S),m=""}a===Qa.Scalar.BLOCK_LITERAL?(u+=f+m.slice(c)+y,f=`
|
|
75
|
+
`):m.length>c||y[0]===" "?(f===" "?f=`
|
|
76
76
|
`:!p&&f===`
|
|
77
77
|
`&&(f=`
|
|
78
78
|
|
|
79
|
-
`),
|
|
80
|
-
`,p=!0):
|
|
81
|
-
`?
|
|
79
|
+
`),u+=f+m.slice(c)+y,f=`
|
|
80
|
+
`,p=!0):y===""?f===`
|
|
81
|
+
`?u+=`
|
|
82
82
|
`:f=`
|
|
83
|
-
`:(
|
|
84
|
-
`+o[h][0].slice(c);
|
|
85
|
-
`&&(
|
|
86
|
-
`);break;default:
|
|
87
|
-
`}let
|
|
83
|
+
`:(u+=f+y,f=" ",p=!1)}switch(n.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 g=r+n.length+e.source.length;return{value:u,type:a,comment:n.comment,range:[r,g,g]}}function Hm({offset:t,props:e},i,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=e[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let p=n[f];if(!s&&(p==="-"||p==="+"))s=p;else{let g=Number(p);!o&&g?o=g:c===-1&&(c=t+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,d="",u=n.length;for(let f=1;f<e.length;++f){let p=e[f];switch(p.type){case"space":l=!0;case"newline":u+=p.source.length;break;case"comment":i&&!l&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,d=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let g=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",g);let h=p.source;h&&typeof h=="string"&&(u+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:d,length:u}}function Dm(t){let e=t.split(/\n( *)/),i=e[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<e.length;o+=2)a.push([e[o],e[o+1]]);return a}bl.resolveBlockScalar=Om});var to=w(Sl=>{"use strict";var eo=j(),Bm=Ct();function Lm(t,e,i){let{offset:r,type:n,source:a,end:o}=t,s,c,l=(f,p,g)=>i(r+f,p,g);switch(n){case"scalar":s=eo.Scalar.PLAIN,c=Mm(a,l);break;case"single-quoted-scalar":s=eo.Scalar.QUOTE_SINGLE,c=Fm(a,l);break;case"double-quoted-scalar":s=eo.Scalar.QUOTE_DOUBLE,c=Vm(a,l);break;default:return i(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let d=r+a.length,u=Bm.resolveEnd(o,d,e,i);return{value:c,type:s,comment:u.comment,range:[r,d,u.offset]}}function Mm(t,e){let i="";switch(t[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${t[0]}`;break}case"@":case"`":{i=`reserved character ${t[0]}`;break}}return i&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),kl(t)}function Fm(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),kl(t.slice(1,-1)).replace(/''/g,"'")}function kl(t){let e,i;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
|
-
`,"sy")}catch{
|
|
90
|
-
`?
|
|
91
|
-
`:(
|
|
92
|
-
`))if(
|
|
93
|
-
`){let{fold:a,offset:o}=
|
|
94
|
-
`)for(a=
|
|
95
|
-
`)for(a=
|
|
96
|
-
`&&!(o==="\r"&&
|
|
97
|
-
`)&&(i+=
|
|
98
|
-
`||
|
|
99
|
-
`);)
|
|
89
|
+
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=e.exec(t);if(!r)return t;let n=r[1],a=" ",o=e.lastIndex;for(i.lastIndex=o;r=i.exec(t);)r[1]===""?a===`
|
|
90
|
+
`?n+=a:a=`
|
|
91
|
+
`:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(t),n+a+(r?.[1]??"")}function Vm(t,e){let i="";for(let r=1;r<t.length-1;++r){let n=t[r];if(!(n==="\r"&&t[r+1]===`
|
|
92
|
+
`))if(n===`
|
|
93
|
+
`){let{fold:a,offset:o}=qm(t,r);i+=a,r=o}else if(n==="\\"){let a=t[++r],o=Wm[a];if(o)i+=o;else if(a===`
|
|
94
|
+
`)for(a=t[r+1];a===" "||a===" ";)a=t[++r+1];else if(a==="\r"&&t[r+1]===`
|
|
95
|
+
`)for(a=t[++r+1];a===" "||a===" ";)a=t[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=zm(t,r+1,s,e),r+=s}else{let s=t.substr(r-1,2);e(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=t[r+1];for(;o===" "||o===" ";)o=t[++r+1];o!==`
|
|
96
|
+
`&&!(o==="\r"&&t[r+2]===`
|
|
97
|
+
`)&&(i+=r>a?t.slice(a,r+1):n)}else i+=n}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),i}function qm(t,e){let i="",r=t[e+1];for(;(r===" "||r===" "||r===`
|
|
98
|
+
`||r==="\r")&&!(r==="\r"&&t[e+2]!==`
|
|
99
|
+
`);)r===`
|
|
100
100
|
`&&(i+=`
|
|
101
|
-
`),
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),e+=1,r=t[e+1];return i||(i=" "),{fold:i,offset:e}}var Wm={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function zm(t,e,i,r){let n=t.substr(e,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=t.substr(e-2,i+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Sl.resolveFlowScalar=Lm});var xl=w(Pl=>{"use strict";var st=P(),El=j(),Jm=Za(),Gm=to();function Um(t,e,i,r){let{value:n,type:a,comment:o,range:s}=e.type==="block-scalar"?Jm.resolveBlockScalar(t,e,r):Gm.resolveFlowScalar(e,t.options.strict,r),c=i?t.directives.tagName(i.source,u=>r(i,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[st.SCALAR]:c?l=Km(t.schema,n,c,i,r):e.type==="scalar"?l=Ym(t,n,e,r):l=t.schema[st.SCALAR];let d;try{let u=l.resolve(n,f=>r(i??e,"TAG_RESOLVE_FAILED",f),t.options);d=st.isScalar(u)?u:new El.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);r(i??e,"TAG_RESOLVE_FAILED",f),d=new El.Scalar(n)}return d.range=s,d.source=n,a&&(d.type=a),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function Km(t,e,i,r,n){if(i==="!")return t[st.SCALAR];let a=[];for(let s of t.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(e))return s;let o=t.knownTags[i];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),t[st.SCALAR])}function Ym({atKey:t,directives:e,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(r))||i[st.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[st.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),d=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",d,!0)}}return o}Pl.composeScalar=Um});var Rl=w(Cl=>{"use strict";function Xm(t,e,i){if(e){i??(i=e.length);for(let r=i-1;r>=0;--r){let n=e[r];switch(n.type){case"space":case"comment":case"newline":t-=n.source.length;continue}for(n=e[++r];n?.type==="space";)t+=n.source.length,n=e[++r];break}}return t}Cl.emptyScalarPosition=Xm});var Tl=w(ro=>{"use strict";var Qm=Jt(),Zm=P(),ev=Nl(),Al=xl(),tv=Ct(),iv=Rl(),rv={composeNode:_l,composeEmptyNode:io};function _l(t,e,i,r){let n=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,d=!0;switch(e.type){case"alias":l=nv(t,e,r),(s||c)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Al.composeScalar(t,e,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=ev.composeCollection(rv,t,e,i,r),s&&(l.anchor=s.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);r(e,"RESOURCE_EXHAUSTION",f)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",u),d=!1}}return l??(l=io(t,e.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&t.options.stringKeys&&(!Zm.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&d&&(l.srcToken=e),l}function io(t,e,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let d={type:"scalar",offset:iv.emptyScalarPosition(e,i,r),indent:-1,source:""},u=Al.composeScalar(t,d,s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function nv({options:t},{offset:e,source:i,end:r},n){let a=new Qm.Alias(i.substring(1));a.source===""&&n(e,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(e+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+i.length,s=tv.resolveEnd(r,o,t.strict,n);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}ro.composeEmptyNode=io;ro.composeNode=_l});var $l=w(jl=>{"use strict";var av=ci(),Il=Tl(),ov=Ct(),sv=fi();function cv(t,e,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:e},t),c=new av.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=sv.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Il.composeNode(l,n,d,o):Il.composeEmptyNode(l,d.end,r,null,d,o);let u=c.contents.range[2],f=ov.resolveEnd(a,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,u,f.offset],c}jl.composeDoc=cv});var ao=w(Dl=>{"use strict";var lv=Wi("process"),uv=Wn(),dv=ci(),hi=di(),Ol=P(),fv=$l(),hv=Ct();function pi(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:i}=t;return[e,e+(typeof i=="string"?i.length:1)]}function Hl(t){let e="",i=!1,r=!1;for(let n=0;n<t.length;++n){let a=t[n];switch(a[0]){case"#":e+=(e===""?"":r?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.substring(1)||" "),i=!0,
|
|
106
|
-
${
|
|
107
|
-
${s}`:
|
|
108
|
-
${o}`:
|
|
109
|
-
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new
|
|
105
|
+
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":t[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:e,afterEmptyLine:r}}var no=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=pi(i);a?this.warnings.push(new hi.YAMLWarning(o,r,n)):this.errors.push(new hi.YAMLParseError(o,r,n))},this.directives=new uv.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,i){let{comment:r,afterEmptyLine:n}=Hl(this.prelude);if(r){let a=e.contents;if(i)e.comment=e.comment?`${e.comment}
|
|
106
|
+
${r}`:r;else if(n||e.directives.docStart||!a)e.commentBefore=r;else if(Ol.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Ol.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
|
|
107
|
+
${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
|
|
108
|
+
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)e.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)e.warnings.push(this.warnings[a])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Hl(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,i=!1,r=-1){for(let n of e)yield*this.next(n);yield*this.end(i,r)}*next(e){switch(lv.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(i,r,n)=>{let a=pi(e);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let i=fv.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let i=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new hi.YAMLParseError(pi(e),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new hi.YAMLParseError(pi(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=hv.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
|
|
109
|
+
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new hi.YAMLParseError(pi(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),n=new dv.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};Dl.Composer=no});var Ml=w(Hr=>{"use strict";var pv=Za(),mv=to(),vv=di(),Bl=Xt();function gv(t,e=!0,i){if(t){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new vv.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return mv.resolveFlowScalar(t,e,r);case"block-scalar":return pv.resolveBlockScalar({options:{strict:e}},t,r)}}return null}function wv(t,e){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=e,s=Bl.stringifyString({type:o,value:t},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:r,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
|
-
`),
|
|
112
|
-
`,f=[{type:"block-scalar-header",offset:a,indent:
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:
|
|
114
|
-
`),
|
|
115
|
-
`;if(
|
|
116
|
-
`});for(let c of Object.keys(
|
|
117
|
-
`};delete
|
|
111
|
+
`),d=s.substring(0,l),u=s.substring(l+1)+`
|
|
112
|
+
`,f=[{type:"block-scalar-header",offset:a,indent:r,source:d}];return Ll(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:r,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function yv(t,e,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in t?t.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Bl.stringifyString({type:o,value:e},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Nv(t,c);break;case'"':oo(t,c,"double-quoted-scalar");break;case"'":oo(t,c,"single-quoted-scalar");break;default:oo(t,c,"scalar")}}function Nv(t,e){let i=e.indexOf(`
|
|
114
|
+
`),r=e.substring(0,i),n=e.substring(i+1)+`
|
|
115
|
+
`;if(t.type==="block-scalar"){let a=t.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,t.source=n}else{let{offset:a}=t,o="indent"in t?t.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];Ll(s,"end"in t?t.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:n})}}function Ll(t,e){if(e)for(let i of e)switch(i.type){case"space":case"comment":t.push(i);break;case"newline":return t.push(i),!0}return!1}function oo(t,e,i){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=i,t.source=e;break;case"block-scalar":{let r=t.props.slice(1),n=e.length;t.props[0].type==="block-scalar-header"&&(n-=t.props[0].source.length);for(let a of r)a.offset+=n;delete t.props,Object.assign(t,{type:i,source:e,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:t.offset+e.length,indent:t.indent,source:`
|
|
117
|
+
`};delete t.items,Object.assign(t,{type:i,source:e,end:[n]});break}default:{let r="indent"in t?t.indent:-1,n="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:i,indent:r,source:e,end:n})}}}Hr.createScalarToken=wv;Hr.resolveAsScalar=gv;Hr.setScalarValue=yv});var Vl=w(Fl=>{"use strict";var bv=t=>"type"in t?Br(t):Dr(t);function Br(t){switch(t.type){case"block-scalar":{let e="";for(let i of t.props)e+=Br(i);return e+t.source}case"block-map":case"block-seq":{let e="";for(let i of t.items)e+=Dr(i);return e}case"flow-collection":{let e=t.start.source;for(let i of t.items)e+=Dr(i);for(let i of t.end)e+=i.source;return e}case"document":{let e=Dr(t);if(t.end)for(let i of t.end)e+=i.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let i of t.end)e+=i.source;return e}}}function Dr({start:t,key:e,sep:i,value:r}){let n="";for(let a of t)n+=a.source;if(e&&(n+=Br(e)),i)for(let a of i)n+=a.source;return r&&(n+=Br(r)),n}Fl.stringify=bv});var Jl=w(zl=>{"use strict";var so=Symbol("break visit"),kv=Symbol("skip children"),ql=Symbol("remove item");function ct(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Wl(Object.freeze([]),t,e)}ct.BREAK=so;ct.SKIP=kv;ct.REMOVE=ql;ct.itemAtPath=(t,e)=>{let i=t;for(let[r,n]of e){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};ct.parentCollection=(t,e)=>{let i=ct.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Wl(t,e,i){let r=i(e,t);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=e[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Wl(Object.freeze(t.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===so)return so;s===ql&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(e,t))}}return typeof r=="function"?r(e,t):r}zl.visit=ct});var Lr=w(W=>{"use strict";var co=Ml(),Sv=Vl(),Ev=Jl(),lo="\uFEFF",uo="",fo="",ho="",Pv=t=>!!t&&"items"in t,xv=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Cv(t){switch(t){case lo:return"<BOM>";case uo:return"<DOC>";case fo:return"<FLOW_END>";case ho:return"<SCALAR>";default:return JSON.stringify(t)}}function Rv(t){switch(t){case lo:return"byte-order-mark";case uo:return"doc-mode";case fo:return"flow-error-end";case ho:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
118
|
`:case`\r
|
|
119
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
121
|
-
\r `),
|
|
122
|
-
`?!0:i==="\r"?this.buffer[
|
|
123
|
-
`:!1}charAt(
|
|
124
|
-
`||!
|
|
125
|
-
`||
|
|
126
|
-
`,this.pos),this.lineEndPos=
|
|
127
|
-
`,this.pos);if(
|
|
128
|
-
`,a)}
|
|
129
|
-
`:
|
|
130
|
-
`)break}default:break e}if(!
|
|
131
|
-
`,a)}while(
|
|
132
|
-
`;)
|
|
133
|
-
`&&a>=this.pos&&a+1+i>s)
|
|
134
|
-
`?(
|
|
135
|
-
`,a=this.buffer[
|
|
136
|
-
`){let o=this.continueScalar(
|
|
137
|
-
`?yield*this.pushCount(1):
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(
|
|
119
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}W.createScalarToken=co.createScalarToken;W.resolveAsScalar=co.resolveAsScalar;W.setScalarValue=co.setScalarValue;W.stringify=Sv.stringify;W.visit=Ev.visit;W.BOM=lo;W.DOCUMENT=uo;W.FLOW_END=fo;W.SCALAR=ho;W.isCollection=Pv;W.isScalar=xv;W.prettyToken=Cv;W.tokenType=Rv});var vo=w(Ul=>{"use strict";var mi=Lr();function le(t){switch(t){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var Gl=new Set("0123456789ABCDEFabcdef"),Av=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Mr=new Set(",[]{}"),_v=new Set(` ,[]{}
|
|
121
|
+
\r `),po=t=>!t||_v.has(t),mo=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,i=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,i=this.buffer[e];for(;i===" "||i===" ";)i=this.buffer[++e];return!i||i==="#"||i===`
|
|
122
|
+
`?!0:i==="\r"?this.buffer[e+1]===`
|
|
123
|
+
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let i=this.buffer[e];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+e];if(i==="\r"){let n=this.buffer[r+e+1];if(n===`
|
|
124
|
+
`||!n&&!this.atEnd)return e+r+1}return i===`
|
|
125
|
+
`||r>=this.indentNext||!i&&!this.atEnd?e+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&le(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
126
|
+
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===mi.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let i=e.length,r=e.indexOf("#");for(;r!==-1;){let a=e[r-1];if(a===" "||a===" "){i=r-1;break}else r=e.indexOf("#",r+1)}for(;;){let a=e[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-i),yield*this.pushNewline(),"stream"}return yield mi.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let i=this.peek(3);if((i==="---"||i==="...")&&le(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&&!le(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&le(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(e[i]){case"#":yield*this.pushCount(e.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(po),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,i,r=-1;do e=yield*this.pushNewline(),e>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(e+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&le(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield mi.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(po),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||le(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),i=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
|
|
127
|
+
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=r.indexOf(`
|
|
128
|
+
`,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let i=this.buffer[++e];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>le(i)||i==="#")}*parseBlockScalar(){let e=this.pos-1,i=0,r;e:for(let a=this.pos;r=this.buffer[a];++a)switch(r){case" ":i+=1;break;case`
|
|
129
|
+
`:e=a,i=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
|
+
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(e+1);if(a===-1)break;e=this.buffer.indexOf(`
|
|
131
|
+
`,a)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let n=e+1;for(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
132
|
+
`;)r=this.buffer[++n];e=n-1}else if(!this.blockScalarKeep)do{let a=e-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
+
`&&a>=this.pos&&a+1+i>s)e=a;else break}while(!0);return yield mi.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(le(a)||e&&Mr.has(a))break;i=r}else if(le(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
|
|
134
|
+
`?(r+=1,n=`
|
|
135
|
+
`,a=this.buffer[r+1]):i=r),a==="#"||e&&Mr.has(a))break;if(n===`
|
|
136
|
+
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(e&&Mr.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield mi.SCALAR,yield*this.pushToIndex(i+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,i){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(po),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(le(r)||i&&Mr.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,i=this.buffer[e];for(;!le(i)&&i!==">";)i=this.buffer[++e];return yield*this.pushToIndex(i===">"?e+1:e,!1)}else{let e=this.pos+1,i=this.buffer[e];for(;i;)if(Av.has(i))i=this.buffer[++e];else if(i==="%"&&Gl.has(this.buffer[e+1])&&Gl.has(this.buffer[e+2]))i=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
137
|
+
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||e&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(e){let i=this.pos,r=this.buffer[i];for(;!e(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Ul.Lexer=mo});var wo=w(Kl=>{"use strict";var go=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<e?i=a+1:r=a}if(this.lineStarts[i]===e)return{line:i+1,col:1};if(i===0)return{line:0,col:e};let n=this.lineStarts[i-1];return{line:i,col:e-n+1}}}};Kl.LineCounter=go});var No=w(eu=>{"use strict";var Tv=Wi("process"),Yl=Lr(),Iv=vo();function ze(t,e){for(let i=0;i<t.length;++i)if(t[i].type===e)return!0;return!1}function Xl(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Zl(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Fr(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function Rt(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Vr(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let i=0;i<e.length;++i)t.push(e[i])}function Ql(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!ze(e.start,"explicit-key-ind")&&!ze(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Zl(e.value)?e.value.end?Vr(e.value.end,e.sep):e.value.end=e.sep:Vr(e.start,e.sep),delete e.sep)}var yo=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Iv.Lexer,this.onNewLine=e}*parse(e,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,i))yield*this.next(r);i||(yield*this.end())}*next(e){if(this.source=e,Tv.env.LOG_TOKENS&&console.log("|",Yl.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let i=Yl.tokenType(e);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let r=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let i=e??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&Ql(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Xl(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Xl(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let i=Fr(this.peek(2)),r=Rt(i),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
140
|
-
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(
|
|
140
|
+
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let i=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Vr(n,i.start),n.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ze(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(Zl(i.key)&&!ze(i.sep,"newline")){let o=Rt(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(ze(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Rt(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?e.items.push({start:a,key:null,sep:[this.sourceToken]}):ze(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||i.value?(e.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!ze(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let i=e.items[e.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Vr(n,i.start),n.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=e.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;i.value||ze(i.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let i=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?e.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?e.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=Fr(r),a=Rt(n);Ql(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let i=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
142
|
-
`,i)+1}return{type: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=wa(t),n=Ci(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=wa(t),n=Ci(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())}}};Zf.Parser=gc});var rh=R(xn=>{"use strict";var eh=rc(),jb=Nn(),An=Sn(),Ob=is(),$b=M(),Hb=vc(),th=wc();function ih(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Hb.LineCounter||null,prettyErrors:t}}function Fb(e,t={}){let{lineCounter:i,prettyErrors:n}=ih(t),r=new th.Parser(i?.addNewLine),a=new eh.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(An.prettifyError(e,i)),s.warnings.forEach(An.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function nh(e,t={}){let{lineCounter:i,prettyErrors:n}=ih(t),r=new th.Parser(i?.addNewLine),a=new eh.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 An.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(An.prettifyError(e,i)),o.warnings.forEach(An.prettifyError(e,i))),o}function Db(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=nh(e,i);if(!r)return null;if(r.warnings.forEach(a=>Ob.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 Lb(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 $b.isDocument(e)&&!n?e.toString(i):new jb.Document(e,n,i).toString(i)}xn.parse=Db;xn.parseAllDocuments=Fb;xn.parseDocument=nh;xn.stringify=Lb});var ba=R(V=>{"use strict";var Mb=rc(),Bb=Nn(),qb=Ds(),yc=Sn(),Vb=rn(),xt=M(),Wb=Et(),zb=te(),Jb=Rt(),Gb=Pt(),Ub=va(),Kb=pc(),Yb=vc(),Xb=wc(),Na=rh(),ah=Zi();V.Composer=Mb.Composer;V.Document=Bb.Document;V.Schema=qb.Schema;V.YAMLError=yc.YAMLError;V.YAMLParseError=yc.YAMLParseError;V.YAMLWarning=yc.YAMLWarning;V.Alias=Vb.Alias;V.isAlias=xt.isAlias;V.isCollection=xt.isCollection;V.isDocument=xt.isDocument;V.isMap=xt.isMap;V.isNode=xt.isNode;V.isPair=xt.isPair;V.isScalar=xt.isScalar;V.isSeq=xt.isSeq;V.Pair=Wb.Pair;V.Scalar=zb.Scalar;V.YAMLMap=Jb.YAMLMap;V.YAMLSeq=Gb.YAMLSeq;V.CST=Ub;V.Lexer=Kb.Lexer;V.LineCounter=Yb.LineCounter;V.Parser=Xb.Parser;V.parse=Na.parse;V.parseAllDocuments=Na.parseAllDocuments;V.parseDocument=Na.parseDocument;V.stringify=Na.stringify;V.visit=ah.visit;V.visitAsync=ah.visitAsync});var ho=Lo(ba(),1);import{promises as lt}from"fs";import be from"path";import{createHash as tk}from"node:crypto";import{promises as Oe}from"node:fs";import Ee from"node:path";import{TextDecoder as ik}from"node:util";import Nc from"path";var Qb=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Zb=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function ek(e){return e.toLowerCase().startsWith(".env")}function Xe(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>ek(n))?"environment-file":i.some(n=>Zb.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>Qb.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function bc(e,t){let i=Xe(t);if(i)return i;let n=Nc.resolve(e.projectRoot,...t.split("/")),r=Nc.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===Nc.resolve(e.configFile)?"native-runtime":null}function Tt(e){return e!==0&&e!==0n&&e!=="0"}function se(e,t){return Tt(e.dev)&&Tt(t.dev)&&Tt(e.ino)&&Tt(t.ino)}function L(e,t){let i=Tt(e.dev)&&Tt(t.dev);if(i&&e.dev!==t.dev)return!1;let n=Tt(e.ino)&&Tt(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var Tn=1024*1024;function kc(e,t){let i=Ee.relative(e,t);return i===""||!Ee.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ee.sep}`)}function nk(e){let t=Ee.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})||Ee.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=Xe(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 rk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ak(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ka(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return se(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function oh(e){let t=await Oe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Oe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ok(e,t){let i=Ee.resolve(e),n=Ee.resolve(t);if(!kc(i,n))throw new Error("Native artifact path is outside its root");let r=[await oh(i)],a=i;for(let o of Ee.relative(i,n).split(Ee.sep).filter(Boolean)){a=Ee.join(a,o);let s=await oh(a);if(!kc(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function sh(e){for(let t of e){let i=await Oe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!ak(t,i)||await Oe.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function de(e){let t=nk(e.ref),i=rk(e.maxBytes??Tn),n=Ee.resolve(e.root,...t.split("/")),r=await ok(e.root,Ee.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await Oe.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 Oe.realpath(n);if(!kc(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Oe.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Oe.lstat(n),Oe.realpath(n)]);if(await sh(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!ka(a,c)||!ka(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let k=i+1-f,b=await s.read(p,0,Math.min(p.length,k),null);if(b.bytesRead===0)break;if(f+=b.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([s.stat(),Oe.lstat(n),Oe.realpath(n)]);if(await sh(r),!h.isFile()||h.isSymbolicLink()||g!==o||!ka(c,m)||!ka(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),N;try{N=new ik("utf-8",{fatal:!0}).decode(S)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:f,hash:tk("sha256").update(S).digest("hex"),text:N}}finally{await s.close()}}import{randomUUID as sk}from"crypto";import{promises as ce}from"fs";import $e from"path";function Ec(e,t){let i=$e.relative(e,t);return i===""||!$e.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${$e.sep}`)}function ck(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Sc(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return se(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ch(e){let t=await ce.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 ce.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function In(e){for(let t of e){let i=await ce.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!ck(t,i)||await ce.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function lk(e,t){let i=$e.resolve(e),n=$e.resolve(t);if(!Ec(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await ch(i)],a=$e.relative(i,n).split($e.sep).filter(Boolean),o=i;for(let s of a){await In(r),o=$e.join(o,s);try{await ce.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await ch(o);if(!Ec(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await In(r),r}async function uk(e){let t;try{t=await ce.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 dk(e,t,i={}){let n=$e.dirname(e),r=i.containedRoot?await lk(i.containedRoot,n):null;r||await ce.mkdir(n,{recursive:!0});let a=$e.join(n,`.${$e.basename(e)}.${sk()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await ce.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([ce.lstat(a),ce.realpath(a)]);if(await In(r),!c.isFile()||c.isSymbolicLink()||!Sc(s,c)||!Ec(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(),!Sc(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 In(r);let c=await ce.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Sc(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await ce.link(a,e),await ce.unlink(a)):await ce.rename(a,e),await uk(n)}catch(c){if(await o?.close(),!r)await ce.rm(a,{force:!0});else try{await In(r),await ce.rm(a,{force:!0})}catch{}throw c}}async function It(e,t,i={}){await dk(e,t,i)}async function Qe(e,t,i={}){await It(e,JSON.stringify(t,null,2)+`
|
|
143
|
-
|
|
144
|
-
#
|
|
145
|
-
#
|
|
146
|
-
#
|
|
147
|
-
# archive_confirmation: automatic | required`,"native.max_verify_failures":"# Maximum failed Verify outcomes allowed for one confirmed contract before Native stops the completion loop.","native.snapshot":"# Controls the auditable project scope and bounded work used by Native content snapshots.","native.snapshot.include":"# Selects the project-relative paths included in Native snapshots. Patterns use / and support *, **, and ?.","native.snapshot.exclude":"# Removes paths from the included scope. Exclusions are bound into each new change baseline.","native.snapshot.max_files":"# Bounds the number of files captured by one snapshot. Increase it for large monorepos.","native.snapshot.max_total_bytes":"# Bounds the total file content hashed by one snapshot. Content is streamed and does not depend on Git hashes.","native.snapshot.max_duration_ms":"# Bounds snapshot capture time in milliseconds. Increase it together with the byte budget on slower or larger repositories.",classic:"# Classic workflow settings. They do not change Native state or behavior.","classic.artifact_layout":`# Selects the Classic artifact layout. The default is docs; update preserves detected root-level legacy artifacts.
|
|
142
|
+
`,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Fr(e),r=Rt(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Fr(e),r=Rt(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};eu.Parser=yo});var au=w(gi=>{"use strict";var tu=ao(),jv=ci(),vi=di(),$v=ra(),Ov=P(),Hv=wo(),iu=No();function ru(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Hv.LineCounter||null,prettyErrors:e}}function Dv(t,e={}){let{lineCounter:i,prettyErrors:r}=ru(e),n=new iu.Parser(i?.addNewLine),a=new tu.Composer(e),o=Array.from(a.compose(n.parse(t)));if(r&&i)for(let s of o)s.errors.forEach(vi.prettifyError(t,i)),s.warnings.forEach(vi.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function nu(t,e={}){let{lineCounter:i,prettyErrors:r}=ru(e),n=new iu.Parser(i?.addNewLine),a=new tu.Composer(e),o=null;for(let s of a.compose(n.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new vi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(vi.prettifyError(t,i)),o.warnings.forEach(vi.prettifyError(t,i))),o}function Bv(t,e,i){let r;typeof e=="function"?r=e:i===void 0&&e&&typeof e=="object"&&(i=e);let n=nu(t,i);if(!n)return null;if(n.warnings.forEach(a=>$v.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function Lv(t,e,i){let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:i===void 0&&e&&(i=e),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(t===void 0){let{keepUndefined:n}=i??e??{};if(!n)return}return Ov.isDocument(t)&&!r?t.toString(i):new jv.Document(t,r,i).toString(i)}gi.parse=Bv;gi.parseAllDocuments=Dv;gi.parseDocument=nu;gi.stringify=Lv});var wi=w(C=>{"use strict";var Mv=ao(),Fv=ci(),Vv=La(),bo=di(),qv=Jt(),Je=P(),Wv=Fe(),zv=j(),Jv=qe(),Gv=We(),Uv=Lr(),Kv=vo(),Yv=wo(),Xv=No(),qr=au(),ou=Vt();C.Composer=Mv.Composer;C.Document=Fv.Document;C.Schema=Vv.Schema;C.YAMLError=bo.YAMLError;C.YAMLParseError=bo.YAMLParseError;C.YAMLWarning=bo.YAMLWarning;C.Alias=qv.Alias;C.isAlias=Je.isAlias;C.isCollection=Je.isCollection;C.isDocument=Je.isDocument;C.isMap=Je.isMap;C.isNode=Je.isNode;C.isPair=Je.isPair;C.isScalar=Je.isScalar;C.isSeq=Je.isSeq;C.Pair=Wv.Pair;C.Scalar=zv.Scalar;C.YAMLMap=Jv.YAMLMap;C.YAMLSeq=Gv.YAMLSeq;C.CST=Uv;C.Lexer=Kv.Lexer;C.LineCounter=Yv.LineCounter;C.Parser=Xv.Parser;C.parse=qr.parse;C.parseAllDocuments=qr.parseAllDocuments;C.parseDocument=qr.parseDocument;C.stringify=qr.stringify;C.visit=ou.visit;C.visitAsync=ou.visitAsync});import Pg from"path";var bi=zi(wi(),1);import zr from"path";var ki=64*1024,Jr=1024,Gr=64,So=5,Qv=[".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/**"],Zv=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],eg=[...Qv,...Zv].sort((t,e)=>t.localeCompare(e,"en"));var K={include:["**/*"],exclude:[...eg],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Wr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
|
|
143
|
+
# ambient_resume: true | false`,native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs and changes. Runtime data stays under .comet.","native.language":`# Artifact language used by Native workflow documents.
|
|
144
|
+
# language: en | zh-CN`,"native.clarification_mode":`# Controls how Native asks clarifying questions: batch asks every currently answerable question per round (default), sequential asks one at a time.
|
|
145
|
+
# clarification_mode: batch | sequential`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation.
|
|
146
|
+
# archive_confirmation: automatic | required`,"native.max_verify_failures":"# Maximum failed Verify outcomes allowed for one confirmed acceptance target before Native stops the completion loop.","native.snapshot":"# Controls the auditable project scope and bounded work used by Native content snapshots.","native.snapshot.include":"# Selects the project-relative paths included in Native snapshots. Patterns use / and support *, **, and ?.","native.snapshot.exclude":"# Removes paths from the included scope. Exclusions are bound into each new change baseline.","native.snapshot.max_files":"# Bounds the number of files captured by one snapshot. Increase it for large monorepos.","native.snapshot.max_total_bytes":"# Bounds the total file content hashed by one snapshot. Content is streamed and does not depend on Git hashes.","native.snapshot.max_duration_ms":"# Bounds snapshot capture time in milliseconds. Increase it together with the byte budget on slower or larger repositories.",classic:"# Classic workflow settings. They do not change Native state or behavior.","classic.artifact_layout":`# Selects the Classic artifact layout. The default is docs; update preserves detected root-level legacy artifacts.
|
|
148
147
|
# artifact_layout: legacy | docs`,"classic.language":`# Artifact language used by Classic workflow documents.
|
|
149
148
|
# language: en | zh-CN`,"classic.context_compression":`# Controls beta context compression for new Classic changes.
|
|
150
149
|
# context_compression: off | beta`,"classic.review_mode":`# Sets the default review depth for new Classic changes.
|
|
151
150
|
# review_mode: off | standard | thorough`,"classic.auto_transition":`# Automatically enters the next Classic phase after a phase passes.
|
|
152
151
|
# auto_transition: true | false`},"zh-CN":{schema:"# Comet 使用的配置格式版本,请勿修改此值。",default_workflow:"# `/comet` 默认进入的工作流;该值也必须出现在 workflows 中。",workflows:"# 此项目启用的工作流,可填写 native、classic 或同时启用两者。",ambient_resume:`# 是否启用只读的环境感知恢复探针,同时作用于 Native 和 Classic;设为 false 可关闭自动工作流恢复。
|
|
153
|
-
# ambient_resume: true | false`,native:"# Native 工作流配置,不会改变 Classic 的状态或行为。","native.artifact_root":"# Native
|
|
154
|
-
# 可选值:en | zh-CN`,"native.clarification_mode":`# Native
|
|
155
|
-
# 可选值:
|
|
156
|
-
# 可选值:automatic | required`,"native.max_verify_failures":"#
|
|
152
|
+
# ambient_resume: true | false`,native:"# Native 工作流配置,不会改变 Classic 的状态或行为。","native.artifact_root":"# Native 规格和 change 的存放根目录;运行时数据始终位于 .comet。","native.language":`# Native 工作流文档使用的产物语言。
|
|
153
|
+
# 可选值:en | zh-CN`,"native.clarification_mode":`# Native 提问澄清问题的方式:batch 每轮一次提出当前所有可回答的问题(默认),sequential 每轮只问一个。
|
|
154
|
+
# 可选值:batch | sequential`,"native.archive_confirmation":`# Native 归档检查成功后自动归档,或等待用户明确确认。
|
|
155
|
+
# 可选值:automatic | required`,"native.max_verify_failures":"# 同一个已确认验收目标最多允许的 Verify 失败次数;达到上限后停止完成循环。","native.snapshot":"# Native 内容快照使用的可审计项目范围与有界工作预算。","native.snapshot.include":"# Native 快照纳入的项目相对路径;模式使用 /,支持 *、** 和 ?。","native.snapshot.exclude":"# 从纳入范围中排除路径;新 change 会把排除策略绑定到 baseline。","native.snapshot.max_files":"# 单次快照最多捕获的文件数;大型 monorepo 可按需提高。","native.snapshot.max_total_bytes":"# 单次快照最多哈希的文件内容总字节数;内容采用流式读取,不依赖 Git hash。","native.snapshot.max_duration_ms":"# 单次快照的最长执行时间(毫秒);较慢或更大的仓库应与字节预算一并提高。",classic:"# Classic 工作流配置,不会改变 Native 的状态或行为。","classic.artifact_layout":`# Classic 产物布局;默认使用 docs,update 检测到根目录 legacy 产物时予以保留。
|
|
157
156
|
# 可选值:legacy | docs`,"classic.language":`# Classic 工作流文档使用的产物语言。
|
|
158
157
|
# 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
|
|
159
158
|
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
160
159
|
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
161
|
-
# 可选值:true | false`}};function
|
|
162
|
-
`)){let o=
|
|
163
|
-
`))i.push(`${s}${c}`)}i.push(a),/^[a-z_]+:/u.test(a)?(a.startsWith("native:")?
|
|
164
|
-
`)}function pk(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Ea.posix.isAbsolute(i)||Ea.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 Xt(e){let t=pk(e,"native.artifact_root");return t.length===0?".":t.join("/")}function dh(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 Pc(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||Ea.posix.isAbsolute(n)||Ea.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 _n(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function fh(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 Pa(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>Ca)throw new Error(`${t} exceeds ${Ca} 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>Ra)throw new Error(`${t} contains more than ${Ra} wildcard tokens`);return e}function lh(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=>Pa(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function Cc(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 mk(e){if(e===void 0)return{...me,include:[...me.include],exclude:[...me.exclude]};let t=_n(e,"native.snapshot");return{include:lh(t.include,"native.snapshot.include",me.include),exclude:lh(t.exclude,"native.snapshot.exclude",me.exclude),max_files:Cc(t.max_files,me.max_files,"native.snapshot.max_files"),max_total_bytes:Cc(t.max_total_bytes,me.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Cc(t.max_duration_ms,me.max_duration_ms,"native.snapshot.max_duration_ms")}}function vk(e){if(e===void 0)return;let t=_n(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=_n(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Xt(n),toArtifactRoot:Xt(r),stage:a,...o?{cleanup:o}:{}}}function gk(e,t={}){let i=_n(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??Rc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=vk(i.pending_root_move);return{artifact_root:Xt(n),language:fh(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:mk(i.snapshot),...s?{pending_root_move:s}:{}}}function wk(e){let t=_n(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:dh(t.artifact_layout),language:fh(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function yk(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Nk(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 Pi(e,t={}){let i=(0,jn.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=yk(r.ambient_resume),o=r.native===void 0?void 0:gk(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=r.classic===void 0?void 0:wk(r.classic),c=Nk(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function hh(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function ph(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,snapshot:e.native.snapshot,...e.native.pending_root_move?{pending_root_move:hh(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function Ri(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Hn(e,t){let i=ph(t),n=Pi((0,jn.stringify)(i)).config;if(!n)throw new Error("Unsupported Comet project schema");let r={...e,schema:n.schema,default_workflow:n.default_workflow,workflows:n.workflows,ambient_resume:n.ambient_resume};if(n.native){let a=Ri(e.native),o=Ri(a.snapshot),s={...a,artifact_root:n.native.artifact_root,language:n.native.language,clarification_mode:n.native.clarification_mode,archive_confirmation:n.native.archive_confirmation,max_verify_failures:n.native.max_verify_failures,snapshot:{...o,...n.native.snapshot}};if(n.native.pending_root_move){let c=Ri(a.pending_root_move),l=hh(n.native.pending_root_move),u=Ri(c.cleanup),d=Ri(l.cleanup);s.pending_root_move={...c,...l,...l.cleanup?{cleanup:{...u,...d}}:{}}}else delete s.pending_root_move;r.native=s}return n.classic&&(r.classic={...Ri(e.classic),artifact_layout:n.classic.artifact_layout,language:n.classic.language,context_compression:n.classic.context_compression,review_mode:n.classic.review_mode,auto_transition:n.classic.auto_transition}),r}function Aa(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Xt(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:Rc,snapshot:{...me,include:[...me.include],exclude:[...me.exclude]}}}}import{createHash as kk}from"crypto";import{promises as Ia}from"fs";import _t from"path";import{constants as xa,promises as Qt}from"fs";var He=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function Ac(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 Fn(e){return{dev:e.dev,ino:e.ino,birthtime:Ac(e)}}function Ta(e,t){let i=Fn(e),n=Fn(t);return se(i,n)?L(i,n):L(i,n)&&Ac(e)===Ac(t)&&mh(e)===mh(t)&&e.size===t.size}async function Zt(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 Qt.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new He("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new He("too-large",`${n} exceeds ${t} bytes`);let o=await Qt.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Fn(a)});let s=process.platform==="win32"?xa.O_RDONLY:xa.O_RDONLY|xa.O_NOFOLLOW|xa.O_NONBLOCK,c;try{c=await Qt.open(e,s)}catch(l){throw l.code==="ELOOP"?new He("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),Qt.lstat(e,{bigint:r}),Qt.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ta(a,l)||!Ta(a,u))throw new He("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Fn(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-p,{bytesRead:k}=await c.read(m,0,Math.min(m.length,N),null);if(k===0)break;if(p+=k,p>t)throw new He("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,g,S]=await Promise.all([c.stat({bigint:r}),Qt.lstat(e,{bigint:r}),Qt.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||S!==o||!Ta(a,h)||!Ta(a,g))throw new He("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:Fn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:S}}finally{await c.close()}}function bk(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function xc(e,t){let i=_t.relative(e,t);return i===""||!_t.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${_t.sep}`)}async function vh(e,t){let i=_t.resolve(e),n=await Ia.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Ia.realpath(i)}async function gh(e,t,i,n){let r=e;for(let a=0;a<i.length;a++){r=_t.join(r,i[a]);let o;try{o=await Ia.lstat(r)}catch(u){if(bk(u))return{exists:!1,kind:"missing"};throw u}let s=_t.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 Ia.realpath(r);if(!xc(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 Dn(e,t,i){let n=Pc(t,i.label),r=_t.resolve(e),a=await vh(r,i.label),o=n.split("/"),s=_t.resolve(r,...o);if(!xc(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await gh(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function ei(e,t,i,n){let r=await Dn(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 vh(r.projectRoot,n.label);return Zt(r.target,i,{...n,verify:async(o,s)=>{if(!xc(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await gh(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var Ln=".comet/config.yaml";function Tc(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function Sk(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Ic(e,t={}){return(await Mn(e,t)).document}async function wh(e){try{return(await ei(e,Ln,On,{label:Ln})).bytes}catch(t){if(Sk(t))return null;throw t}}function yh(e){return e?{exists:!0,sha256:kk("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function _a(e){return yh(await wh(e))}async function Mn(e,t={}){let i=await wh(e);return{document:i?Pi(i.toString("utf8"),t):null,identity:yh(i)}}var QT=16*1024;async function _c(e,t){if(!t)return;let i=await _a(e);if(!Tc(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{promises as ti}from"fs";import J from"path";import Pk from"os";var Oa=".comet/config.yaml";async function jc(e){try{return await ti.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ak(e){try{let t=await ti.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Bn(e,t){let i=J.relative(e,t);return i===""||!J.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${J.sep}`)}async function qn(e){let t=[],i=e;for(;!await jc(i);){let r=J.dirname(i);if(r===i)break;t.push(J.basename(i)),i=r}let n=await ti.realpath(i);return J.resolve(n,...t.reverse())}async function Nh(e){try{return(await ti.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Oc(e){let t=J.resolve(e);try{(await ti.stat(t)).isDirectory()||(t=J.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=J.resolve(Pk.homedir());for(;;){if(!(t===n&&i!==n)){let o=J.join(t,...Oa.split("/")),s=t===i||await Ak(o);if(await jc(o)&&s)return t}if(await jc(J.join(t,".git")))return t;let a=J.dirname(t);if(a===t)return i;t=a}}function $c(e){return Xt(e)}async function xk(e,t){let i=$c(t),n=J.resolve(e,...i.split("/")),r=await ti.realpath(e),a=await qn(n);if(!Bn(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function $a(e,t){let i=$c(t),n=await xk(e,i),r=J.join(n,"comet");if(await Nh(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([qn(n),qn(r)]);if(!Bn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:J.resolve(e),configFile:J.join(e,...Oa.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:J.join(r,"specs"),changesDir:J.join(r,"changes"),archiveDir:J.join(r,"archive"),runtimeDir:J.join(r,"runtime"),locksDir:J.join(r,"runtime","locks"),transactionsDir:J.join(r,"runtime","transactions")}}async function bh(e){let t=[e.specsDir,e.changesDir,e.archiveDir,e.locksDir,e.transactionsDir];await Promise.all(t.map(async i=>{await F(e.nativeRoot,i),await ti.mkdir(i,{recursive:!0})}))}function W(e,t){return Bn(J.resolve(e),J.resolve(t))}async function F(e,t){let i=J.resolve(e),n=J.resolve(t);if(!Bn(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await Nh(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([qn(i),qn(n)]);if(!Bn(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var Ha=me;var Fa=Pa;function kh(e="docs",t="en"){return Aa(e,t)}async function Ce(e){let t=(await Ic(e))?.config??null;return t?.native?t:null}async function Da(e){let t=await Ce(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 Sh(e,t,i={}){let n=await Mn(e,{allowPartialProject:!0}),r=Hn(n.document?.value??{},t),a=Tk.join(e,...Oa.split("/"));await It(a,$n(r,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await _c(e,n.identity)}})}import{promises as rS}from"fs";import aS from"path";import{AsyncLocalStorage as Ik}from"async_hooks";import{randomUUID as Rh}from"crypto";import{promises as Re}from"fs";import Ph from"os";import fe from"path";var Eh=16*1024,Ah=".coordinator",_k=5e3,Ch=new Ik,La=new Map;function jk(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function Ok(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 Hc(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return se(i,n)?L(i,n):L(i,n)&&e.size===t.size}function Fc(e,t){return Hc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function at(e){let t,i;try{let n=await Zt(e,Eh,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof He?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Eh} 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:Ok(JSON.parse(t.toString("utf8")),e),identity:xh(i)}}async function $k(e){return(await at(e))?.owner??null}function Th(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Ph.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Bk(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Hk(e,t){try{await Re.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Re.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Dc(e,t){let i=await at(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Fc(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Re.mkdir(t,{recursive:!0});let n=fe.join(t,`${fe.basename(e.file)}.${e.owner.id}.${Rh()}.removed`);try{await Re.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await at(n);if(!r||r.owner.id!==e.owner.id||!Hc(r.identity,e.identity))throw await Hk(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Re.rm(n,{force:!0}),"removed"}function Ih(e){return{id:Rh(),pid:process.pid,hostname:Ph.hostname(),createdAt:new Date().toISOString(),operation:e}}async function _h(e,t){let i;try{i=await Re.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await $k(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)+`
|
|
165
|
-
`,"utf8"),await i.sync(),xh(await i.stat({bigint:!0}))}finally{await i.close()}}async function Fk(e,t){let i=await F(e.nativeRoot,e.locksDir);await Re.mkdir(i,{recursive:!0});let n=await F(e.nativeRoot,fe.join(i,Ah));await Re.mkdir(n,{recursive:!0});let r=Ih(t),a=fe.join(n,`.${r.id}.tmp`),o=fe.join(n,`${r.id}.claim`);try{let s=await _h(a,r);await Re.rename(a,o);let c=await at(o);if(!c||!Hc(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 Re.rm(a,{force:!0})}}async function Dk(e){let t=fe.dirname(e.file),i=!1,n=fe.basename(e.file);for(let r of await Re.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=fe.join(t,r.name);if(fe.resolve(a)!==fe.resolve(e.file))try{let o=await at(a),s=Th(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Dc(o,t);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function jh(e){let t=await at(e.file);if(t){if(t.owner.id!==e.owner.id||!Fc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Dc(t,fe.dirname(e.file))}}async function Lk(e,t){let i=Date.now()+_k;for(;;){let n=await Fk(e,t);if(!await Dk(n))return n;if(await jh(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 Mk(e){let t=La.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return La.set(e,r),await t,()=>{i(),La.get(e)===r&&La.delete(e)}}async function Oh(e,t,i){let n=fe.resolve(e.locksDir),r=Ch.getStore();if(r?.has(n))return i();let a=await Mk(n);try{let o=await Lk(e,t),s=new Map(r??[]);return s.set(n,o),await Ch.run(s,async()=>{try{return await i()}finally{await jh(o)}})}finally{a()}}async function Ma(e,t,i){return Oh(e,`acquire ${t}`,async()=>{let n=await F(e.nativeRoot,e.locksDir);await Re.mkdir(n,{recursive:!0});let r=await F(e.nativeRoot,fe.join(n,jk(t))),a=Ih(i),o=await _h(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function Ba(e){await at(e.file)&&await Oh(e,`release ${fe.basename(e.file)}`,async()=>{let t=await at(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Fc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=fe.join(e.locksDir,Ah);await Dc(t,i)})}function Bk(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function $h(e){return Th(await at(e))}import st from"path";import{TextDecoder as Uk}from"util";import{createHash as qk}from"node:crypto";import{constants as qa,promises as Ne}from"node:fs";import Fe from"node:path";import{TextDecoder as Vk}from"node:util";function Wa(e,t){let i=Fe.relative(e,t);return i===""||!Fe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Fe.sep}`)}function Hh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Wk(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function zk(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Va(e,t){return L({...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 Lc(e,t){let i=await Ne.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ne.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Fh(e,t,i){let n=Fe.resolve(e),r=Fe.resolve(t);if(!Wa(n,r))throw new Error(`${i} is outside its managed root`);let a=[await Lc(n,i)],o=n;for(let s of Fe.relative(n,r).split(Fe.sep).filter(Boolean)){await ot(a,i),o=Fe.join(o,s);let c=await Lc(o,i);if(!Wa(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ot(a,i),a}async function ot(e,t){for(let i of e){let n=await Ne.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Wk(i,n)||await Ne.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function Jk(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 Ze(e){let t=Hh(e.maxBytes),i=Fe.resolve(e.file),n=await Fh(e.root,Fe.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>Lc(Fe.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ot(n,e.label);let a=await Ne.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=zk(a),s=await Ne.realpath(i);if(!Wa(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Wa(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?qa.O_RDONLY:qa.O_RDONLY|qa.O_NOFOLLOW|qa.O_NONBLOCK,l=await Ne.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Ne.lstat(i),Ne.realpath(i)]);if(await ot(n,e.label),await ot(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Va(o,u)||!Va(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Jk(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([l.stat(),Ne.lstat(i),Ne.realpath(i)]);if(await ot(n,e.label),await ot(r,e.label),!h.isFile()||h.isSymbolicLink()||g!==s||!Va(o,m)||!Va(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:qk("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Dh(e){let t=await Ze(e),i;try{i=new Vk("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 Ai(e){let t=await Fh(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await Ne.readdir(e.directory,{withFileTypes:!0});else{let n=Hh(e.maxEntries);i=[];let r=await Ne.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 ot(t,e.label),{entries:i,verify:()=>ot(t,e.label)}}var Kk=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Yk=new Set(["id","type","source","target","staged","backup"]),Xk=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Qk=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Bh=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Zk=256*1024,VI=1024*1024,WI=16*1024;var zI=64*1024*1024;var eS=new Uk("utf-8",{fatal:!0});function Ja(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ga(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 qh(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Mc(e,t){if(typeof e!="string"||e.length===0||st.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function za(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Lh(e,t){if(Mc(e,t),e.includes("\\")||e!==st.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 tS(e,t){let i=Ja(e,`transaction operations[${t}]`);if(Ga(i,Yk,`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`);Mc(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&Mc(i[n],`transaction operation ${i.id} ${n}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function Vh(e){let t=Ja(e,"Native Archive transaction journal");if(Ga(t,Xk,"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"||!Bh.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(!qh(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(za(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=Ja(s,`Archive transaction operations[${c}]`);if(Ga(l,Qk,`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`);Lh(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Lh(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&za(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(za(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`);za(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 iS(e){let t=Ja(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Vh(t);if(Ga(t,Kk,"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"||!Bh.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!st.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!st.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(!qh(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(tS),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 nS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return st.join(e.transactionsDir,t)}function Wh(e,t){let i=nS(e,t);return{directory:i,journal:st.join(i,"transaction.json"),events:st.join(i,"events.jsonl"),staged:st.join(i,"staged"),backups:st.join(i,"backups")}}async function Bc(e,t){let i=Wh(e,t);return await Promise.all(Object.values(i).map(n=>F(e.nativeRoot,n))),i}async function qc(e,t,i={}){let n=await Bc(e,t),r=await Ze({root:e.nativeRoot,file:n.journal,maxBytes:Zk,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(eS.decode(r.bytes)),o=iS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function oS(e,t){let i;try{i=await rS.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 qc(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function sS(e,t){let i=Date.now()+5e3,n=aS.join(e.locksDir,"root-move.lock");for(;;)try{return await Ma(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await $h(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 et(e,t,i,n){let r=await sS(e,t);try{if(await Da(e.projectRoot),await oS(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Ba(r)}}import{createHash as Qa}from"crypto";import{spawn as ep}from"node:child_process";import{promises as X}from"fs";import H from"path";import{createHash as zh}from"crypto";import{createReadStream as cS}from"fs";async function Vc(e){let t=zh("sha256");for await(let i of cS(e))t.update(i);return t.digest("hex")}function U(e){return zh("sha256").update(e).digest("hex")}var Ua={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Kc=1e3,lS=8*1024*1024,uS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dS=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),fS=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),hS=new Set(["schema","include","exclude","hash"]),pS=new Set(["provider","gitSelection","physicalSelection","projection"]),mS=new Set(["provider","selection"]),vS=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),gS=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),wS=new Set(["schema","status","before","after"]),yS=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),NS=new Set(["path","hash","size","type","gitObjectId"]),bS=new Set(["path","size","type","reason"]),kS=new Set(["ref","hash","count"]),SS=new Set(["change-created","legacy-migration","explicit"]),ES=new Set(["file","directory","other"]),CS=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"]),Za=/^[a-f0-9]{64}$/u,tp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,RS=new Set(["EACCES","EPERM"]),ji=64*1024,Gc=64*1024,PS=6e4,AS=1e3,xS=2,Yc={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},TS={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function ip(e){let t=e.deadlineMs??PS;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 De(e){return Math.max(0,e.deadlineAt-Date.now())}function _(e){return De(e)>=1}function Wc(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 Ii(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function IS(e){let t={...TS,...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 _S(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&&H.win32.isAbsolute(n)?H.win32.resolve(n):"C:\\Windows",a=H.win32.join(r,"System32","taskkill.exe");if(!H.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,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=ep(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),AS),u.unref()}catch{d(!1)}});for(let s=0;s<xS;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 Xc(e,t,i,n){let r=De(e);if(r<1)throw Wc();let a=e.gitProcess,o=ep(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 u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=_S(o,a).then(()=>({error:null}),p=>({error:p}))},r);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let m=await l;throw m?.error?Wc(m.error):Wc()}return{code:p,spawnError:s}});return{child:o,completion:f}}function np(e){let t={...Yc,...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 Ka(e,t,i,n=Gc){let{child:r,completion:a}=Xc(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;r.stdout.on("data",p=>{let m=Math.max(0,n-l);m>0&&o.push(Buffer.from(p).subarray(0,m)),l+=p.byteLength,l>n&&(u=!0)}),r.stderr.on("data",p=>{if(c>=ji)return;let m=ji-c,h=Buffer.from(p).subarray(0,m);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function zc(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Wn(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}=Xc(e,t,i,n.stdin!==void 0),c=[],l=Qa("sha256"),u=[],d=0,f=0,p=0,m=0,h=Buffer.alloc(0),g=!1,S=!1,N=!1,k=b=>{let C=0;for(;C<b.byteLength;){let y=b.indexOf(0,C),w=y<0?b.byteLength:y,v=b.subarray(C,w);if(!g&&v.byteLength>0&&(h.byteLength+v.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),g=!0,S=!0):h=Buffer.concat([h,v])),y<0)break;m+=1,h.byteLength===0&&!g&&(N=!0);let E=h.byteLength+1;!g&&m<=n.maxRecords&&p+E<=n.maxBytes?(c.push(h),p+=E):S=!0,h=Buffer.alloc(0),g=!1,C=y+1}};o.stdout.on("data",b=>{l.update(b),f+=b.byteLength,f>n.maxBytes&&(S=!0);let C=n.outputChunkBytes;if(C===void 0){k(b);return}for(let y=0;y<b.byteLength;y+=C)k(b.subarray(y,Math.min(b.byteLength,y+C)))}),o.stderr.on("data",b=>{if(d>=ji)return;let C=ji-d,y=Buffer.from(b).subarray(0,C);u.push(y),d+=y.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:b,spawnError:C})=>{let y=n.acceptedExitCodes??[0];if(b!==null&&y.includes(b)&&C===null&&!N&&h.byteLength===0&&!g){r({records:c,digest:l.digest("hex"),overflow:S,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${C?`: ${C.message}`:N||h.byteLength>0||g?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function Ya(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 jS(e,t,i){if(i.length===0)return new Set;let n=await Wn(e,t,["check-ignore","--no-index","-z","--stdin"],{...Yc,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(n.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(n.records.map(r=>{let a=Ya(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function OS(e,t,i){let{child:n,completion:r}=Xc(e,t,i,!1),a=[],o=0,s=!1;n.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),n.stderr.on("data",u=>{if(o>=ji)return;let d=ji-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.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 _i(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||H.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||H.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function $S(e,t){return e.map(i=>{let n=_i(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function HS(e){let t=H.resolve(e);for(;;){try{return await X.lstat(H.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=H.dirname(t);if(i===t)return!1;t=i}}async function rp(e,t,i,n={}){let r=H.resolve(t.projectRoot),a=H.join(r,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.configFile,a].map(f=>{let p=H.relative(r,H.resolve(f)).replaceAll("\\","/"),m=_i(p);if(m===null)throw new Error("Native Git snapshot exclusion escaped the project root");return m}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},l=await Wn(e,r,["ls-files","--stage","-z",...s],c);await n.afterStageBefore?.();let u=await Wn(e,r,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await n.afterCombined?.();let d=await Wn(e,r,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function ap(e){return{stageBefore:zc(e.stagedBefore),combined:zc(e.combined),stageAfter:zc(e.stagedAfter)}}async function op(e,t,i=Yc,n={}){let r=H.resolve(t.projectRoot);if(!await HS(r))return null;let a;try{a=await Ka(e,r,["rev-parse","--is-inside-work-tree"])}catch(N){throw Ii(N)?N:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:N})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await rp(e,t,i,n)}catch(N){throw Ii(N)?N:new Error("Native Git snapshot provider failed after repository detection",{cause:N})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=N=>{for(let k of N){let b=Ya(k),C=b.indexOf(" ");if(C<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let y=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(b.slice(0,C))?.groups;if(!y)throw new Error("Native Git snapshot provider returned a malformed staged header");let w=_i(b.slice(C+1));if(w===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(w),y.stage==="0"&&d.set(w,y.objectId),y.mode==="160000"&&y.stage==="0"&&f.add(w)}};p(s.records),p(l.records);let m=c.records.map(Ya),h=$S(m,"combined"),g=new Set(h.filter(N=>!u.has(N))),S=new Set(h.filter((N,k)=>!u.has(N)&&m[k].endsWith("/")));for(let N of f)S.delete(N);return{tracked:u,trackedObjectIds:d,untracked:g,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:ap(o)}}function Ot(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Jh(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function FS(e,t){return!Ot(e.stageBefore,e.stageAfter)||!Ot(e.stageAfter,t.stageBefore)||!Ot(e.combined,t.combined)||!Ot(t.stageBefore,t.stageAfter)}async function sp(e,t,i,n,r){let a;try{a=await rp(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw Ii(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=ap(a),c=Jh(o)||Jh(s),l=FS(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:U(`comet.native.git-selection-overflow.v2
|
|
166
|
-
|
|
167
|
-
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):U(`comet.native.physical-selection.v1
|
|
168
|
-
|
|
169
|
-
`)}function VS(e,t){return U(`comet.native.snapshot-policy.v1
|
|
170
|
-
${
|
|
171
|
-
${
|
|
172
|
-
${Buffer.byteLength(n)}:${n}`)}function Uc(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Xa(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Uc(i))return e.splice(t,1),i}return null}function jt(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return se(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function JS(e,t,i,n){if(!_(n))return{status:"budget-exhausted"};let r;try{r=await X.open(e,"r")}catch(c){if(!_(n))return{status:"budget-exhausted"};throw c}if(!_(n))return await r.close(),{status:"budget-exhausted"};let a=Qa("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()||!jt(i,c))return{status:"changed"};for(;;){if(!_(n))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await r.read(o,0,Math.min(o.length,l),null);if(!_(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!_(n))return{status:"budget-exhausted"};let d=await r.stat();return _(n)?!d.isFile()||!jt(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await r.close()}}function Pe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ae(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function Ti(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function tt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function fp(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=H.posix.normalize(e);if(i!==e||H.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function GS(e,t){let i=Pe(e,`Native snapshot entry ${t}`);Ae(i,NS,`Native snapshot entry ${t}`);let n=fp(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Za.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:tt(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!tp.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function US(e,t){let i=Pe(e,`Native snapshot omission ${t}`);if(Ae(i,bS,`Native snapshot omission ${t}`),!ES.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!CS.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:fp(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:tt(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function KS(e){let t=Pe(e,"Native snapshot omission overflow");if(Ae(t,kS,"Native snapshot omission overflow"),typeof t.hash!="string"||!Za.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:Ti(t.count,"Native snapshot omission overflow count")}}function xi(e,t){let i=Pe(e,t);if(Ae(i,gS,t),typeof i.hash!="string"||!Za.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=tt(i.recordCount,`${t} recordCount`),r=tt(i.storedRecordCount,`${t} storedRecordCount`),a=tt(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 Qh(e){let t=Pe(e,"Native Git selection evidence");if(Ae(t,vS,"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=xi(t.stageBefore,"Native Git selection stageBefore"),n=xi(t.combined,"Native Git selection combined"),r=xi(t.stageAfter,"Native Git selection stageAfter"),a=xi(t.finalStageBefore,"Native Git selection finalStageBefore"),o=xi(t.finalCombined,"Native Git selection finalCombined"),s=xi(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!Ot(i,r)||!Ot(r,a)||!Ot(n,o)||!Ot(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Zh(e,t){let i=Pe(e,t);if(Ae(i,yS,t),typeof i.hash!="string"||!Za.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=tt(i.visitedNodeCount,`${t} visitedNodeCount`),r=tt(i.recordCount,`${t} recordCount`),a=tt(i.storedRecordCount,`${t} storedRecordCount`),o=tt(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 YS(e){let t=Pe(e,"Native physical selection evidence");if(Ae(t,wS,"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=Zh(t.before,"Native physical selection before"),n=Zh(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!cp(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 ct(e){let t=Pe(e,"Native content snapshot manifest");if(Ae(t,dS,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!SS.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let y=Pe(t.capture,"Native content snapshot capture");if(Ae(y,pS,"Native content snapshot capture"),y.provider!=="git"&&y.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let w=y.gitSelection===void 0?void 0:Qh(y.gitSelection),v=y.physicalSelection===void 0?void 0:YS(y.physicalSelection),E=null;if(y.projection!==void 0){let I=Pe(y.projection,"Native content snapshot projection");if(Ae(I,mS,"Native content snapshot projection"),I.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...I.selection===void 0?{}:{selection:Qh(I.selection)}}}if(y.provider==="git"){if(v||E)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...w?{gitSelection:w}:{}}}else{if(w)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(v&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");i=E?{provider:"physical-tree",projection:E}:{provider:"physical-tree",...v?{physicalSelection:v}:{}}}}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=Pe(t.limits,"Native content snapshot limits");Ae(n,fS,"Native content snapshot limits");let r={maxFiles:Ti(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Ti(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Ti(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Ti(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:Ti(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let y=Pe(t.policy,"Native snapshot policy");if(Ae(y,hS,"Native snapshot policy"),y.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(y.include)||!Array.isArray(y.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=dp({include:y.include,exclude:y.exclude,hash:y.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(GS),s=t.omitted.map(US),c=tt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:KS(t.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(y=>y.size>r.maxFileBytes)||o.reduce((y,w)=>y+w.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(y=>y.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Kc||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(y=>y.reason==="git-enumeration-limit"),f=s.filter(y=>y.reason==="git-selection-changed");for(let y of[...d,...f])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.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!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let g=s.filter(y=>y.reason==="physical-enumeration-limit"),S=s.filter(y=>y.reason==="physical-selection-changed");for(let y of[...g,...S])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(g.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=i?.physicalSelection,k=N?.status==="overflow"||N?.status==="overflow-and-changed",b=N?.status==="changed"||N?.status==="overflow-and-changed";if(k!==(g.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(b!==(S.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let C={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(Qc(C)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return C}async function hp(e,t,i={}){let n=ct(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=H.resolve(e.projectRoot),a=ip(i),o=np(i.gitSelectionLimits),s=await op(a,e,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set(lp(s).filter(v=>Vn(e,v))),l=[...s.gitlinks].filter(v=>c.has(v)),u=[...s.nestedRepositories].filter(v=>Vn(e,v)),d=(v,E)=>E.some(I=>v===I||v.startsWith(`${I}/`)),f=v=>d(v,l),p=v=>d(v,u),m=[...n.entries.map(v=>v.path),...n.omitted.flatMap(v=>v.type==="directory"?[v.path,`${v.path}/`]:[v.path])].filter(v=>!c.has(v)&&!f(v)&&!p(v)),h=await jS(a,r,m),g=n.entries.filter(v=>!f(v.path)&&!p(v.path)&&Vn(e,v.path)&&(c.has(v.path)||!h.has(v.path)));await sp(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let S=[...s.omissions];for(let v of l)S.push({path:v,size:null,type:"directory",reason:"legacy-gitlink-boundary"});g.sort((v,E)=>v.path.localeCompare(E.path,"en"));let N=n.omitted.filter(v=>f(v.path)||p(v.path)||!Vn(e,v.path)?!1:h.has(v.path)?c.has(v.path)||[...c].some(E=>E.startsWith(`${v.path}/`)):!0);for(let v of S)N.some(E=>E.path===v.path&&E.reason===v.reason)||N.push(v);N.sort((v,E)=>v.path.localeCompare(E.path,"en"));let k=n.omissionOverflow?.count??0,b=n.omissionOverflow?.hash??U("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,b=zn(b,"git-selection",{source:"git-selection",...s.overflow}));let C=v=>{k+=1,b=zn(b,"omission",v)};for(;N.length>Kc;){let v=Xa(N);if(v===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");C(v)}let y=()=>({...n,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:N.length+k===0,entries:g,omitted:N,omittedCount:N.length+k,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:k}}:{}}),w=y();for(;Qc(w)>n.limits.maxManifestBytes;){let v=Xa(N);if(v===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");C(v),w=y()}return ct(w)}function pp(e,t){if(!uS.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=H.join(e.changesDir,t);if(!W(e.changesDir,i))throw new Error("Native change path escaped");return H.join(i,"runtime","baseline-manifest.json")}async function Zc(e,t={}){let i={maxFiles:t.limits?.maxFiles??Ua.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Ua.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Ua.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Ua.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=dp(t.policy),r=ip({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=np(t.gitSelectionLimits),o=IS(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=H.resolve(e.projectRoot),c=await X.realpath(s),l=H.resolve(e.nativeRoot),u=await X.realpath(l),d=H.resolve(e.configFile),f=H.join(s,".comet","current-change.json"),p=qS(s,t.denylist??[]),m=[],h=[],g=new Map,S=new Map,N=0,k=0,b=U("comet.native.snapshot-omission-overflow.v1"),C=0,y=!1,w=null,v=x=>{k+=1,b=zn(b,"omission",x)},E=x=>{if(N+=1,h.length<Kc){h.push(x);return}if(Uc(x)){let A=Xa(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");v(A),h.push(x);return}v(x)},I=x=>{N+=x.count,k+=x.count,b=zn(b,"git-selection",{source:"git-selection",...x})},G=x=>{k+=1,b=zn(b,"manifest-entry",{reason:"manifest-size",entry:x})},q=async(x,A)=>{m.push(x),C+=x.size,g.set(x.path,A),y||(y=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(x.path))},z=(x,A)=>{let T=m.findIndex(Y=>Y.path===x);if(T<0)return;let[O]=m.splice(T,1);C-=O.size,g.delete(x),E(A)},K=async(x,A,T,O)=>{if(!T.isFile()||T.isSymbolicLink()||!_(r))return;let Y;try{Y=await X.realpath(x)}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;E({path:A,size:T.size,type:"file",reason:ie(P)?"changed-during-read":"unreadable"});return}if(!_(r)||!W(c,Y)||$t(u,Y))return;if(m.length>=i.maxFiles){E({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){E({path:A,size:T.size,type:"file",reason:"file-size"});return}if(C+T.size>i.maxTotalBytes){E({path:A,size:T.size,type:"file",reason:"total-size"});return}let B,j,Q;try{if(B=await JS(Y,T.size,T,r),B.status==="budget-exhausted"||!_(r))return;if(B.status==="changed"){E({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!_(r)||(Q=await X.realpath(x),!_(r)))return;j=await X.lstat(x)}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;E({path:A,size:T.size,type:"file",reason:ie(P)?"changed-during-read":"unreadable"});return}if(_(r)){if(B.bytes!==T.size||Q!==Y||!jt(T,B.finalStat)||!jt(B.finalStat,j)||!j.isFile()||j.isSymbolicLink()||j.size!==T.size||j.mtimeMs!==T.mtimeMs||j.ctimeMs!==T.ctimeMs){E({path:A,size:j.isFile()?j.size:null,type:j.isFile()?"file":"other",reason:"changed-during-read"});return}_(r)&&await q({path:A,hash:B.hash,size:j.size,type:"file",...O===void 0?{}:{gitObjectId:O}},{kind:"file",target:x,realTarget:Y,stat:j})}},Ge=async(x,A,T)=>{if(!_(r))return;let O,Y,B;try{if(O=await X.readlink(x,{encoding:"buffer"}),!_(r)||(B=await X.lstat(x),!_(r)))return;Y=await X.readlink(x,{encoding:"buffer"})}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;E({path:A,size:null,type:"other",reason:ie(P)?"changed-during-read":"unreadable"});return}if(!_(r))return;if(!B.isSymbolicLink()||!jt(T,B)||B.mtimeMs!==T.mtimeMs||B.ctimeMs!==T.ctimeMs||!O.equals(Y)){E({path:A,size:null,type:"other",reason:"changed-during-read"});return}let j=O.byteLength;if(m.length>=i.maxFiles){E({path:A,size:j,type:"other",reason:"file-count"});return}if(j>i.maxFileBytes){E({path:A,size:j,type:"other",reason:"file-size"});return}if(C+j>i.maxTotalBytes){E({path:A,size:j,type:"other",reason:"total-size"});return}let Q=Qa("sha256").update("symlink\0").update(O).digest("hex");_(r)&&await q({path:A,hash:Q,size:j,type:"file"},{kind:"symlink",target:x,rawTarget:O,stat:B})},Ue=async()=>{for(let[x,A]of[...g]){if(!_(r))return;if(A.kind==="file"){let j,Q;try{if(j=await X.realpath(A.target),!_(r))return;Q=await X.lstat(A.target)}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;z(x,{path:x,size:null,type:"file",reason:ne(P)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(j!==A.realTarget||!Q.isFile()||Q.isSymbolicLink()||!jt(A.stat,Q)||Q.size!==A.stat.size||Q.mtimeMs!==A.stat.mtimeMs||Q.ctimeMs!==A.stat.ctimeMs)&&z(x,{path:x,size:Q.isFile()?Q.size:null,type:Q.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let j,Q;try{if(j=await X.lstat(A.target),!_(r))return;Q=await X.readlink(A.target,{encoding:"buffer"})}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;z(x,{path:x,size:null,type:"other",reason:ne(P)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(!j.isSymbolicLink()||!jt(A.stat,j)||j.mtimeMs!==A.stat.mtimeMs||j.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(Q))&&z(x,{path:x,size:null,type:"other",reason:"changed-during-read"});continue}let T,O;try{if(T=await X.realpath(A.target),!_(r))return;O=await X.lstat(A.target)}catch{if(!_(r))return;z(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;if(!(T===A.realTarget&&O.isDirectory()&&!O.isSymbolicLink()&&jt(A.stat,O)&&W(c,T)&&!$t(u,T))){z(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"});continue}let B;try{if(!_(r))return;B=await Kh(r,T)}catch(j){if(Ii(j))throw j;z(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;B.dirty?z(x,{path:x,size:null,type:"directory",reason:"gitlink-dirty"}):B.hash!==A.hash&&z(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"})}for(let[x,A]of S){if(!_(r))return;try{let T=await X.lstat(A);if(!_(r))return;E({path:x,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!_(r))return;if(ie(T))continue;if(!ne(T))throw T;E({path:x,size:null,type:"file",reason:"unreadable"})}}},we=await op(r,e,a,t.gitSelectionHooks);if(we===null){let x=await Gh({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let O of x.records){if(O.type!=="file"&&O.type!=="symlink"||g.has(O.path))continue;if(De(r)<1)break;if(!Xh(n,O.path,r))continue;if(De(r)<1)break;let Y=H.resolve(s,...O.path.split("/")),B;try{B=await X.lstat(Y)}catch(j){if(!_(r))break;if(!ne(j)&&!ie(j))throw j;E({path:O.path,size:null,type:"file",reason:ie(j)?"changed-during-read":"unreadable"});continue}if(De(r)<1)break;if(O.type==="symlink"&&B.isSymbolicLink()){if(await Ge(Y,O.path,B),De(r)<1)break;continue}if(O.type!=="file"||!B.isFile()||B.isSymbolicLink()){E({path:O.path,size:B.isFile()?B.size:null,type:B.isDirectory()?"directory":B.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await K(Y,O.path,B),De(r)<1)break}De(r)>=1&&await Ue();let A=await Gh({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),T=MS(x.evidence,A.evidence);w=T.evidence;for(let O of[...x.omissions,...A.omissions,...T.omissions])h.some(Y=>Y.path===O.path&&Y.reason===O.reason)||E(O)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let x=t.incrementalBaseline,A=new Map,T=!1;if(x){let P=ct(x);for(let Z of P.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);T=A.size>0}let O=new Set,Y=!0;try{let P=await Wn(r,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(P.overflow)T=!1,Y=!1,A.clear();else for(let Z of P.records){let ee=Ya(Z),ue=ee.indexOf(" "),oe=ue<0?null:_i(ee.slice(ue+1));if(ue!==1||oe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ee[0]!=="H"&&O.add(oe)}}catch(P){if(Ii(P))throw P;T=!1,Y=!1,A.clear()}let B=new Set;try{let P=await Ka(r,s,["ls-files","--modified","-z"],Gc);for(let Z of P.toString("utf8").split("\0")){let ee=_i(Z);ee!==null&&B.add(ee)}}catch{T=!1,Y=!1,A.clear()}let j=new Set,Q=new Set;for(let P of lp(we)){if(g.has(P)||!Vn(e,P))continue;if(De(r)<1)break;if(!Xh(n,P,r))continue;if(De(r)<1)break;let Z=H.resolve(s,...P.split("/"));if(Z===d||Z===f||p.some(ye=>$t(ye,Z)))continue;if(we.gitlinks.has(P)){if(m.length>=i.maxFiles){E({path:P,size:0,type:"file",reason:"file-count"});continue}let ye,br;try{[ye,br]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(br.isSymbolicLink()||!br.isDirectory()||!W(c,ye)||$t(u,ye)){E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let pi=await Kh(r,ye);if(pi.dirty){E({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await q({path:P,hash:pi.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:ye,stat:br,hash:pi.hash})}catch(pi){if(Ii(pi))throw pi;E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ee;try{ee=await X.lstat(Z)}catch(ye){if(ie(ye)&&we.tracked.has(P)){S.set(P,Z);continue}if(!ne(ye)&&!ie(ye))throw ye;E({path:P,size:null,type:"file",reason:ie(ye)?"changed-during-read":"unreadable"});continue}if(ee.isSymbolicLink()){await Ge(Z,P,ee);continue}if(!ee.isFile()){we.nestedRepositories.has(P)||E({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let ue=we.trackedObjectIds.get(P),oe=ue?A.get(P):void 0;if(T&&oe?.gitObjectId!==void 0&&oe.gitObjectId===ue&&!O.has(P)&&!B.has(P)){if(m.length>=i.maxFiles){E({path:P,size:oe.size,type:"file",reason:"file-count"});continue}if(oe.size>i.maxFileBytes){E({path:P,size:oe.size,type:"file",reason:"file-size"});continue}if(C+oe.size>i.maxTotalBytes){E({path:P,size:oe.size,type:"file",reason:"total-size"});continue}m.push({...oe}),C+=oe.size,j.add(P);continue}let mu=Y&&!O.has(P)&&!B.has(P)?ue:void 0;await K(Z,P,ee,mu),mu!==void 0&&Q.add(P)}if(await Ue(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await sp(r,e,a,we,t.gitSelectionHooks?.outputChunkBytes),j.size>0||T&&Q.size>0){let P=await Ka(r,s,["ls-files","--modified","-z"],Gc),Z=new Set;for(let ee of P.toString("utf8").split("\0")){let ue=_i(ee);ue!==null&&Z.add(ue)}for(let ee of j){if(!Z.has(ee))continue;let ue=m.find(oe=>oe.path===ee);z(ee,{path:ee,size:ue?.size??null,type:"file",reason:"changed-during-read"})}for(let ee of Q){if(!Z.has(ee))continue;let ue=m.find(oe=>oe.path===ee);ue&&delete ue.gitObjectId}}for(let P of we.omissions)E(P);we.overflow&&I(we.overflow)}m.sort((x,A)=>x.path.localeCompare(A.path,"en")),h.sort((x,A)=>x.path.localeCompare(A.path,"en"));let wg=we===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...we.evidence?{gitSelection:we.evidence}:{}},pu=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:wg,createdAt:(t.now??new Date).toISOString(),complete:N===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:N,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:k}}:{}}),Do=pu();for(;Qc(Do)>i.maxManifestBytes;){if(h.filter(A=>!Uc(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let O=Xa(h);if(O===null)break;v(O)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))N+=1,G(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Do=pu()}return Do}async function el(e,t,i={}){let r=(await Ce(e.projectRoot))?.native.snapshot??Ha;return Zc(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 mp(e,t,i){let n=pp(e,t);await F(e.nativeRoot,n),await Qe(n,ct(i))}async function eo(e,t){let i=pp(e,t);await F(e.nativeRoot,i);try{let n=await Dh({root:e.nativeRoot,file:i,maxBytes:lS,label:"Native baseline snapshot manifest"});return ct(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as hE}from"crypto";import rl from"path";var xe=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{constants as to,promises as Le}from"node:fs";import Me from"node:path";import{TextDecoder as cE}from"node:util";import rE from"path";var iE=Lo(ba(),1);var vp=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Gn(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 Jn(e,t){let i=Gn(e,t);if(rE.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 aE(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=Gn(e,"run_id"),i=Gn(e,"skill"),n=Gn(e,"skill_version"),r=Gn(e,"skill_hash"),a=Jn(e,"pending_ref"),o=Jn(e,"trajectory_ref"),s=Jn(e,"context_ref"),c=Jn(e,"artifacts_ref"),l=Jn(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<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:vp(e,"current_step"),iteration:u,pending:vp(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:aE(e)}}var mj=256*1024;var oE=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function sE(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 tl(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=>!oE.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 sE(t)}var Oi={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 no(e,t){let i=Me.relative(e,t);return i===""||!Me.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Me.sep}`)}function lE(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function io(e,t){return L({...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 uE(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ro(e,t,i){let n=xe[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=Me.resolve(e),a=Me.resolve(r,...n.split("/"));if(!no(r,a))throw new Error("Native Run path must stay inside its change");return a}async function wp(e){let t=await Le.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function dE(e,t){let i=Me.resolve(e),n=Me.resolve(t);if(!no(i,n))throw new Error("Native Run path is outside its change");let r=[await wp(i)],a=i;for(let o of Me.relative(i,n).split(Me.sep).filter(Boolean)){a=Me.join(a,o);let s;try{s=await wp(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!no(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function yp(e){for(let t of e){let i=await Le.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!uE(t,i)||await Le.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function fE(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 ao(e,t,i,n,r){let a=await dE(e,Me.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await Le.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}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=lE(o),c=await Le.realpath(t);if(!no(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?to.O_RDONLY:to.O_RDONLY|to.O_NOFOLLOW|to.O_NONBLOCK,u;try{u=await Le.open(t,l)}catch(d){throw new Error(`${n} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),Le.lstat(t),Le.realpath(t)]);if(await yp(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!io(s,d)||!io(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await fE(u,i,n);await r?.beforeFinalCheck?.();let[h,g,S]=await Promise.all([u.stat(),Le.lstat(t),Le.realpath(t)]);if(await yp(a),!g.isFile()||g.isSymbolicLink()||S!==c||!io(s,h)||!io(s,g))throw new Error(`${n} changed while reading`);let N;try{N=new cE("utf-8",{fatal:!0}).decode(m)}catch(k){throw new Error(`${n} is not valid UTF-8`,{cause:k})}return{text:N,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function Np(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function il(e){return tl(e)}async function $i(e,t){let i=ro(e,"stateRef"),n=await ao(e,i,Oi.runStateBytes,"Native Run state",t);return n?tl(Np(n.text,"Native Run state")):null}async function ii(e,t,i){let n=ro(e,"trajectoryRef",t),r=await ao(e,n,Oi.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>Oi.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Oi.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 bp(e,t,i){return(await ao(e,ro(e,"trajectoryRef",t),Oi.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function oo(e,t,i){let n=await ao(e,ro(e,"checkpointRef",t),Oi.checkpointBytes,"Native Run checkpoint",i);return n?Np(n.text,"Native Run checkpoint"):null}var pE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function nl(e){return hE("sha256").update(e).digest("hex")}function mE(e,t){if(!pE.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=rl.join(e.changesDir,t);if(!W(e.changesDir,i))throw new Error("Native change path escaped");return rl.join(i,"runtime","trajectory.jsonl")}function vE(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 gE(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 wE(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=vE(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(`
|
|
173
|
-
`)
|
|
174
|
-
${
|
|
175
|
-
${n.
|
|
176
|
-
${n.ino}
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
`);function ir(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Dp(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 Li(e){if(!Fp.test(e))throw new Error(`Invalid Native change name: ${e}`)}function FE(e){if(!Fp.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Lp(e,t){if(e.length===0||be.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function DE(e,t){let i=ir(e,`spec_changes[${t}]`);if(Dp(i,IE,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(FE(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"&&Lp(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"||!dl.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"||!dl.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 LE(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 fl(e,t){if(Dp(e,t,ut),typeof e.name!="string")throw new Error("Native change name is required");if(Li(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"||!_E.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&&!jE.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(DE),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"||!OE.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"&&Lp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!LE(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 nr(e){let t=ir(e,ut);if(t.schema!==ri)throw new Error(`Expected ${ri}`);return{schema:ri,...fl(t,xE)}}function tr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ul(e,t,i){if(e===null)return null;let n=typeof e=="string"?$E.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 ME(e){if(e==null)return null;if(typeof e!="string"||!dl.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function BE(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 rr(e){let t=ir(e,ut);if(t.schema!==ni)throw new Error(`Expected ${ni}`);if(tr(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ni} minimum_runtime_version must be 2`);return{schema:ni,minimum_runtime_version:2,revision:tr(t.revision,"Native v2 revision"),...fl(t,Hp)}}function Dt(e){let t=ir(e,ut);if(t.schema!==Ft){if(t.schema===ri||t.schema===ni){let o=t.schema===ri?nr(t):rr(t);throw new uo(o.name,o.schema)}throw new ai(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=tr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new ai(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=tr(t.revision,"Native revision"),r=fl(t,TE),a=ME(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ft,minimum_runtime_version:3,revision:n,verification_protocol:BE(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:ul(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:ul(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:ul(t.partial_allowance,"Native partial_allowance","allowances")}}function Mp(e){let t=ir(e,ut);if(t.schema===ri){let r=nr(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Ft}`}}if(t.schema===ni){let r=rr(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Ft}`}}if(t.schema!==Ft){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 ai(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=tr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new ai(t.schema,i).message};let n=Dt(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function qE(e){let t=Dt(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 $(e,t){Li(t);let i=be.join(e.changesDir,t);if(!W(e.changesDir,i))throw new Error("Native change path escaped");return i}async function po(e,t){let i=be.join($(e,t),"runtime","schema-migration.json");await F(e.nativeRoot,i);try{return await lt.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Bp(e,t){let i=be.join($(e,t),"runtime","checkpoint-journal.json");await F(e.nativeRoot,i);try{return await lt.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function qp(e){return et(e.paths,`create change ${e.name}`,()=>VE(e))}async function VE(e){if(Li(e.name),e.initialProjectConfig&&await Ce(e.paths.projectRoot)===null&&await Sh(e.paths.projectRoot,e.initialProjectConfig),e.workspaceBinding){Tp(e.paths.projectRoot,e.workspaceBinding);let r=await KE(e.paths);if(r.length>0)throw new Zn(e.workspaceBinding.isolation,r)}let t=e.verificationProtocol??"legacy-v1",i=$(e.paths,e.name);await F(e.paths.nativeRoot,i);let n=!1;try{try{await lt.mkdir(i,{recursive:!1}),n=!0}catch(c){if(c.code==="ENOENT"){await lt.mkdir(e.paths.changesDir,{recursive:!0});try{await lt.mkdir(i,{recursive:!1}),n=!0}catch(l){throw l.code==="EEXIST"?new Error(`Native change already exists: ${e.name}`,{cause:l}):l}}else throw c.code==="EEXIST"?new Error(`Native change already exists: ${e.name}`,{cause:c}):c}let r={schema:Ft,minimum_runtime_version:3,revision:1,verification_protocol:t,name:e.name,language:e.language,phase:"shape",brief:"brief.md",approval:null,approved_contract_hash:null,spec_changes:[],verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1,created_at:(e.now??new Date).toISOString().slice(0,10),run_id:null};await Promise.all([lt.mkdir(be.join(i,"specs"),{recursive:!0}),lt.mkdir(be.join(i,"runtime","checkpoints"),{recursive:!0}),It(be.join(i,"brief.md"),HE)]);let o=(await Ce(e.paths.projectRoot))?.native.snapshot??Ha,s=await Zc(e.paths,{now:e.now,origin:"change-created",policy:o,limits:{maxFiles:o.max_files,maxFileBytes:o.max_total_bytes,maxTotalBytes:o.max_total_bytes,maxDurationMs:o.max_duration_ms},deadlineMs:o.max_duration_ms});if(!s.complete){let c=up(s),l=s.omitted.reduce((d,f)=>(d[f.reason]=(d[f.reason]??0)+1,d),{}),u=s.omissionOverflow?.count??0;throw u>0&&(l.overflow=u),new er(r.name,s.omittedCount,l,c.samplePaths,c.sampleTruncated,s.limits,s.policy?.hash??null)}return await mp(e.paths,r.name,s),await GE(e.paths,r),await jp({paths:e.paths,name:r.name,revision:r.revision,now:e.now,...e.workspaceBinding?{binding:e.workspaceBinding}:{}}),r}catch(r){throw n&&await lt.rm(i,{recursive:!0,force:!0}),r}}var WE=256*1024;async function Vp(e,t=be.dirname(e)){let i=be.relative(t,e).split(be.sep).join("/"),n=await de({root:t,ref:i,maxBytes:WE}),r=(0,ho.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 hl(e,t){let i=be.join($(e,t),ut);await F(e.nativeRoot,i);let n=Mp(await Vp(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await po(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 JE(e,n.state),n)}async function zE(e,t){let i=be.join($(e,t),ut);await F(e.nativeRoot,i);let n=Mp(await Vp(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return n}async function JE(e,t){if(await eo(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function dt(e,t){let i=await hl(e,t);if(i.status==="migration-required")throw new uo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new ai(i.schema,i.minimumRuntimeVersion);return await Op(e,t),i.state}async function GE(e,t){let i=be.join($(e,t.name),ut);await F(e.nativeRoot,i);try{throw await lt.access(i),new Error(`Native change state already exists: ${t.name}`)}catch(n){if(n.code!=="ENOENT")throw n}if(t.revision!==1)throw new Error("New Native change must start at revision 1");await It(i,(0,ho.stringify)(qE(t)))}async function UE(e){let t;try{let n=await Ai({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:4096});await n.verify(),t=n.entries}catch(n){if(n.code==="ENOENT")return[];throw n}return t.filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort()}async function KE(e){let t=[];for(let i of await UE(e)){let n=await zE(e,i);if(!n.state){t.push(i);continue}if(n.state.archived)continue;let r=await Be(e,i);if(r?.schema==="comet.native.workspace.v3"){if((await Xn({paths:e,identity:r})).code==="workspace-binding-root-changed")continue}else if(r&&(await Yn({paths:e,identity:r})).state==="drifted")continue;t.push(i)}return t}import{promises as pl}from"fs";import Wp from"path";var zp=["Outcome","Scope","Non-goals","Acceptance examples"],YE=[...zp,"Constraints and invariants","Decisions","Open questions","Verification expectations"],XE=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],Jp={maxFileBytes:Tn};function Gp(e){let t=new Map,i=null,n=[],r=()=>{i!==null&&t.set(i,n.join(`
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
${
|
|
192
|
-
|
|
193
|
-
`);let i=0;_m(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){Lt(t,"change",r);let a=0;for(let o of e.declaredArtifacts)bo(o,r.path)&&(a+=1,Lt(t,"change-attribution",o));Lt(t,"change-end",{attributionCount:a}),a===0&&Lt(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&&Lt(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function $m(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=XC(e,t,r,i.gitChangedPaths),s=D(lr,e),c=D(lr,t),l=[];for(let[y,w]of[["baseline",e],["current",t]])for(let v of w.omitted){if(l.length>=MC)break;l.push(ht({kind:"snapshot-omission",source:y,path:v.path,evidence:{reason:v.reason,size:v.size,type:v.type}},`${y} snapshot omitted ${v.path}: ${v.reason}`))}let u=e.omitted.length+t.omitted.length,d=[...Em("baseline",e),...Em("current",t),...o.totalChanges===0&&a===null?[ht({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")]:[]],f=()=>{if(i.gitChangedPaths===void 0)return;let y=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>y.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!y.has(w))}},p=y=>{let w=o.candidates.slice(0,y.detailedChangeCount),v=w.filter(Ue=>Ue.attributedTo.length===0),E=o.totalChanges-w.length,I=o.totalUnattributed-v.length,G=u-y.detailedOmissionCount,q=I+G,z=[...v.map(Ue=>ht({kind:"unattributed-change",source:"implementation-scope",path:Ue.path,evidence:{after:Ue.after,before:Ue.before,changeKind:Ue.kind}},`Changed path is not covered by a declared artifact: ${Ue.path}`)),...l.slice(0,y.detailedOmissionCount),...d,...E>0||q>0?[Om(y.overflowHash,{changes:E,unattributed:I,unresolved:q})]:[]],K=KC(z),Ge=y.includeGitAdvisory?f():void 0;return{schema:Al,contractHash:n,baselineProjectionRef:xl(s),baselineProjectionHash:s,currentProjectionRef:xl(c),currentProjectionHash:c,complete:K.length===0,declaredArtifacts:r,changes:w,unattributed:v,unresolvedScopes:K,noCodeReason:a,...Ge?{gitAdvisory:Ge}:{}}},m=o.candidates.length,h=l.length,g=i.gitChangedPaths!==void 0,S="0".repeat(64);for(;;){let y=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:g,overflowHash:S});if(ur({...y,scopeHash:S})<=si)break;if(g){g=!1;continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let k=o.totalChanges>m||u>h?ZC({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):S,b=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:g,overflowHash:k}),C={...b,scopeHash:D(Tm,b)};if(ur(C)>si)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return C}function jl(e){let t=Tl(e.baseline),i=Tl(e.current),n=jm(e);return{authority:n,baseline:t,current:i,scope:$m(t,i,n)}}var eR=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function pt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mt(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 oi(e,t){if(typeof e!="string"||!_l.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Cm(e,t,i){let n=xl(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function yo(e,t){let i=pt(e,"Native snapshot projection");if(mt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==xm)throw new Error("Native snapshot projection schema is invalid");let n=ct({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=Tl(n);if(D(lr,i)!==D(lr,r))throw new Error("Native snapshot projection is not canonical");let a=D(lr,r);if(t!==void 0&&oi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function Ol(e,t){let i=pt(e,`Declared artifact ${t}`);if(mt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Mt(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Rm(e,t){if(e===null)return null;let i=pt(e,t);return mt(i,["hash","size"],[],t),{hash:oi(i.hash,`${t} hash`),size:Vi(i.size,`${t} size`)}}function Pm(e,t){let i=pt(e,`Implementation change ${t}`);if(mt(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(Ol),r=No(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Rm(i.before,`Implementation change ${t} before`),o=Rm(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:Mt(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function tR(e,t){let i=pt(e,`Unresolved scope ${t}`);mt(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"?Im(i.path,`Unresolved scope ${t} path`):Mt(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function wo(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)=>Mt(r,`${t} ${a}`)),n=[...new Set(i)].sort(le);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function ko(e){let t=pt(e,"Native implementation scope"),i=[...eR].filter(w=>w!=="gitAdvisory");if(mt(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==Al)throw new Error("Native implementation scope schema is invalid");let n=oi(t.contractHash,"Implementation scope contractHash"),r=oi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Cm(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=oi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Cm(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(Ol);if(JSON.stringify(c)!==JSON.stringify(No(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Pm),u=[...l].sort((w,v)=>le(w.path,v.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(v=>!d.has(`${v.kind}:${v.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(v=>bo(v,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Pm),p=l.filter(w=>w.attributedTo.length===0);if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(tR),h=m.filter(w=>w.kind==="scope-detail-overflow");if(h.length>1)throw new Error("Implementation scope has multiple detail overflow records");let g=h[0]===void 0?null:QC(h[0]);if(g&&(g.changes+g.unresolved===0||g.unattributed>g.changes||g.unattributed>g.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,N=[...p.map(w=>ht({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(g?.changes??0)===0&&S===null?[ht({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:r,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Il))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(N.sort(Il))||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 b;if(t.gitAdvisory!==void 0){let w=pt(t.gitAdvisory,"Implementation scope Git advisory");if(mt(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let v=wo(w.changedPaths,"Git changed paths"),E=wo(w.pathsPresentInSnapshotChanges,"Git present paths"),I=wo(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),G=[...E,...I].sort(le),q=new Set(l.map(z=>z.path));if(JSON.stringify(G)!==JSON.stringify(v)||(g?.changes??0)===0&&E.some(z=>!q.has(z))||I.some(z=>q.has(z)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:v,pathsPresentInSnapshotChanges:E,pathsAbsentFromSnapshotChanges:I}}let C={schema:Al,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:S,...b?{gitAdvisory:b}:{}},y=oi(t.scopeHash,"Implementation scope scopeHash");if(D(Tm,C)!==y)throw new Error("Implementation scope content hash mismatch");return{...C,scopeHash:y}}function iR(e){let t=pt(e,"Native implementation scope authority");if(mt(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(Ol);if(JSON.stringify(i)!==JSON.stringify(No(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=wo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=jm({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 dr(e){let t=pt(e,"Native implementation scope bundle");mt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=iR(t.authority),n=yo(t.baseline),r=yo(t.current),a=ko(t.scope),o=$m(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 Hm(e){let t=ko(e.scope);return dr({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{}},baseline:e.baseline,current:e.current,scope:t})}var Lm=/^[a-f0-9]{64}$/u;var nR="comet.native.acceptance-trace.v2",rR="comet.native.partial-allowance.v1",aR="comet.native.verification-evidence.v2";function vt(e,t){if(!Lm.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Mm(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Bm(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 $l(e,t,i=2e3){let n=Ve(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function fr(e,t){let i=Fm.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})||Fm.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 oR(e,t,i){let n=fr(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=Xe(n),a=n.toLowerCase(),o=i?fr(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 Hl(e){let t=fr(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 Wi(e,t){return e<t?-1:e>t?1:0}function So(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Eo(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 qm(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 Dm(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 sR(e){let t=So(e,"Native acceptance trace");if(Eo(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"||!Lm.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=fr(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=So(o,`Native acceptance trace entry ${s}`);if(Eo(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(d=>typeof d!="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(d=>Hl(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Wi))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:fr(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:$l(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>Wi(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=vt(t.traceHash,"Native acceptance trace hash");if(D(nR,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function Vm(e){let t=So(e,"Native partial allowance");if(Eo(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(Wi))||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:Bm(t.change),scopeHash:vt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:$l(t.reason,"Partial allowance reason"),confirmedSummary:$l(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Mm(t.sourceRevision),confirmedAt:qm(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=vt(t.allowanceHash,"Native partial allowance hash");if(D(rR,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function Fl(e){let t=So(e,"Native verification evidence");if(Eo(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=vt(t.implementationScopeHash,"Native verification implementation scope hash"),n=sR(t.acceptanceTrace),r=vt(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:vt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Hl(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Wi)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort(Wi);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(f=>Hl(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Wi)))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 u={schema:"comet.native.verification-evidence.v2",change:Bm(t.change),sourceRevision:Mm(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:vt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:Dm(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:oR(t.reportRef,"Native verification report ref"),reportHash:vt(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:Dm(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:qm(t.createdAt,"Native verification timestamp")},d=vt(t.envelopeHash,"Native verification envelope hash");if(D(aR,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function Dl(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 Wm="repairStagnation",ke={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},lR=/^[a-f0-9]{64}$/u;var uR=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),dR=["data","runId","sequence","timestamp","type"],zm=["disposition","overrideSummaryHash","signatureHash"],fR=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Jm=12;function Ml(e,t){return e<t?-1:e>t?1:0}function Gm(e,t,i){let n=Object.keys(e).sort(Ml);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function Co(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 hr(e,t){if(typeof e!="string"||!lR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function hR(e){if(!Array.isArray(e)||e.length>qi.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(Ml)}function Um(e){if(typeof e!="string"||e.length===0||e.length>ke.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Ll(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>ke.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>ke.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${n} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>ke.maxTextCharacters&&(!r||e.length>ke.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>ke.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${n} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${n} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>ke.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>Ll(s,t+1,i,`${n}[${c}]`));return}let a=Co(e,n),o=Object.keys(a);if(o.length>ke.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>ke.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>ke.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Ll(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function pR(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function mR(e,t,i){let n=Co(e,`Native repair trajectory event ${t+1}`);if(Gm(n,dR,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(pR(n.timestamp),typeof n.type!="string"||!uR.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(Um(n.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let r={nodes:0,characters:0,ancestors:new Set};return Ll(n.data,0,r,"Native trajectory event data"),Co(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function Bl(e){let t=Co(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Ml),n=i.length===zm.length&&i.every((l,u)=>l===zm[u]);n||Gm(t,fR,"Native repair trajectory projection");let r=hr(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:hr(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=hr(t.contractHash,"Native repair trajectory contract hash"),s=hR(t.failedAcceptanceIds),c=Rl(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}}function vR(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function gR(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??Jm;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Pl({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":a<qi.warningAtConsecutiveFailures?"continue":a<qi.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function wR(e,t,i){let n=t.filter(a=>a.kind==="failure"),r=i?.maxVerifyFailures??Jm;if(n.length>=r)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||n.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Km(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>ke.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Um(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],n=null,r=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=mR(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>ke.maxTotalDataNodes||c>ke.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?hr(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?hr(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Wm)){if(n?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&r!==null&&p!==r||p===null&&(n?.disposition==="manual-stop"||n?.disposition==="hard-stop"))){i.length=0,n=null,r=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=Bl(f[Wm]);if(vR(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(i.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&p!==null&&r!==null&&p!==r&&(i.length=0,o=0),p!==null&&(r=p),gR(m,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(n?.contractHash===null&&p!==null&&r!==null&&p!==r)throw new Error("Native repair override cannot cross implementation scope progress");wR(m,i,n);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(n=m,i.length>qi.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function Ym(e){return Km(e).history}function Xm(e){let t=Km(e).latestProjection;return t?{...t}:null}var zi={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:[]},ql=U("comet-native-runtime:v3:semantic-repair-budget"),yR=[{skillVersion:"2",skillHash:U("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:U("comet-native-runtime:v1")}];function Qm(e){return e.skillVersion===zi.definition.metadata.version&&e.skillHash===ql||yR.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function Zm(e){return U(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 av=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],CR=new Set(av),ov=new Set([...av,"minimum_runtime_version","revision"]),RR=new Set([...ov,"operation"]),PR=512*1024,Vl=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),AR=new Set([...Vl,"implementationScopeHash","repairScopeHash","repairStagnation"]),Wl=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 Jl(e,t){return ER.join($(e,t),"runtime","transition.json")}function Po(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Gl(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 Ro(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function zl(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(u=>!AR.has(u)),a=[...Vl].find(u=>!Object.hasOwn(i,u)),o=Vl.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(Dl(i.summary,"Native transition journal event summary"),Ve(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Dl(i.noCodeReason,"Native transition journal event no-code reason"),Ve(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")?Bl(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function xR(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 zl({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return zl(e,t)}function Ul(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?xR(e.eventData,e.evidenceHash):zl(e.eventData,e.evidenceHash),r=il(e.nextRun),a=e.previousRun===null?null:il(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function ev(e,t,i=!1){if(e.skill!==zi.definition.metadata.name||(i?!Qm(e):e.skillVersion!==zi.definition.metadata.version||e.skillHash!==ql)||e.orchestration!==zi.definition.orchestration.mode||e.pendingRef!==xe.pendingRef||e.trajectoryRef!==xe.trajectoryRef||e.contextRef!==xe.contextRef||e.artifactsRef!==xe.artifactsRef||e.checkpointRef!==xe.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function tv(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 iv(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 Kl(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(ev(a,"next Run",n||r!==null),iv(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(ev(r,"previous Run",!0),iv(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(!rv(tv(r),tv(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function TR(e,t,i){return U(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function sv(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function nv(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Yl(e,t,i,n,r=!1){let a=i.eventData,o=nv(e),s=nv(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&&rv(e.spec_changes,t.spec_changes),l=Zm({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=TR(e.name,a.summary,t.spec_changes),l=U(`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 IR(e,t){let i=Po(e);if(Gl(i,RR),i.schema!==Fi)throw new Error(`Expected Native transition schema ${Fi}`);let n=Ro(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 ${Fi} minimum_runtime_version must be ${3}`);let r=Ro(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=Ul(i,t),o=Dt(i.previousState),s=Dt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Yl(o,s,a,i.operation),Kl(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Fi,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 _R(e,t){let i=Po(e);if(Gl(i,CR),i.schema!==Qn)throw new Error(`Expected Native transition schema ${Qn}`);let n=Ul(i,t,!0),r=nr(i.previousState),a=nr(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Yl(r,a,n,sv(r,a,n.eventData),!0),Kl(r,a,n,!0),{schema:Qn,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 jR(e,t){let i=Po(e);if(Gl(i,ov),i.schema!==Di)throw new Error(`Expected Native transition schema ${Di}`);if(Ro(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Di} minimum_runtime_version must be 2`);let r=Ro(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Ul(i,t,!0),o=rr(i.previousState),s=rr(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Yl(o,s,a,sv(o,s,a.eventData),!0),Kl(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Di,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 OR(e,t){let i=Po(e);if(i.schema===Fi)return{status:"current",journal:IR(i,t)};if(i.schema===Qn)return{status:"migration-required",journal:_R(i,t)};if(i.schema===Di)return{status:"migration-required",journal:jR(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function $R(e,t){let i=Jl(e,t);await F(e.nativeRoot,i);try{let n=await Ze({root:e.nativeRoot,file:i,maxBytes:PR,label:`Native transition journal ${t}`});return OR(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function cv(e,t){let i=await $R(e,t);if(!i)return null;if(i.status==="migration-required")throw new Wl(t);return i.journal}var HR=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function FR(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 lv(e){let i=(e.findings??[]).filter(u=>!Hi(u.code)),n=i.find(u=>u.requiresUserDecision),r=i.find(u=>u.repairCommand!==null||HR.test(u.code)),a=i.find(u=>u.code==="repair-iteration-limit"||u.code==="repair-override-exhausted"),o=i.find(u=>u.code==="repair-stagnation-stop"),s=i.find(u=>u.requiredAction==="return-to-bound-working-directory"||u.requiredAction==="repair-workspace-binding"),c=[...new Set(i.map(u=>u.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:c};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(s)return{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:c};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:c};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:c}:c.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:c}:{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:c};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 l=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>"${l}`,requiresUserDecision:!1,requiredInputs:FR(e.state)}}import pr from"path";var uv=8,DR={"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function LR(e){let t=DR[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:Hi(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function MR(e,t,i){if(!i.path)return null;let n;if(pr.isAbsolute(i.path)?n=pr.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=pr.resolve($(e,t.name),...i.path.split(/[\\/]/u)):n=pr.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!W(e.projectRoot,n))return null;let r=pr.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function BR(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function dv(e){return e.findings.map(t=>{let i=LR(t.code);return{code:t.code,message:t.message,severity:i.severity,path:MR(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:BR(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let n={error:0,warning:1,info:2};return n[t.severity]-n[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function fv(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,uv),truncated:t.length>uv}}import Nv from"path";import Ji from"path";var qt={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Gi=/^[a-f0-9]{64}$/u;function Ao(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xo(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 Bt(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 hv(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Xl(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function qR(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Ji.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Ji.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function pv(e,t){return Ji.join($(e,t),"runtime","checkpoints","progress.json")}function mr(e,t){return Ji.join($(e,t),"runtime","checkpoint-journal.json")}function mv(e,t,i){if(!Gi.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Ji.join($(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function VR(e){if(!Gi.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Ql(e,t,i){let n=await Ze({root:e,file:t,maxBytes:qt.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function WR(e,t){let i=Ao(e,`checkpoint manifest artifact ${t}`);xo(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=qR(Bt(i.path,`checkpoint artifact ${t} path`,4096)),r=Xe(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!Gi.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:Xl(i.size,`checkpoint artifact ${t} size`)}}function Zl(e,t){let i=Ao(e,"Native checkpoint manifest");if(xo(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>qt.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(WR),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=Xl(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>qt.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 vv(e){return U(JSON.stringify(Zl(e,e.change)))}function gv(e,t){let i=Ao(e,"Native progress checkpoint");if(xo(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=hv(i.previousRevision,"Native checkpoint previousRevision"),a=hv(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Bt(i.manifestHash,"Native checkpoint manifestHash",64);if(!Gi.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=VR(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Bt(i.inputHash,"Native checkpoint inputHash",64);if(!Gi.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Bt(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Xl(i.artifactCount,"Native checkpoint artifactCount");if(u>qt.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Bt(i.summary,"Native checkpoint summary"),f=Bt(i.nextAction,"Native checkpoint nextAction");if(Ve(d)!==d||Ve(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Bt(i.id,"Native checkpoint id",128),change:t,phase:n,previousRevision:r,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function zR(e,t){let i=Ao(e,"Native checkpoint journal");if(xo(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=Dt(i.previousState),r=Dt(i.nextState),a=gv(i.checkpoint,t),o=Zl(i.manifest,t),s=Bt(i.inputHash,"Native checkpoint journal inputHash",64),c=U(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Gi.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(n.name!==t||r.name!==t||r.revision!==n.revision+1||a.previousRevision!==n.revision||a.stateRevision!==r.revision||a.phase!==r.phase||a.manifestHash!==vv(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 JR(e,t,i){let n=Ji.resolve(e.projectRoot,...t.split("/"));if(!W(e.projectRoot,n)||W(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=bc(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await Ze({root:e.projectRoot,file:n,maxBytes:qt.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function GR(e,t){let i=pv(e,t);await F(e.nativeRoot,i);try{return gv(await Ql(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function UR(e,t,i){let n=mv(e,t,i);await F(e.nativeRoot,n);let r=await Ql(e.nativeRoot,n,"Native checkpoint manifest"),a=Zl(r,t);if(wv(e,a),vv(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function eu(e,t){let i=mr(e,t);await F(e.nativeRoot,i);try{let n=zR(await Ql(e.nativeRoot,i,"Native checkpoint journal"),t);return wv(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function wv(e,t){for(let i of t.artifacts){let n=bc(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function yv(e){let t;try{t=await GR(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:pv(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],n=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let r=null;try{r=await UR(e.paths,e.name,t.manifestHash);let a=U(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:r.artifacts}));if(t.inputHash!==a||t.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of r.artifacts)try{let s=await JR(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),n.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:mv(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}var bv=240,kv=8,To=50;function Sv(e){let t=Array.from(e);return t.length<=bv?e:`${t.slice(0,bv-1).join("")}…`}function KR(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function YR(e){let t=[...new Set(e.map(KR))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,kv),reasonCount:e.length,codesTruncated:t.length>kv};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,To),reasonsTruncated:e.length>To}}}async function Ev(e){let t=null;try{let s=await eu(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:mr(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:mr(e.paths,e.state.name)}}let i=await yv({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=YR(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:qt.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Sv(i.checkpoint.summary),nextAction:Sv(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:Nv.relative(e.paths.projectRoot,Nv.join($(e.paths,e.state.name),...i.checkpoint.manifestRef.split("/"))).replaceAll("\\","/"),artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:qt.maxArtifacts}}import{promises as HA}from"node:fs";import rg from"node:path";import Cv from"node:path";var XR="comet.native.archive-preflight.v1",QR="comet.native.archive-preflight.v1",ZR="comet.native.archive-operation.v1",eP=/^[a-f0-9]{64}$/u,Rv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Io(e,t){return e<t?-1:e>t?1:0}function iP(e,t){if(typeof e!="string"||!eP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function gt(e,t){return e===null?null:iP(e,t)}function nP(e,t){let i=Cv.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Cv.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 rP(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function aP(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function oP(e,t){if(!Rv.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=gt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=gt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=gt(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 sP(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:gt(e.contractHash,"Native archive contract hash"),acceptanceHash:gt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:gt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:gt(e.reportHash,"Native archive report hash"),envelopeHash:gt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:gt(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 cP(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!tP.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(Io);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function lP(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(Io)}function Pv(e){if(!Rv.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(oP).sort((l,u)=>Io(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:D(ZR,l)})),n=sP(e.evidence),r=aP(e.workspace),a=[...new Set([...cP(e.findingCodes??[]),...lP({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(Io),o=rP(e.revision),s=nP(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:n,workspace:r,findingCodes:a};return{schema:XR,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:n.freshness,operationCount:i.length,operations:i,workspace:r,findingCodes:a,preflightHash:D(QR,c)}}import{createHash as uP}from"node:crypto";import Av from"node:path";var dP="comet.native.conflict-radar.v1",ge=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}),fP="comet.native.conflict-radar.v1",hP="comet.native.conflict-radar-signals.v1",pP=/^[a-f0-9]{64}$/u,Iv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mP=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),vP=new Set(["capability","operation","baseHash"]),gP=new Set(["path","kind"]);function Ui(e,t){return e<t?-1:e>t?1:0}function tu(e){return Buffer.byteLength(e,"utf8")}function iu(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 nu(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(tu(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function wP(e,t){let i=nu(e,t,ge.maxArtifactPathBytes),n=Av.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)||Av.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 _v(e,t){if(typeof e!="string"||!pP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yP(e,t){let i=iu(e,vP,t),n=nu(i.capability,`${t} capability`,ge.maxCapabilityBytes);if(!Iv.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:_v(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 NP(e,t){let i=iu(e,gP,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:wP(i.path,`${t} path`),kind:i.kind}}function bP(e,t){let i=iu(e,mP,`Conflict radar change ${t}`),n=nu(i.name,`Conflict radar change ${t} name`,ge.maxNameBytes);if(!Iv.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>ge.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>ge.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>yP(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>Ui(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)=>NP(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>Ui(c.path,l.path)||Ui(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:_v(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function kP(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ge.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(bP).sort((r,a)=>Ui(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)>ge.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>ge.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function SP(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 EP(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 CP(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function RP(e,t){let i=[],n=uP("sha256").update(`${hP}
|
|
194
|
-
[`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(or(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<ge.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(SP(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=EP(l,u);d&&o(d)}let c=a?"definite-conflict":r>0?"possible-overlap":"disjoint";return n.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:CP(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function xv(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function PP(e,t){return xv(e.classification)-xv(t.classification)||Ui(e.left,t.left)||Ui(e.right,t.right)}function Tv(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:dP,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 jv(e){let t=kP(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(RP(t[s],t[c]));i.sort(PP);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(fP,{changes:t,relationships:n}),a=i.slice(0,ge.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Tv(t,i,a,r);for(;a.length>0&&tu(JSON.stringify(o))>ge.maxSerializedBytes;)a=a.slice(0,-1),o=Tv(t,i,a,r);if(tu(JSON.stringify(o))>ge.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as aA}from"node:crypto";import{promises as ze}from"node:fs";import it from"node:path";import Ov from"node:path";var $v="comet.native.check-receipt.v1",AP="comet.native.check-receipt.v1",Ki="scoped-text-safety",ru=1,Te=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),xP=/^[a-f0-9]{64}$/u,TP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,IP="comet.native.checker-policy.v1",_P="comet.native.check-input.v1",jP=2048,Hv=D(IP,{policy:Ki,version:ru,limits:Te,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),OP=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),Fv=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Lv=["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"],$P=new Set(Lv);function li(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ui(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 wt(e,t){if(typeof e!="string"||!xP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ci(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Mv(e,t){let i=ci(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function Dv(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 HP(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>jP||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=Ov.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Ov.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function FP(e){let t=li(e,"Native check receipt checker");ui(t,["policy","version","hash","limits"],"Native check receipt checker");let i=li(t.limits,"Native check receipt limits");if(ui(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Ki||t.version!==ru||t.hash!==Hv||i.maxFiles!==Te.maxFiles||i.maxFileBytes!==Te.maxFileBytes||i.maxTotalBytes!==Te.maxTotalBytes||i.maxIssues!==Te.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Ki,version:ru,hash:Hv,limits:{...Te}}}function DP(e){let t=li(e,"Native check receipt contract");return ui(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:wt(t.expectedHash,"Native check expected contract hash"),beforeHash:wt(t.beforeHash,"Native check before contract hash"),afterHash:wt(t.afterHash,"Native check after contract hash")}}function LP(e){let t=li(e,"Native check receipt implementation");return ui(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:wt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:wt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:wt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:wt(t.afterSnapshotHash,"Native check after snapshot hash")}}function MP(e){let t=li(e,"Native check receipt counts");ui(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:ci(t.filesSelected,"Native check filesSelected"),filesScanned:ci(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:ci(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:ci(t.bytesScanned,"Native check bytesScanned"),issueCount:ci(t.issueCount,"Native check issueCount"),recordedIssueCount:ci(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>Te.maxFiles||i.bytesScanned>Te.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Te.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function BP(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||Fv.indexOf(e.kind)-Fv.indexOf(t.kind)}function qP(e){if(!Array.isArray(e)||e.length>Te.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=li(n,`Native check issue ${r}`);if(ui(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!OP.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:HP(a.path,`Native check issue ${r} path`),line:Mv(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(BP);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function VP(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!$P.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=Lv.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 WP(e){return D(_P,e)}function Bv(e){let t=li(e,"Native check receipt");if(ui(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==$v)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!TP.test(t.change))throw new Error("Native check receipt change name is invalid");let i=Mv(t.sourceRevision,"Native check source revision"),n=FP(t.checker),r=DP(t.contract),a=LP(t.implementation),o=WP({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(wt(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=Dv(t.startedAt,"Native check receipt startedAt"),c=Dv(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=MP(t.counts),u=qP(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=VP(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.filesSelected>Te.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>Te.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:$v,change:t.change,sourceRevision:i,checker:n,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:r,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},m=wt(t.receiptHash,"Native check receipt content hash");if(D(AP,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var ou="comet.native.verification-receipt.v3",zP=ou,JP="comet.native.declared-artifacts.v1",GP=/^[a-f0-9]{64}$/u,UP=/^acceptance-[a-f0-9]{64}$/u,KP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,YP=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,XP=4096,QP=256,ZP=1024;function Yi(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 Vt(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 yt(e,t){if(typeof e!="string"||!GP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function We(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=Ve(e).trim();if(!i||i.length>XP||i!==e.trim())throw new Error(`${t} is invalid`);return i}function au(e,t){let i=We(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 vr(e,t,i=We,n=!1,r=QP){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 eA(e,t){if(typeof e!="string"||!UP.test(e))throw new Error(`${t} is invalid`);return e}function tA(e){let t=Yi(e,"Native verification receipt bindings");if(Vt(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!KP.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:yt(t.contractHash,"Native verification receipt contract hash"),scopeHash:yt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:yt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:yt(t.artifactHash,"Native verification receipt artifact hash")}}function iA(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=YP.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function nA(e,t,i,n){let r=Yi(t,`Native ${e} evidence`);if(e==="automated-check"){if(Vt(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=au(r.startedAt,"Native automated-check start time"),o=au(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=Yi(r.worktree,"Native automated-check worktree");if(Vt(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=Yi(r.afterFence,"Native automated-check after fence");if(Vt(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:We(r.executable,"Native automated-check executable"),args:vr(r.args,"Native automated-check arguments",We,!0),cwd:We(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:We(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:yt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:yt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:yt(r.outputHash,"Native automated-check output hash"),outputSummary:We(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){Vt(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=iA(r.checkReceiptRef);if(yt(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:vr(r.subjects,"Native static inspection subjects",We,n==="required-check"),rule:We(r.rule,"Native static inspection rule"),resultSummary:We(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Vt(r,["steps","observations"],"Native manual-evidence evidence"),{steps:vr(r.steps,"Native manual evidence steps"),observations:vr(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function rA(e){let t=Yi(e,"Native verification receipt");if(Vt(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=We(t.actor,"Native verification receipt actor"),o=vr(t.acceptanceIds,"Native receipt acceptance IDs",eA,n==="required-check",ZP).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:ou,kind:i,role:n,status:r,bindings:tA(t.bindings),acceptanceIds:o,actor:a,issuedAt:au(t.issuedAt,"Native verification receipt issue time"),evidence:nA(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Ki||s.actor!==`native-runtime:${Ki}`))throw new Error("Native required check policy identity is invalid");return s}function qv(e){let t=Yi(e,"Native verification receipt");if(Vt(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==ou)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=rA(n),a=yt(t.receiptHash,"Native verification receipt hash");if(D(zP,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function su(e){return D(JP,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var Jv=/^[a-f0-9]{64}$/u,Xi=si,M$=3*Xi;function cu(e,t){let i=it.relative(e,t);return i===""||!it.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${it.sep}`)}function oA(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function _o(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return se(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Vv(e){let t=await ze.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ze.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function sA(e,t){let i=it.resolve(e),n=it.resolve(t);if(!cu(i,n))throw new Error("Native evidence path is outside its change");let r=[await Vv(i)],a=i;for(let o of it.relative(i,n).split(it.sep).filter(Boolean)){a=it.join(a,o);let s=await Vv(a);if(!cu(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function Wv(e){for(let t of e){let i=await ze.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!oA(t,i)||await ze.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function cA(e,t,i={}){let n=await sA(t,it.dirname(e));await i.afterParentChainCaptured?.();let r=await ze.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ze.realpath(e);if(!cu(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ze.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ze.lstat(e),ze.realpath(e)]);if(await Wv(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!_o(s,r)||!_o(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Xi)throw new Error(`Native evidence document exceeds ${Xi} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let g=Xi+1-d,S=await o.read(f,0,Math.min(f.length,g),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>Xi)throw new Error(`Native evidence document exceeds ${Xi} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),ze.lstat(e),ze.realpath(e)]);if(await Wv(n),!m.isFile()||m.isSymbolicLink()||h!==a||!_o(s,p)||!_o(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function Gv(e,t){if(!Jv.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function lA(e,t,i,n,r){if(!Jv.test(i))throw new Error("Native report evidence hash is invalid");let a=await di({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"||aA("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 Qi(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 uA(e,t,i,n,r){return it.join(r??$(e,t),...Gv(i,n).split("/"))}async function di(e){let t=e.changeDir??$(e.paths,e.name),i=uA(e.paths,e.name,e.kind,e.hash,t);return await F(e.paths.nativeRoot,i),cA(i,t,e.hooks)}function zv(e,t){return yo(e,t)}function dA(e,t){let i=ko(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function fA(e,t,i){let n=Vm(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function hA(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 pA(e,t,i,n=!1,r){let a=await lu(e,t,i.implementationScopeRef,void 0,r);if(n&&await lA(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 Uv(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 gr(e,t,i,n,r){let a=Qi(i,"scopes"),o=dA(await di({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=Qi(o.baselineProjectionRef,"snapshots"),c=Qi(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([di({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(d=>zv(d,s)),di({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(d=>zv(d,c))]);return Hm({baseline:l,current:u,scope:o})}async function lu(e,t,i,n,r){return(await gr(e,t,i,n,r)).scope}async function Uv(e,t,i,n,r){let a=Qi(i,"allowances");return fA(await di({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function jo(e,t,i,n,r){let a=Qi(i,"receipts"),o=qv(await di({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 wr(e,t,i,n,r){let a=Qi(i,"verifications"),o=hA(await di({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await pA(e,t,o,!1,r),o}var mA=4096;async function vA(e,t=ge.maxChanges){try{let i=await Ai({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function Kv(e,t){let i=await dt(e,t),[n,r]=await Promise.all([i.implementation_scope?lu(e,t,i.implementation_scope):null,Be(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 Oo(e,t,i={}){let r=(await vA(e,mA)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!r.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await Kv(e,t),o=0,s=0;for(let c of r){if(c===t)continue;let l=await Kv(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=jv([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{execFile as PA,spawn as bH}from"node:child_process";import{promisify as AA}from"node:util";import{constants as uu,promises as Ie}from"node:fs";import fi from"node:path";var wA=/^[a-f0-9]{64}$/u,yA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,yr=512*1024;function NA(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function $o(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return se(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function bA(e,t){let i=fi.resolve(e),n=fi.resolve(t);if(!W(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...fi.relative(i,n).split(fi.sep).filter(Boolean)]){o&&(a=fi.join(a,o));let s=await Ie.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ie.realpath(a);if(r.length>0&&!W(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 Xv(e){for(let t of e){let i=await Ie.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!NA(t,i)||await Ie.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function kA(e){if(!wA.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function SA(e){let t=yA.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function EA(e,t,i){return fi.join($(e,t),...kA(i).split("/"))}async function CA(e,t,i){let n=await bA(i,fi.dirname(e)),r=await Ie.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>yr)throw new Error(`Native check receipt exceeds ${yr} bytes`);let[a,o]=await Promise.all([Ie.realpath(t),Ie.realpath(e)]);if(!W(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":uu.O_RDONLY|uu.O_NOFOLLOW|uu.O_NONBLOCK,c=await Ie.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,u,d]=await Promise.all([c.stat(),Ie.lstat(e),Ie.realpath(e)]);if(await Xv(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!$o(r,l)||!$o(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let N=yr+1-p,k=await c.read(m,0,Math.min(m.length,N),null);if(k.bytesRead===0)break;if(p+=k.bytesRead,p>yr)throw new Error(`Native check receipt exceeds ${yr} bytes`);f.push(Buffer.from(m.subarray(0,k.bytesRead)))}let[h,g,S]=await Promise.all([c.stat(),Ie.lstat(e),Ie.realpath(e)]);if(await Xv(n),!g.isFile()||g.isSymbolicLink()||S!==o||!W(a,S)||!$o(l,h)||!$o(l,g))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function Qv(e,t,i){let n=SA(i),r=$(e,t),a=EA(e,t,n);await F(e.nativeRoot,a);let o=Bv(await CA(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}var Nr=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var HH=64*1024;var FH=3600*1e3;var DH=AA(PA);var LH=["$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 xA=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Zv(e,t){let i=[];for(let n of xA){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 eg(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Qv(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 Wt=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 TA(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 IA(e){let t=TA(e.bundle.baseline),i=await el(e.paths,t,{origin:"explicit",now:e.now});return jl({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function ig(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await gr(e.paths,e.state.name,e.state.implementation_scope),i=await Bi({changeDir:$(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await IA({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 ng(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await ig(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function _A(e){let t=await de({root:$(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:om(t.text)}}function jA(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 OA(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:su(e.implementationScope.scope.declaredArtifacts)}}async function tg(e){let t=await jo(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=Zv(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 Wt([{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 eg({paths:e.paths,state:e.state,receipt:t});if(r){let a=jA({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 $A(e){let t=OA({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await tg({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Wt)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 tg({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Wt)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 Wt(i)}function du(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function fu(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:du(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([ig(e),wr(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:du(e.state.verification_result,"stale"),envelope:null};let n=await _A({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 $A({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:du(e.state.verification_result,"invalid"),envelope:null}}}function FA(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function ag(e){try{return await HA.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function DA(e,t){try{return(await de({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function LA(e,t,i){let n=mo(e,i.capability);if(!W(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=rg.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await DA(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await de({root:$(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 MA(e,t){return ag(Jl(e,t))}async function hu(e){let t=e.now??new Date,i=await dt(e.paths,e.name),n=await Be(e.paths,e.name),r=await Ce(e.paths.projectRoot),a=FA(i.name,t),o=rg.resolve(e.paths.nativeRoot,...a.split("/"));if(!W(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(m=>LA(e.paths,i.name,m))),fu({paths:e.paths,state:i,now:t}),Oo(e.paths,i.name),po(e.paths,i.name),Bp(e.paths,i.name),MA(e.paths,i.name),ag(o)]);return Pv({change:i.name,archiveConfirmation:r?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:n?.schema==="comet.native.workspace.v3"?{schema:n.schema,isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}async function BA(e,t){let i=$(e,t.name),n=await $i(i);if(!n||!t.run_id||n.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let r=await oo(i,n.checkpointRef);if(!r||r.runId!==n.runId||r.stateVersion!==n.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await ii(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function qA(e,t){let i=await BA(e,t);return{committed:i,latest:Xm(i),history:Ym(i)}}async function og(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await qA(e,t),r=n.latest;if(!r)return null;let a=n.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=r.disposition==="hard-stop"&&!o?"continue":r.disposition;return{disposition:o?"hard-stop":s,signatureHash:r.signatureHash,overrideRecorded:n.history.some(c=>c.kind==="override"&&c.signatureHash===r.signatureHash),failedAcceptanceIds:[...r.failedAcceptanceIds],failedCheckIds:[...r.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var J1=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function WA(e){return(await wm(e))?.change??null}function zA(e,t,i=!1,n){return e.phase==="archive"?t?`comet native archive ${e.name} --dry-run`:i?`comet native next ${e.name} --summary "<summary>"`:null:`comet native next ${e.name} --summary "<summary>"${e.phase==="shape"||e.phase==="build"&&e.approval!=="confirmed"?" --confirmed":""}`}async function JA(e,t){let i=$(e,t.name),n=[...(await ml(i,t.brief)).findings,...(await Up(e,t)).findings,...await Nm(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await eo(e,t.name);if(r===null)n.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await hp(e,r);a.complete||n.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(r){n.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${r.message}`})}if(t.phase==="build")try{let r=await Bi({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==r.contract.contractHash&&n.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(r){n.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${r.message}`})}try{await cv(e,t.name)&&n.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(r){n.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${r.message}`})}return t.verification_report?n.push(...(await vl(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&n.push({code:"verification-report-missing",message:"Native change has no verification report"}),n}async function sg(e,t,i){let n=await WA(e)===t,r;try{let w=await hl(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};r=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,error:w.message}}let a=await Ev({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await og(e,r,i?.maxVerifyFailures??5),o&&(o.disposition==="manual-stop"||o.disposition==="hard-stop")){let w=o.disposition==="hard-stop"?"repair-iteration-limit":o.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";s.push({code:w,message:`Native repair is stopped at failure signature: ${o.signatureHash}`})}}catch{s.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let c;if(i?.details&&(r.phase==="build"||r.phase==="verify"||r.phase==="archive"))try{let w=await Bi({changeDir:$(e,r.name),briefRef:r.brief,specChanges:r.spec_changes}),v=new Map;if(r.phase==="build"&&r.verification_result==="fail"&&r.verification_evidence){let E=await wr(e,r.name,r.verification_evidence);for(let I of E.acceptanceTrace.entries)v.set(I.acceptanceId,I.status==="failed"?"failed":I.status==="missing"?"missing":"satisfied")}c=tm({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:v,failedCheckIds:o?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}})}catch(w){if(i.acceptanceCursor)throw w;c=void 0}let l=[];if(i?.includeConflictFindings!==!1)try{let w=await Oo(e,r.name,{tolerateInvalidSiblings:!0});l.push(...w.findingCodes.map(v=>({code:v,message:`Native change overlap is visible in the current root: ${v}`})))}catch{l.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let u=[];try{let w=await Be(e,r.name);if(w)if(w.schema==="comet.native.workspace.v3"){let v=await Xn({paths:e,identity:w});v.state==="drifted"&&v.code&&u.push({code:v.code,message:v.message??"Native workspace binding is no longer valid"})}else{let v=await Yn({paths:e,identity:w});u.push(...v.findingCodes.map(E=>({code:E,message:`Native workspace advisory changed: ${E} (${v.driftComponents.join(", ")||"no-component"})`})))}}catch{u.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let d=[],f=!1;if(r.phase==="verify"){let w=await ng({paths:e,state:r});f=w.freshness!=="fresh",d.push(...w.findingCodes.map(v=>({code:v,message:`Native Verify implementation scope is not current: ${v}`})))}let p=null,m=[];if(r.phase==="archive")try{p=await hu({paths:e,name:r.name}),m.push(...p.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let h=[...await JA(e,r),...a.findings,...l,...u,...d,...s,...m].filter((w,v,E)=>E.findIndex(I=>I.code===w.code&&I.path===w.path)===v),g=dv({paths:e,state:r,findings:h}),S=g.filter(w=>!Hi(w.code)),N=r.phase==="archive"&&p?.ready===!0&&S.length===0,k=f||r.phase==="archive"&&(p?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=g.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),C=o?.disposition==="manual-stop"||o?.disposition==="hard-stop",y=g.find(w=>w.severity==="error");return{name:r.name,phase:r.phase,revision:r.revision,approval:r.approval,verificationResult:r.verification_result,specChanges:r.spec_changes.length,selected:n,nextCommand:b||C?null:zA(r,N,k,i?.clarificationMode),archiveReady:N,inspection:a.inspection,findingSummary:fv(g),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:lv({state:r,findings:g,archiveReady:N,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),repair:o,...i?.details?{...c?{acceptancePage:c}:{},findings:g.slice(0,50),inspectionDetails:a.inspectionDetails,checkpointDetails:a.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:To,maxCheckpointArtifacts:a.maxCheckpointArtifacts,findingsTruncated:g.length>50,inspectionReasonsTruncated:a.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,...y?{error:y.message}:{}}}import KA from"path";var aF={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var pF=16*1024*1024,mF=256*1024,vF=16*1024;var eD=16*1024*1024,Ho=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"},Fo=class extends Error{constructor(i,n=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(n);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var dD=10*1024*1024,Je=class extends Error{};function cg(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new Je(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function hi(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Je(`${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 Je(`${t} requires a value`);return e.splice(n,2),r}function lg(e){if(e.length>0)throw new Je(`Unexpected argument: ${e[0]}`)}function ug(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new Je(`${t} is required`);return i}function dg(e,t="en"){let i=hi(e,"--language")??t;if(i!=="en"&&i!=="zh-CN")throw new Je("--language must be en or zh-CN");return i}async function fg(e){return e?KA.resolve(e):Oc(process.cwd())}function hg(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
|
|
195
|
-
`}}function pg(e,t){if(t instanceof Je)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Ho)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 Fo)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof fo)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 Zn)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof er)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 Wt)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Nr)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let 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 mg(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}})+`
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
160
|
+
# 可选值:true | false`}};function cu(t,e){return Wr[e][t]}function tg(t,e,i){let r=/^(\s*)([a-z_]+):/u.exec(t);if(!r)return null;let n=r[1].length,a=r[2];if(n===0&&a in Wr.en)return a;if(n===2&&e){let o=`${e}.${a}`;if(o in Wr.en)return o}if(n===4&&e==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in Wr.en)return o}return null}function Si(t,e){let i=[],r=null,n=null;for(let a of(0,bi.stringify)(t).trimEnd().split(`
|
|
161
|
+
`)){let o=tg(a,r,n);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of cu(o,e).split(`
|
|
162
|
+
`))i.push(`${s}${c}`)}i.push(a),/^[a-z_]+:/u.test(a)?(a.startsWith("native:")?r="native":a.startsWith("classic:")?r="classic":r=null,n=null):/^ {2}[a-z_]+:/u.test(a)&&r==="native"&&(n=a.startsWith(" snapshot:")?"snapshot":null)}return i.push(""),i.join(`
|
|
163
|
+
`)}function ig(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||zr.posix.isAbsolute(i)||zr.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${e} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${e} must not contain empty or dot path segments`);return r}function lt(t){let e=ig(t,"native.artifact_root");return e.length===0?".":e.join("/")}function lu(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Eo(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim().replaceAll("\\","/");if(r.length===0||zr.posix.isAbsolute(r)||zr.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${e} cannot contain wildcards`);return n.join("/")}function Ni(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function uu(t,e,i){let r=t??e;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function Ur(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Jr)throw new Error(`${e} exceeds ${Jr} characters`);let i=0;for(let r=0;r<t.length;r+=1)t[r]==="?"?i+=1:t[r]==="*"&&(i+=1,t[r+1]==="*"&&(r+=1));if(i>Gr)throw new Error(`${e} contains more than ${Gr} wildcard tokens`);return t}function su(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(r=>Ur(r,e)))].sort((r,n)=>r.localeCompare(n,"en"))}function ko(t,e,i){let r=t??e;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function rg(t){if(t===void 0)return{...K,include:[...K.include],exclude:[...K.exclude]};let e=Ni(t,"native.snapshot");return{include:su(e.include,"native.snapshot.include",K.include),exclude:su(e.exclude,"native.snapshot.exclude",K.exclude),max_files:ko(e.max_files,K.max_files,"native.snapshot.max_files"),max_total_bytes:ko(e.max_total_bytes,K.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ko(e.max_duration_ms,K.max_duration_ms,"native.snapshot.max_duration_ms")}}function ng(t){if(t===void 0)return;let e=Ni(t,"native.pending_root_move"),i=e.id,r=e.from_artifact_root,n=e.to_artifact_root,a=e.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let s=Ni(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,d=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:i,fromArtifactRoot:lt(r),toArtifactRoot:lt(n),stage:a,...o?{cleanup:o}:{}}}function ag(t,e={}){let i=Ni(t,"native"),r=i.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??So;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=ng(i.pending_root_move);return{artifact_root:lt(r),language:uu(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:rg(i.snapshot),...s?{pending_root_move:s}:{}}}function og(t){let e=Ni(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=e.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=e.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:lu(e.artifact_layout),language:uu(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function sg(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function cg(t,e,i,r,n){let a=t.schema!==void 0;if(!(a||t.default_workflow!==void 0||t.workflows!==void 0||!n.allowPartialProject&&t.native!==void 0)||n.allowPartialProject&&!a)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=t.workflows??[t.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:r,...e?{native:e}:{},...i?{classic:i}:{}}}function At(t,e={}){let i=(0,bi.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=sg(n.ambient_resume),o=n.native===void 0?void 0:ag(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=n.classic===void 0?void 0:og(n.classic),c=cg(n,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function du(t){return{id:t.id,from_artifact_root:t.fromArtifactRoot,to_artifact_root:t.toArtifactRoot,stage:t.stage,...t.cleanup?{cleanup:{kind:t.cleanup.kind,state:t.cleanup.state,manifest_hash:t.cleanup.manifestHash}}:{}}}function fu(t){return{schema:t.schema,default_workflow:t.default_workflow,workflows:t.workflows??[t.default_workflow],ambient_resume:t.ambient_resume,...t.native?{native:{artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,...t.native.pending_root_move?{pending_root_move:du(t.native.pending_root_move)}:{}}}:{},...t.classic?{classic:{artifact_layout:t.classic.artifact_layout,language:t.classic.language,context_compression:t.classic.context_compression,review_mode:t.classic.review_mode,auto_transition:t.classic.auto_transition}}:{}}}function yi(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Ei(t,e){let i=fu(e),r=At((0,bi.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...t,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.native){let a=yi(t.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(delete o.snapshot,r.native.pending_root_move){let s=yi(a.pending_root_move),c=du(r.native.pending_root_move),l=yi(s.cleanup),d=yi(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...d}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...yi(t.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}function Kr(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:lt(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:So,snapshot:{...K,include:[...K.include],exclude:[...K.exclude]}}}}import{createHash as ug}from"crypto";import{promises as Qr}from"fs";import Ue from"path";import{constants as Yr,promises as ut}from"fs";function Ge(t){return t!==0&&t!==0n&&t!=="0"}function Y(t,e){return Ge(t.dev)&&Ge(e.dev)&&Ge(t.ino)&&Ge(e.ino)}function T(t,e){let i=Ge(t.dev)&&Ge(e.dev);if(i&&t.dev!==e.dev)return!1;let r=Ge(t.ino)&&Ge(e.ino);return r&&t.ino!==e.ino?!1:i&&r?!0:t.birthtime===e.birthtime}var ue=class extends Error{reason;constructor(e,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=e}};function Po(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function hu(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Pi(t){return{dev:t.dev,ino:t.ino,birthtime:Po(t)}}function Xr(t,e){let i=Pi(t),r=Pi(e);return Y(i,r)?T(i,r):T(i,r)&&Po(t)===Po(e)&&hu(t)===hu(e)&&t.size===e.size}async function _t(t,e,i={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await ut.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ue("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new ue("too-large",`${r} exceeds ${e} bytes`);let o=await ut.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:Pi(a)});let s=process.platform==="win32"?Yr.O_RDONLY:Yr.O_RDONLY|Yr.O_NOFOLLOW|Yr.O_NONBLOCK,c;try{c=await ut.open(t,s)}catch(l){throw l.code==="ELOOP"?new ue("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,d,u]=await Promise.all([c.stat({bigint:n}),ut.lstat(t,{bigint:n}),ut.realpath(t)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||u!==o||!Xr(a,l)||!Xr(a,d))throw new ue("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:u,identity:Pi(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let N=e+1-p,{bytesRead:k}=await c.read(g,0,Math.min(g.length,N),null);if(k===0)break;if(p+=k,p>e)throw new ue("too-large",`${r} exceeds ${e} bytes`);f.push(Buffer.from(g.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,m,y]=await Promise.all([c.stat({bigint:n}),ut.lstat(t,{bigint:n}),ut.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||y!==o||!Xr(a,h)||!Xr(a,m))throw new ue("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:y,identity:Pi(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:y}}finally{await c.close()}}function lg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function xo(t,e){let i=Ue.relative(t,e);return i===""||!Ue.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ue.sep}`)}async function pu(t,e){let i=Ue.resolve(t),r=await Qr.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Qr.realpath(i)}async function mu(t,e,i,r){let n=t;for(let a=0;a<i.length;a++){n=Ue.join(n,i[a]);let o;try{o=await Qr.lstat(n)}catch(d){if(lg(d))return{exists:!1,kind:"missing"};throw d}let s=Ue.relative(t,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await Qr.realpath(n);if(!xo(e,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Tt(t,e,i){let r=Eo(e,i.label),n=Ue.resolve(t),a=await pu(n,i.label),o=r.split("/"),s=Ue.resolve(n,...o);if(!xo(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await mu(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Ke(t,e,i,r){let n=await Tt(t,e,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await pu(n.projectRoot,r.label);return _t(n.target,i,{...r,verify:async(o,s)=>{if(!xo(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await mu(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var xi=".comet/config.yaml";function Co(t,e){return t.exists===e.exists&&t.sha256===e.sha256}function dg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Ro(t,e={}){return(await Ci(t,e)).document}async function vu(t){try{return(await Ke(t,xi,ki,{label:xi})).bytes}catch(e){if(dg(e))return null;throw e}}function gu(t){return t?{exists:!0,sha256:ug("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Zr(t){return gu(await vu(t))}async function Ci(t,e={}){let i=await vu(t);return{document:i?At(i.toString("utf8"),e):null,identity:gu(i)}}var uS=16*1024;async function Ao(t,e){if(!e)return;let i=await Zr(t);if(!Co(i,e))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as mg}from"crypto";import{promises as B}from"fs";import de from"path";function To(t,e){let i=de.relative(t,e);return i===""||!de.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${de.sep}`)}function vg(t,e){return T({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function _o(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return Y(i,r)?T(i,r):T(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function wu(t){let e=await B.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await B.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Ai(t){for(let e of t){let i=await B.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!vg(e,i)||await B.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function gg(t,e){let i=de.resolve(t),r=de.resolve(e);if(!To(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await wu(i)],a=de.relative(i,r).split(de.sep).filter(Boolean),o=i;for(let s of a){await Ai(n),o=de.join(o,s);try{await B.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await wu(o);if(!To(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ai(n),n}async function wg(t){let e;try{e=await B.open(t,"r"),await e.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await e?.close()}}async function yg(t,e,i={}){let r=de.dirname(t),n=i.containedRoot?await gg(i.containedRoot,r):null;n||await B.mkdir(r,{recursive:!0});let a=de.join(r,`.${de.basename(t)}.${mg()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await B.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([B.lstat(a),B.realpath(a)]);if(await Ai(n),!c.isFile()||c.isSymbolicLink()||!_o(s,c)||!To(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!_o(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await Ai(n);let c=await B.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!_o(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await B.link(a,t),await B.unlink(a)):await B.rename(a,t),await wg(r)}catch(c){if(await o?.close(),!n)await B.rm(a,{force:!0});else try{await Ai(n),await B.rm(a,{force:!0})}catch{}throw c}}async function te(t,e,i={}){await yg(t,e,i)}async function Se(t,e,i={}){await te(t,JSON.stringify(e,null,2)+`
|
|
164
|
+
`,i)}import{existsSync as yu,promises as Ae}from"fs";import R from"path";import Ng from"os";var en=".comet/config.yaml",bg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Io(t){try{return await Ae.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function kg(t){try{let e=await Ae.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function jt(t,e){let i=R.relative(t,e);return i===""||!R.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${R.sep}`)}async function It(t){let e=[],i=t;for(;!await Io(i);){let n=R.dirname(i);if(n===i)break;e.push(R.basename(i)),i=n}let r=await Ae.realpath(i);return R.resolve(r,...e.reverse())}async function jo(t){try{return(await Ae.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function $o(t){let e=R.resolve(t);try{(await Ae.stat(e)).isDirectory()||(e=R.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let i=e,r=R.resolve(Ng.homedir());for(;;){if(!(e===r&&i!==r)){let o=R.join(e,...en.split("/")),s=e===i||await kg(o);if(await Io(o)&&s)return e}if(await Io(R.join(e,".git")))return e;let a=R.dirname(e);if(a===e)return i;e=a}}function Oo(t){return lt(t)}async function Sg(t,e){let i=Oo(e),r=R.resolve(t,...i.split("/")),n=await Ae.realpath(t),a=await It(r);if(!jt(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function $t(t,e){let i=Oo(e),r=await Sg(t,i),n=R.join(r,"comet");if(await jo(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([It(r),It(n)]);if(!jt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=R.resolve(t),c=R.join(s,".comet","runtime","native");if(await jo(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,d]=await Promise.all([Ae.realpath(s),It(c)]);if(!jt(l,d))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:R.join(t,...en.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:R.join(n,"specs"),changesDir:R.join(n,"changes"),archiveDir:R.join(n,"archive"),runtimeDir:c,changesRuntimeDir:R.join(c,"changes"),locksDir:R.join(c,"locks"),transactionsDir:R.join(c,"transactions")}}async function Nu(t){await Promise.all([t.specsDir,t.changesDir,t.archiveDir].map(async e=>{await A(t.nativeRoot,e),await Ae.mkdir(e,{recursive:!0})})),await Promise.all([t.changesRuntimeDir,t.locksDir,t.transactionsDir].map(async e=>{await A(t.projectRoot,e),await Ae.mkdir(e,{recursive:!0})}))}function bu(t){if(!bg.test(t))throw new Error(`Invalid Native change name: ${t}`)}function dt(t,e){bu(e);let i=R.join(t.changesRuntimeDir,e);if(!L(t.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Eg(t,e){bu(e);let i=R.join(t.changesDir,e,"runtime");if(!L(t.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function ie(t,e){let i=dt(t,e);if(yu(i))return i;let r=Eg(t,e);return yu(r)?r:i}function fe(t,e){let i=R.resolve(e);if(L(t.runtimeDir,i))return t.runtimeDir;if(L(t.nativeRoot,i))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function L(t,e){return jt(R.resolve(t),R.resolve(e))}async function A(t,e){let i=R.resolve(t),r=R.resolve(e);if(!jt(i,r))throw new Error(`Path is outside the Native root: ${e}`);if(await jo(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([It(i),It(r)]);if(!jt(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return r}var tn=Ur;function ku(t="docs",e="en"){return Kr(t,e)}async function X(t){let e=(await Ro(t))?.config??null;return e?.native?e:null}async function rn(t){let e=await X(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function _i(t,e,i={}){let r=await Ci(t,{allowPartialProject:!0}),n=Ei(r.document?.value??{},e),a=Pg.join(t,...en.split("/"));await te(a,Si(n,e.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:t,beforeCommit:async()=>{await i.beforeCommit?.(),await Ao(t,r.identity)}})}function Su(t){let e={schema:"comet.native.continuation.v2",skill:"comet-native",change:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,inputOptions:[]},i=r=>({kind:r,candidateId:t.builder_handoff?.candidate_id??null,iteration:t.loop.iteration,attempt:t.loop.attempt});if(t.status==="done")return{...e,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:i("none")};if(t.status==="await-user")return t.phase==="verify"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass"?{...e,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:["comet","native","next",t.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")}:t.phase==="verify"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.next_action==="confirm-verifier-unavailable"?{...e,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",t.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")}:t.phase==="verify"&&t.loop.next_action==="resolve-verifier-blocker"?{...e,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:["comet","native","next",t.name,"--summary","<summary>","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:i("none")}:t.phase==="verify"&&t.loop.next_action==="await-user"?{...e,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",t.name,"--return-to-build","--summary","<summary>"],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:i("none")}:{...e,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:i("none")};if(t.status==="blocked"){let r=t.blockers.some(({resolution_action:n})=>n==="retry-verifier");return{...e,disposition:"blocked",action:r?"retry-verifier":"none",commandArgs:r?["comet","native","next",t.name,"--retry-verifier","--summary","<summary>"]:null,requiredInputs:r?["summary"]:["repair-runtime"],inputOptions:r?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:i(r?"retry-verifier":"none")}}if(t.phase==="shape")return{...e,disposition:"continue",action:"confirm-shape",commandArgs:["comet","native","next",t.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")};if(t.phase==="build")return{...e,disposition:"continue",action:t.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[]}}],runnerAction:i("builder-handoff")};if(t.phase==="verify"){let r=t.loop.next_action==="await-verifier-result";return{...e,disposition:"continue",action:r?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:[r?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:r?[{kind:"verifier-response",response:{kind:"request-checks",iteration:t.loop.iteration,attempt:t.loop.attempt,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:t.loop.iteration,attempt:t.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:i(r?"await-verifier":"dispatch-verifier")}}return{...e,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:i("none")}}import{promises as tt}from"node:fs";import Vi from"node:path";import{execFileSync as xg}from"child_process";import Ti from"path";function Ye(t,e){return xg("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Cg(t,e){let i=Ti.normalize(t),r=Ti.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function re(t){try{let e=Ti.resolve(Ye(t,["rev-parse","--show-toplevel"])),r=Ye(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?Ti.resolve(r.slice(9)):e,a=null;try{a=Ye(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Cg(e,n),currentWorktreeRoot:e,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function nn(t){try{Ye(t,["rev-parse","--is-inside-work-tree"])}catch{return[]}return Ye(t,["worktree","list","--porcelain","-z"]).split("\0").filter(i=>i.startsWith("worktree ")).map(i=>Ti.resolve(i.slice(9)))}function Ii(t,e){try{return Ye(t,["check-ref-format","--branch",e]),Ye(t,["show-ref","--verify",`refs/heads/${e}`]),!0}catch{return!1}}function Ho(t,e){try{let i=Ye(t,["rev-parse","--verify",`${e}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as Tg}from"node:crypto";import{promises as he}from"node:fs";import ne from"node:path";import{TextDecoder as Ig}from"node:util";var Rg=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Ag=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function _g(t){return t.toLowerCase().startsWith(".env")}function ji(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>_g(r))?"environment-file":i.some(r=>Ag.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>Rg.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}var on=1024*1024;function Do(t,e){let i=ne.relative(t,e);return i===""||!ne.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ne.sep}`)}function jg(t){let e=ne.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ne.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),r=ji(t);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${t}`);return t}function $g(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function Og(t,e){return T({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function an(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return Y(i,r)?T(i,r):T(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Eu(t){let e=await he.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await he.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Hg(t,e){let i=ne.resolve(t),r=ne.resolve(e);if(!Do(i,r))throw new Error("Native artifact path is outside its root");let n=[await Eu(i)],a=i;for(let o of ne.relative(i,r).split(ne.sep).filter(Boolean)){a=ne.join(a,o);let s=await Eu(a);if(!Do(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Pu(t){for(let e of t){let i=await he.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Og(e,i)||await he.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function pe(t){let e=jg(t.ref),i=t.maxBytes===null?null:$g(t.maxBytes??on),r=ne.resolve(t.root,...e.split("/")),n=await Hg(t.root,ne.dirname(r));await t.hooks?.afterParentChainCaptured?.();let a=await he.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await he.realpath(r);if(!Do(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await he.open(r,"r");try{let[c,l,d]=await Promise.all([s.stat(),he.lstat(r),he.realpath(r)]);if(await Pu(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||d!==o||!an(a,c)||!an(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let u=[],f=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let k=i===null?p.length:i+1-f,S=await s.read(p,0,Math.min(p.length,k),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);u.push(Buffer.from(p.subarray(0,S.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[g,h,m]=await Promise.all([s.stat(),he.lstat(r),he.realpath(r)]);if(await Pu(n),!h.isFile()||h.isSymbolicLink()||m!==o||!an(c,g)||!an(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let y=Buffer.concat(u,f),N;try{N=new Ig("utf-8",{fatal:!0}).decode(y)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:f,hash:t.includeHash===!1?null:Tg("sha256").update(y).digest("hex"),text:N}}finally{await s.close()}}var ns=zi(wi(),1);import{promises as Cn}from"fs";import G from"path";import{promises as ey}from"fs";import ty from"path";import{AsyncLocalStorage as Dg}from"async_hooks";import{randomUUID as Ru}from"crypto";import{promises as ae}from"fs";import Au from"os";import F from"path";var xu=16*1024,_u=".coordinator",Bg=5e3,Cu=new Dg,sn=new Map;function Lg(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function Mg(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let i=t;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${e}`);return i}function Tu(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function Bo(t,e){let i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return Y(i,r)?T(i,r):T(i,r)&&t.size===e.size}function Lo(t,e){return Bo(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function _e(t){let e,i;try{let r=await _t(t,xu,{bigint:!0,label:"Native lock"});e=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof ue?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${xu} bytes: ${t}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:r}):new Error(`Native lock changed while reading: ${t}`,{cause:r}):r}return{file:t,owner:Mg(JSON.parse(e.toString("utf8")),t),identity:Tu(i)}}async function Fg(t){return(await _e(t))?.owner??null}function Iu(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==Au.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=Gg(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function Vg(t,e){try{await ae.lstat(e);return}catch(i){if(i.code!=="ENOENT")throw i}try{await ae.rename(t,e)}catch(i){if(i.code!=="ENOENT")throw i}}async function Mo(t,e){let i=await _e(t.file);if(!i)return"missing";if(i.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Lo(i.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await ae.mkdir(e,{recursive:!0});let r=F.join(e,`${F.basename(t.file)}.${t.owner.id}.${Ru()}.removed`);try{await ae.rename(t.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await _e(r);if(!n||n.owner.id!==t.owner.id||!Bo(n.identity,t.identity))throw await Vg(r,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await ae.rm(r,{force:!0}),"removed"}function ju(t){return{id:Ru(),pid:process.pid,hostname:Au.hostname(),createdAt:new Date().toISOString(),operation:t}}async function $u(t,e){let i;try{i=await ae.open(t,"wx")}catch(r){if(r.code==="EEXIST"){let n=await Fg(t);throw new Error(`Native lock is already held: ${t}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(e,null,2)+`
|
|
165
|
+
`,"utf8"),await i.sync(),Tu(await i.stat({bigint:!0}))}finally{await i.close()}}async function qg(t,e){let i=await A(t.runtimeDir,t.locksDir);await ae.mkdir(i,{recursive:!0});let r=await A(t.runtimeDir,F.join(i,_u));await ae.mkdir(r,{recursive:!0});let n=ju(e),a=F.join(r,`.${n.id}.tmp`),o=F.join(r,`${n.id}.claim`);try{let s=await $u(a,n);await ae.rename(a,o);let c=await _e(o);if(!c||!Bo(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await ae.rm(a,{force:!0})}}async function Wg(t){let e=F.dirname(t.file),i=!1,r=F.basename(t.file);for(let n of await ae.readdir(e,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=F.join(e,n.name);if(F.resolve(a)!==F.resolve(t.file))try{let o=await _e(a),s=Iu(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Mo(o,e);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function Ou(t){let e=await _e(t.file);if(e){if(e.owner.id!==t.owner.id||!Lo(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await Mo(e,F.dirname(t.file))}}async function zg(t,e){let i=Date.now()+Bg;for(;;){let r=await qg(t,e);if(!await Wg(r))return r;if(await Ou(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function Jg(t){let e=sn.get(t)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=e.then(()=>r);return sn.set(t,n),await e,()=>{i(),sn.get(t)===n&&sn.delete(t)}}async function Hu(t,e,i){let r=F.resolve(t.locksDir),n=Cu.getStore();if(n?.has(r))return i();let a=await Jg(r);try{let o=await zg(t,e),s=new Map(n??[]);return s.set(r,o),await Cu.run(s,async()=>{try{return await i()}finally{await Ou(o)}})}finally{a()}}async function cn(t,e,i){return Hu(t,`acquire ${e}`,async()=>{let r=await A(t.runtimeDir,t.locksDir);await ae.mkdir(r,{recursive:!0});let n=await A(t.runtimeDir,F.join(r,Lg(e))),a=ju(i),o=await $u(n,a);return{file:n,nativeRoot:t.runtimeDir,locksDir:r,owner:a,identity:o}})}async function ln(t){await _e(t.file)&&await Hu({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${F.basename(t.file)}`,async()=>{let e=await _e(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Lo(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let i=F.join(t.locksDir,_u);await Mo(e,i)})}function Gg(t){try{return process.kill(t,0),!0}catch(e){let i=e.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Du(t){return Iu(await _e(t))}import Rw from"node:path";import{createHash as Ug}from"crypto";function me(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function Kg(t,e){e.has(t)&&me("cyclic structures are not supported"),e.add(t);try{let i=Object.keys(t);for(let r=0;r<t.length;r+=1)Object.prototype.hasOwnProperty.call(t,r)||me("sparse arrays are not supported");return(i.length!==t.length||i.some((r,n)=>r!==String(n)))&&me("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&me("symbol properties are not supported"),`[${t.map(r=>Fo(r,e)).join(",")}]`}finally{e.delete(t)}}function Yg(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&me("only plain objects are supported"),e.has(t)&&me("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&me("symbol properties are not supported"),e.add(t);try{let r=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&me("accessor properties are not supported"),`${JSON.stringify(o)}:${Fo(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Fo(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||me("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?Kg(t,e):Yg(t,e);case"bigint":case"function":case"symbol":case"undefined":return me(`${typeof t} values are not supported`)}return me("unsupported value type")}function Vo(t){return Fo(t,new Set)}function ve(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return Ug("sha256").update(`${t}
|
|
166
|
+
${Vo(e)}`).digest("hex")}var lE=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Bu=Object.freeze({maxCriteria:1024});var un=zi(wi(),1);import{promises as ew}from"node:fs";var Ot="comet.native.v4",$i="comet.native.local-execution.v4";function qo(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var tw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,iw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rw=/^A[1-9][0-9]*$/u,nw=new Set(["schema","name","language","phase","status","state_version","brief","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]);function z(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function J(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function M(t,e,i){if(typeof t!="string"||!i?.empty&&t.length===0)throw new Error(`${e} must be ${i?.empty?"a string":"a non-empty string"}`);return t}function Wo(t,e){return t===null?null:M(t,e)}function Ht(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function I(t,e,i=0){if(!Number.isSafeInteger(t)||t<i)throw new Error(`${e} must be a safe integer greater than or equal to ${i}`);return t}function aw(t,e){return t===null?null:I(t,e,Number.MIN_SAFE_INTEGER)}function D(t,e,i){if(typeof t!="string"||!e.includes(t))throw new Error(`${i} must be one of: ${e.join(", ")}`);return t}function Ee(t,e,i){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((r,n)=>i(r,n))}function dn(t,e){return Ee(t,e,(i,r)=>M(i,`${e}[${r}]`))}function ft(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function Dt(t,e){let i=M(t,e);if(Number.isNaN(Date.parse(i)))throw new Error(`${e} must be an ISO date or timestamp`);return i}function zo(t,e,i=!1){let r=M(t,e);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return r}function ge(t,e){let i=z(t,e);return J(i,new Set(["text","truncated"]),e),{text:M(i.text,`${e}.text`,{empty:!0}),truncated:Ht(i.truncated,`${e}.truncated`)}}function ow(t,e){let i=`Native spec_changes[${e}]`,r=z(t,i);J(r,new Set(["capability","operation","source"]),i);let n=M(r.capability,`${i}.capability`);if(!iw.test(n))throw new Error(`${i}.capability is invalid`);let a=D(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:zo(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function sw(t){let e="Native workspace",i=z(t,e);J(i,new Set(["isolation","change_branch","target_branch","finish"]),e);let r=D(i.isolation,["current","branch","worktree"],`${e}.isolation`),n=Wo(i.change_branch,`${e}.change_branch`),a=Wo(i.target_branch,`${e}.target_branch`),o=i.finish===null?null:D(i.finish,["merge","push","pull-request","keep"],`${e}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function cw(t){let e="Native loop",i=z(t,e);J(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),e);let r=dn(i.previous_unresolved_ids,`${e}.previous_unresolved_ids`);return ft(r,`${e}.previous_unresolved_ids`),{stage:D(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:I(i.goal_cycle,`${e}.goal_cycle`,1),iteration:I(i.iteration,`${e}.iteration`),attempt:I(i.attempt,`${e}.attempt`),retry_epoch:I(i.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:I(i.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:I(i.no_progress_count,`${e}.no_progress_count`),execution_failure_count:I(i.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:r,next_action:Wo(i.next_action,`${e}.next_action`)}}function lw(t,e){let i=`Native acceptance[${e}]`,r=z(t,i);J(r,new Set(["id","source","text","result","reason"]),i);let n=M(r.id,`${i}.id`);if(!rw.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:zo(r.source,`${i}.source`),text:M(r.text,`${i}.text`),result:D(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:ge(r.reason,`${i}.reason`)}}function uw(t,e){let i=`Native builder_handoff.checks[${e}]`,r=z(t,i);return J(r,new Set(["name","result","note"]),i),{name:ge(r.name,`${i}.name`),result:D(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:ge(r.note,`${i}.note`)}}function dw(t){let e="Native builder_handoff",i=z(t,e);J(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),e);let r=dn(i.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);return ft(r,`${e}.addressed_acceptance_ids`),{candidate_id:M(i.candidate_id,`${e}.candidate_id`),identity_provider:M(i.identity_provider,`${e}.identity_provider`),builder_execution_ref:M(i.builder_execution_ref,`${e}.builder_execution_ref`),iteration:I(i.iteration,`${e}.iteration`,1),summary:ge(i.summary,`${e}.summary`),addressed_acceptance_ids:r,checks:Ee(i.checks,`${e}.checks`,uw),checks_truncated:Ht(i.checks_truncated,`${e}.checks_truncated`),known_limits:Ee(i.known_limits,`${e}.known_limits`,(n,a)=>ge(n,`${e}.known_limits[${a}]`)),known_limits_truncated:Ht(i.known_limits_truncated,`${e}.known_limits_truncated`),submitted_at:Dt(i.submitted_at,`${e}.submitted_at`)}}function fw(t,e){let i=`Native blockers[${e}]`,r=z(t,i);J(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=dn(r.acceptance_ids,`${i}.acceptance_ids`);return ft(n,`${i}.acceptance_ids`),{owner:D(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:ge(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:D(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function hw(t,e){let i=`Native verification.checks[${e}]`,r=z(t,i);return J(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:M(r.id,`${i}.id`),name:ge(r.name,`${i}.name`),argv_display:Ee(r.argv_display,`${i}.argv_display`,(n,a)=>ge(n,`${i}.argv_display[${a}]`)),argv_truncated:Ht(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:zo(r.cwd_ref,`${i}.cwd_ref`,!0),status:D(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:aw(r.exit_code,`${i}.exit_code`),duration_ms:I(r.duration_ms,`${i}.duration_ms`)}}function pw(t){let e="Native verification",i=z(t,e);J(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let r=Ee(i.checks,`${e}.checks`,hw);ft(r.map(a=>a.id),`${e}.checks IDs`);let n=M(i.identity_provider,`${e}.identity_provider`);return{candidate_id:M(i.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:M(i.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:I(i.iteration,`${e}.iteration`,1),attempt:I(i.attempt,`${e}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":D(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:D(i.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:r,summary:ge(i.summary,`${e}.summary`),risks:Ee(i.risks,`${e}.risks`,(a,o)=>ge(a,`${e}.risks[${o}]`)),risks_truncated:Ht(i.risks_truncated,`${e}.risks_truncated`),completed_at:Dt(i.completed_at,`${e}.completed_at`)}}function mw(t,e){let i=`Native history[${e}]`,r=z(t,i);J(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=dn(r.unresolved_ids,`${i}.unresolved_ids`);return ft(n,`${i}.unresolved_ids`),{goal_cycle:I(r.goal_cycle,`${i}.goal_cycle`,1),iteration:I(r.iteration,`${i}.iteration`),attempt:I(r.attempt,`${i}.attempt`),outcome:D(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:ge(r.summary,`${i}.summary`),completed_at:Dt(r.completed_at,`${i}.completed_at`)}}function vw(t){let e="Native history_overflow.outcome_counts",i=z(t,e),r=["pass","fail","blocked","execution-error","recovery"];return J(i,new Set(r),e),{pass:I(i.pass,`${e}.pass`),fail:I(i.fail,`${e}.fail`),blocked:I(i.blocked,`${e}.blocked`),"execution-error":I(i["execution-error"],`${e}.execution-error`),recovery:I(i.recovery,`${e}.recovery`)}}function gw(t){let e="Native history_overflow",i=z(t,e);J(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let r=I(i.dropped_entries,`${e}.dropped_entries`),n=i.first_dropped_at===null?null:Dt(i.first_dropped_at,`${e}.first_dropped_at`),a=i.last_dropped_at===null?null:Dt(i.last_dropped_at,`${e}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=vw(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function ww(t){let e=new Set(t.acceptance.map(i=>i.id));for(let i of t.loop.previous_unresolved_ids)if(!e.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of t.blockers)for(let r of i.acceptance_ids)if(!e.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(t.builder_handoff&&!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,n=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function yw(t){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let i=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(i!==null&&t.loop.stage!==i)throw new Error(`Native status ${t.status} requires loop stage ${i}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function Oi(t){let e=z(t,"Native portable state");if(J(e,nw,"Native portable state"),e.schema!==Ot)throw new Error(`Native portable state schema must be ${Ot}`);let i=M(e.name,"Native state name");if(!tw.test(i))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=Ee(e.spec_changes,"Native spec_changes",ow);ft(r.map(s=>s.capability),"Native spec change capabilities");let n=Ee(e.acceptance,"Native acceptance",lw);ft(n.map(s=>s.id),"Native acceptance IDs");let a=Ee(e.history,"Native history",mw);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Ot,name:i,language:D(e.language,["en","zh-CN"],"Native state language"),phase:D(e.phase,["shape","build","verify","archive"],"Native state phase"),status:D(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:I(e.state_version,"Native state_version",1),brief:"brief.md",spec_changes:r,workspace:sw(e.workspace),loop:cw(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:dw(e.builder_handoff),blockers:Ee(e.blockers,"Native blockers",fw),verification:e.verification===null?null:pw(e.verification),history:a,history_overflow:gw(e.history_overflow),verification_result:D(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:D(e.verification_report,["verification.md"],"Native verification_report"),archived:Ht(e.archived,"Native archived"),created_at:Dt(e.created_at,"Native created_at")};return ww(o),yw(o),o}function Mu(t){let e=t.createdAt instanceof Date?t.createdAt.toISOString():t.createdAt??new Date().toISOString();return Oi({schema:Ot,name:t.name,language:t.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:t.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:t.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:qo(),verification_result:"pending",verification_report:null,archived:!1,created_at:e})}function Nw(t,e){let i=(0,un.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${e} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Fu(t){let e=await ew.readFile(t,"utf8");return Oi(Nw(e,"Native portable state"))}async function Vu(t,e,i={}){let r=Oi(e);await te(t,(0,un.stringify)(r),i)}var Te="comet.native.v3",Ie="comet.native.v2",je="comet.native.v1";var qu="comet.native.portable-migration.v1",bw=new Set(["schema","id","change","fromSchema","status","createdAt"]),kw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Sw=/^[a-z0-9][a-z0-9-]{7,127}$/u,Ew=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Pw=new Set([je,Ie,Te]);function xw(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Cw(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let i=new Date(t);if(Number.isNaN(i.valueOf())||i.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function zu(t){let e=xw(t,"Native portable migration transaction"),i=Object.keys(e).filter(r=>!bw.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(e.schema!==qu)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!Sw.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!kw.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!Pw.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!Ew.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:qu,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:Cw(e.createdAt,"Native portable migration transaction createdAt")}}var Ju="comet.native.archive-transaction.v4",Gu="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Aw=new RegExp(`^portable-archive-(${Gu})\\.json$`,"u"),_w=new RegExp(`^portable-migration-(${Gu})\\.json$`,"u"),Tw=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Iw=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jw=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),$w=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Ow=new Set(["capability","operation","source","content"]),Uu=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Ku(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Yu(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(t).length!==e.size)throw new Error(`${i} fields are invalid`)}function Hw(t,e){let i=`Native portable Archive spec_changes[${e}]`,r=Ku(t,i);if(Yu(r,Ow,i),typeof r.capability!="string"||!Uu.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function Dw(t){let e=Ku(t,"Native portable Archive transaction");if(Yu(e,$w,"Native portable Archive transaction"),e.schema!==Ju)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!Tw.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!Uu.test(e.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(e.start_state_version)||Number(e.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof e.archive_ref!="string"||!Iw.test(e.archive_ref)||!e.archive_ref.endsWith(`-${e.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof e.status!="string"||!jw.has(e.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=e.spec_changes.map(Hw);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(e.next_spec_index)||Number(e.next_spec_index)<0||Number(e.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof e.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(e.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==e.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Ju,id:e.id,change:e.change,start_state_version:Number(e.start_state_version),archive_ref:e.archive_ref,status:e.status,next_spec_index:Number(e.next_spec_index),spec_changes:i,created_at:e.created_at}}function Jo(t){let e=Aw.exec(t);if(e)return{kind:"archive",change:e[1]};let i=_w.exec(t);return i?{kind:"migration",change:i[1]}:null}async function Xu(t,e){let i=Jo(e);if(!i)return null;let r=await pe({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Rw.join(t.transactionsDir,e);if(i.kind==="archive"){let s=Dw(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=zu(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}function Qu(t){return t.kind==="archive"||t.journal.status!=="committed"}import Oe from"path";import{TextDecoder as Ww}from"util";import{createHash as Bw}from"node:crypto";import{constants as mn,promises as Q}from"node:fs";import we from"node:path";import{TextDecoder as Lw}from"node:util";function gn(t,e){let i=we.relative(t,e);return i===""||!we.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${we.sep}`)}function Zu(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function Mw(t,e){return T({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Fw(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function vn(t,e){return T({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Go(t,e){let i=await Q.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await Q.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function ed(t,e,i){let r=we.resolve(t),n=we.resolve(e);if(!gn(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Go(r,i)],o=r;for(let s of we.relative(r,n).split(we.sep).filter(Boolean)){await $e(a,i),o=we.join(o,s);let c=await Go(o,i);if(!gn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await $e(a,i),a}async function $e(t,e){for(let i of t){let r=await Q.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Mw(i,r)||await Q.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function Vw(t,e,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-n,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>e)throw new Error(`${i} exceeds ${e} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function ht(t){let e=Zu(t.maxBytes),i=we.resolve(t.file),r=await ed(t.root,we.dirname(i),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(d=>Go(we.resolve(d),t.label)));await t.hooks?.afterParentChainCaptured?.(),await $e(r,t.label);let a=await Q.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=Fw(a),s=await Q.realpath(i);if(!gn(r[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(d=>gn(d.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?mn.O_RDONLY:mn.O_RDONLY|mn.O_NOFOLLOW|mn.O_NONBLOCK,l=await Q.open(i,c);try{let d=await l.stat();await t.hooks?.afterOpen?.();let[u,f]=await Promise.all([Q.lstat(i),Q.realpath(i)]);if(await $e(r,t.label),await $e(n,t.label),!d.isFile()||!u.isFile()||u.isSymbolicLink()||f!==s||!vn(o,d)||!vn(o,u))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let p=await Vw(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[g,h,m]=await Promise.all([l.stat(),Q.lstat(i),Q.realpath(i)]);if(await $e(r,t.label),await $e(n,t.label),!h.isFile()||h.isSymbolicLink()||m!==s||!vn(o,g)||!vn(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:p,hash:Bw("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function td(t){let e=await ht(t),i;try{i=new Lw("utf-8",{fatal:!0}).decode(e.bytes)}catch(r){throw new Error(`${t.label} is not valid UTF-8`,{cause:r})}return{...e,text:i}}async function Hi(t){let e=await ed(t.root,t.directory,t.label),i;if(t.maxEntries===void 0)i=await Q.readdir(t.directory,{withFileTypes:!0});else{let r=Zu(t.maxEntries);i=[];let n=await Q.opendir(t.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${t.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await $e(e,t.label),{entries:i,verify:()=>$e(e,t.label)}}var zw=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Jw=new Set(["id","type","source","target","staged","backup"]),Gw=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Uw=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var nd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Kw=256*1024,UE=1024*1024,KE=16*1024;var YE=64*1024*1024;var Yw=new Ww("utf-8",{fatal:!0});function yn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Nn(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function ad(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function Uo(t,e){if(typeof t!="string"||t.length===0||Oe.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function wn(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function id(t,e){if(Uo(t,e),t.includes("\\")||t!==Oe.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function Xw(t,e){let i=yn(t,`transaction operations[${e}]`);if(Nn(i,Jw,`transaction operations[${e}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${e}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Uo(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Uo(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function od(t){let e=yn(t,"Native Archive transaction journal");if(Nn(e,Gw,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!nd.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!ad(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(wn(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=e.operations.map((s,c)=>{let l=yn(s,`Archive transaction operations[${c}]`);if(Nn(l,Uw,`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`);id(l.target,`Archive transaction operation ${l.id} target`);for(let d of["source","staged","backup"])l[d]!==void 0&&id(l[d],`Archive transaction operation ${l.id} ${d}`);if(l.expectedTargetHash!==null&&wn(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(wn(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`);wn(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${e.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:i}}function Qw(t){let e=yn(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return od(e);if(Nn(e,zw,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!nd.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!Oe.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!Oe.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!ad(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let i=e.operations.map(Xw),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:i}}function Zw(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return Oe.join(t.transactionsDir,e)}function sd(t,e){let i=Zw(t,e);return{directory:i,journal:Oe.join(i,"transaction.json"),events:Oe.join(i,"events.jsonl"),staged:Oe.join(i,"staged"),backups:Oe.join(i,"backups")}}async function Ko(t,e){let i=sd(t,e);return await Promise.all(Object.values(i).map(r=>A(t.runtimeDir,r))),i}async function Yo(t,e,i={}){let r=await Ko(t,e),n=await ht({root:t.runtimeDir,file:r.journal,maxBytes:Kw,label:`Native transaction journal ${e}`,hooks:i.hooks}),a=JSON.parse(Yw.decode(n.bytes)),o=Qw(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function iy(t,e,i){let r;try{r=await ey.readdir(t.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Yo(t,n.name);if(a.id!==e&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Jo(n.name))try{let a=await Xu(t,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Qu(a))return!0}catch{return!0}return!1}async function ry(t,e){let i=Date.now()+5e3,r=ty.join(t.locksDir,"root-move.lock");for(;;)try{return await cn(t,"root-move",e)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Du(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function ye(t,e,i,r){let n=await ry(t,e);try{if(await rn(t.projectRoot),await iy(t,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await ln(n)}}import Qo from"path";import{createHash as ny}from"crypto";function Z(t){return ny("sha256").update(t).digest("hex")}var vP={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},oy=1e3,sy=8*1024*1024,cy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ly=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),uy=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),dy=new Set(["schema","include","exclude","hash"]),fy=new Set(["provider","gitSelection","physicalSelection","projection"]),hy=new Set(["provider","selection"]),py=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),my=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),vy=new Set(["schema","status","before","after"]),gy=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),wy=new Set(["path","hash","size","type","gitObjectId"]),yy=new Set(["path","size","type","reason"]),Ny=new Set(["ref","hash","count"]),by=new Set(["change-created","legacy-migration","explicit"]),ky=new Set(["file","directory","other"]),Sy=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"]),kn=/^[a-f0-9]{64}$/u,Ey=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var gP=64*1024,wP=64*1024;var yP={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},NP={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function bn(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}var bP=(1n<<256n)-1n;function Py(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function xy(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
167
|
+
`)}function Cy(t,e){return Z(`comet.native.snapshot-policy.v1
|
|
168
|
+
${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function Xo(t,e,i){let r=new Set(e),n=[...e];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=t[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function Ry(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function cd(t){let e=tn(t,"Native snapshot pattern"),i=[];for(let r=0;r<e.length;r+=1){let n=e[r];n==="*"&&e[r+1]==="*"?(r+=1,e[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?Ry(n):void 0;if(a&&!a())return!1;let o=Xo(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let d=i[l];d&&(d.kind==="literal"&&d.value===s||d.kind==="question"&&s!=="/"?c.add(l+1):d.kind==="star"&&s!=="/"||d.kind==="globstar"?c.add(l):d.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Xo(i,c,a),o===null||o.size===0)return!1}return Xo(i,o,a)?.has(i.length)??!1}}function Ay(t){if(t===void 0)return;let e=[...new Set(t.include.map(n=>tn(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(t.exclude.map(n=>tn(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let r=Cy(e,i);if("hash"in t&&t.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:i,hash:r},includeMatchers:e.map(cd),excludeMatchers:i.map(cd),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function oe(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function se(t,e,i){let r=Object.keys(t).find(n=>!e.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Lt(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Pe(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function dd(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let i=Qo.posix.normalize(t);if(i!==t||Qo.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function _y(t,e){let i=oe(t,`Native snapshot entry ${e}`);se(i,wy,`Native snapshot entry ${e}`);let r=dd(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!kn.test(i.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let n={path:r,hash:i.hash,size:Pe(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Ey.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function Ty(t,e){let i=oe(t,`Native snapshot omission ${e}`);if(se(i,yy,`Native snapshot omission ${e}`),!ky.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!Sy.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:dd(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:Pe(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function Iy(t){let e=oe(t,"Native snapshot omission overflow");if(se(e,Ny,"Native snapshot omission overflow"),typeof e.hash!="string"||!kn.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:e.hash,count:Lt(e.count,"Native snapshot omission overflow count")}}function Bt(t,e){let i=oe(t,e);if(se(i,my,e),typeof i.hash!="string"||!kn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let r=Pe(i.recordCount,`${e} recordCount`),n=Pe(i.storedRecordCount,`${e} storedRecordCount`),a=Pe(i.stdoutBytes,`${e} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function ld(t){let e=oe(t,"Native Git selection evidence");if(se(e,py,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=Bt(e.stageBefore,"Native Git selection stageBefore"),r=Bt(e.combined,"Native Git selection combined"),n=Bt(e.stageAfter,"Native Git selection stageAfter"),a=Bt(e.finalStageBefore,"Native Git selection finalStageBefore"),o=Bt(e.finalCombined,"Native Git selection finalCombined"),s=Bt(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(u=>u.overflow),l=!bn(i,n)||!bn(n,a)||!bn(r,o)||!bn(a,s),d=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==d)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:d,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function ud(t,e){let i=oe(t,e);if(se(i,gy,e),typeof i.hash!="string"||!kn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${e} flags are invalid`);let r=Pe(i.visitedNodeCount,`${e} visitedNodeCount`),n=Pe(i.recordCount,`${e} recordCount`),a=Pe(i.storedRecordCount,`${e} storedRecordCount`),o=Pe(i.encodedBytes,`${e} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function jy(t){let e=oe(t,"Native physical selection evidence");if(se(e,vy,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=ud(e.before,"Native physical selection before"),r=ud(e.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!Py(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function fd(t){let e=oe(t,"Native content snapshot manifest");if(se(e,ly,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!by.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let v=oe(e.capture,"Native content snapshot capture");if(se(v,fy,"Native content snapshot capture"),v.provider!=="git"&&v.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=v.gitSelection===void 0?void 0:ld(v.gitSelection),b=v.physicalSelection===void 0?void 0:jy(v.physicalSelection),_=null;if(v.projection!==void 0){let U=oe(v.projection,"Native content snapshot projection");if(se(U,hy,"Native content snapshot projection"),U.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");_={provider:"git",...U.selection===void 0?{}:{selection:ld(U.selection)}}}if(v.provider==="git"){if(b||_)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&_)throw new Error("Native physical-tree capture cannot combine selection and projection");i=_?{provider:"physical-tree",projection:_}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=oe(e.limits,"Native content snapshot limits");se(r,uy,"Native content snapshot limits");let n={maxFiles:Lt(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Lt(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Lt(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Lt(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:Lt(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let v=oe(e.policy,"Native snapshot policy");if(se(v,dy,"Native snapshot policy"),v.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(v.include)||!Array.isArray(v.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Ay({include:v.include,exclude:v.exclude,hash:v.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(_y),s=e.omitted.map(Ty),c=Pe(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:Iy(e.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(v=>v.size>n.maxFileBytes)||o.reduce((v,x)=>v+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(v=>v.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>oy||c<s.length)throw new Error("Native content snapshot omission count is invalid");let d=c-s.length;if(d===0&&l||d>0&&l?.count!==d)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let u=s.filter(v=>v.reason==="git-enumeration-limit"),f=s.filter(v=>v.reason==="git-selection-changed");for(let v of[...u,...f])if(v.path!=="."||v.size!==null||v.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(u.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,g=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(g!==(u.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(v=>v.reason==="physical-enumeration-limit"),y=s.filter(v=>v.reason==="physical-selection-changed");for(let v of[...m,...y])if(v.path!=="."||v.size!==null||v.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=i?.physicalSelection,k=N?.status==="overflow"||N?.status==="overflow-and-changed",S=N?.status==="changed"||N?.status==="overflow-and-changed";if(k!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:e.origin,...i?{capture:i}:{},createdAt:e.createdAt,complete:e.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(xy(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function $y(t,e){if(!cy.test(e))throw new Error(`Invalid Native change name: ${e}`);return Qo.join(ie(t,e),"baseline-manifest.json")}async function hd(t,e){let i=$y(t,e),r=fe(t,i);await A(r,i);try{let n=await td({root:r,file:i,maxBytes:sy,label:"Native baseline snapshot manifest"});return fd(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var My=zi(wi(),1);var DP=4*1024*1024;var Ax=256*1024;var Vx={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import{createHash as Vy}from"node:crypto";import{promises as Sn}from"node:fs";import Xe from"node:path";var Di=/^[a-f0-9]{64}$/u,md=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,qy=16*1024,es=process.platform;function wd(t,e){let i=Xe.relative(t,e);return Xe.isAbsolute(i)||i===".."||i.startsWith(`..${Xe.sep}`)?null:i.replaceAll("\\","/")||"."}function yd(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function Nd(t,e){if(t.length===0||yd(t)||t.includes("\\")||Xe.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let i=Xe.posix.normalize(t);if(i!==t||i===".."||i.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return i}function ts(t,e){return Vy("sha256").update(`${t}
|
|
169
|
+
${e}`).digest("hex")}async function vd(t,e){let i=await Sn.realpath(e),r=await Sn.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=es==="win32"?Xe.normalize(i).toLowerCase():i;return ts(t,`${n}
|
|
170
|
+
${r.dev}
|
|
171
|
+
${r.ino}
|
|
172
|
+
${r.birthtimeMs}`)}async function gd(t,e){let i=await Sn.realpath(e),r=await Sn.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=es==="win32"?Xe.normalize(i).toLowerCase():i;return ts(t,n)}function Wy(t){if(typeof t!="string")throw new Error("Native workspace capturedAt is invalid");let e=new Date(t);if(!Number.isFinite(e.getTime())||e.toISOString()!==t)throw new Error("Native workspace capturedAt is invalid");return t}function Zo(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||yd(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function bd(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Zo(t.changeBranch,"Native workspace change branch"),Zo(t.targetBranch,"Native workspace target branch"),(t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function zy(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace Git provenance must be an object");let e=t,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(e).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(e.provider!=="git"||typeof e.baseCommit!="string"||!md.test(e.baseCommit)||typeof e.targetCommit!="string"||!md.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");Zo(e.targetBranch,"Native workspace Git target branch")}function En(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace identity must be an object");let e=t,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(e).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(e.schema!=="comet.native.workspace.v2"&&e.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(e.capturedRevision)||e.capturedRevision<1||typeof e.nativeRootRef!="string"||!Di.test(String(e.projectRootId))||!Di.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");Wy(e.capturedAt),Nd(e.nativeRootRef,"Native workspace root ref");let n=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Di.test(String(e.projectRootPathId))||a&&!Di.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!Di.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&zy(e.git),e.schema==="comet.native.workspace.v2"){if(e.isolation!==void 0||e.changeBranch!==void 0||e.targetBranch!==void 0||e.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof e.isolation!="string"||e.changeBranch===void 0||e.targetBranch===void 0||e.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(bd(e),e.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(e.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function Jy(t,e){return Xe.join(ie(t,e),"workspace.json")}function Gy(t,e){let i=Jy(t,e),r=fe(t,i),n=wd(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Nd(n,"Native workspace file ref")}}async function Uy(t,e){try{let i=Gy(t,e),r=await pe({root:i.root,ref:i.ref,maxBytes:qy});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ky(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=wd(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let i=re(t.paths.projectRoot),r=i.isGitWorktree?Ho(t.paths.projectRoot,"HEAD"):null,n=t.binding?.targetBranch??i.currentBranch,a=n==null?null:Ho(t.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,d]=await Promise.all([vd("comet.native.workspace-project-root.v2",t.paths.projectRoot),vd("comet.native.workspace-native-root.v2",t.paths.nativeRoot),gd("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),gd("comet.native.workspace-native-root-path.v2",t.paths.nativeRoot)]),u=(t.now??new Date).toISOString();if(t.finish&&!t.binding)throw new Error("Native workspace finish requires a workspace binding");t.binding&&bd(t.binding);let f={capturedAt:u,capturedRevision:t.revision,nativeRootRef:e,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:d,...o?{git:o}:{},...t.sessionId?{sessionHash:ts("comet.native.workspace-session.v2",`${s}
|
|
173
|
+
${c}
|
|
174
|
+
${t.sessionId}`)}:{}},p=t.binding?{schema:"comet.native.workspace.v3",...f,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...f};return En(p),p}async function Mt(t,e){let i=await Uy(t,e);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(En(i),i)}async function Pn(t){En(t.identity);let e=await Ky({paths:t.paths,name:"workspace-advisory",revision:t.identity.capturedRevision}),i=[],r=[];return e.nativeRootRef!==t.identity.nativeRootRef&&i.push("native-root-ref"),t.identity.projectRootPathId&&t.identity.nativeRootPathId?(e.projectRootPathId!==t.identity.projectRootPathId&&i.push("project-root-path"),e.nativeRootPathId!==t.identity.nativeRootPathId&&i.push("native-root-path")):(e.projectRootId!==t.identity.projectRootId&&i.push("project-root-legacy-identity"),e.nativeRootId!==t.identity.nativeRootId&&i.push("native-root-legacy-identity")),es==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function xn(t){if(En(t.identity),t.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Pn(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=re(t.paths.projectRoot);return t.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==t.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${t.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:t.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function kd(t,e){let i=await Mt(t,e);if(i===null)return null;let r=await xn({paths:t,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var Pd=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Xy=new Set(Pd),xd=new Set([...Pd,"minimum_runtime_version","revision"]),Qy=new Set([...xd,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Zy=new Set(["capability","operation","source","base_hash"]),eN=new Set(["shape","build","verify","archive"]),tN=new Set(["implicit","confirmed"]),iN=new Set(["pending","pass","fail"]),He="comet-state.yaml",rs=/^[a-f0-9]{64}$/u,Cd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rN=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Rn=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},pt=class extends Error{constructor(i,r){super(i!==Te||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},An=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Ft=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},_n=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},xC=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
175
|
+
`);function Li(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Rd(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Tn(t){if(!Cd.test(t))throw new Error(`Invalid Native change name: ${t}`)}function nN(t){if(!Cd.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function Ad(t,e){if(t.length===0||G.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function aN(t,e){let i=Li(t,`spec_changes[${e}]`);if(Rd(i,Zy,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(nN(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&Ad(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!rs.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!rs.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function oN(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function as(t,e){if(Rd(t,e,He),typeof t.name!="string")throw new Error("Native change name is required");if(Tn(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!eN.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!tN.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(aN),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof t.verification_result!="string"||!iN.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&Ad(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!oN(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function fn(t){let e=Li(t,He);if(e.schema!==je)throw new Error(`Expected ${je}`);return{schema:je,...as(e,Xy)}}function Bi(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function is(t,e,i){if(t===null)return null;let r=typeof t=="string"?rN.exec(t):null;if(!r||r[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return t}function sN(t){if(t==null)return null;if(typeof t!="string"||!rs.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function cN(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function hn(t){let e=Li(t,He);if(e.schema!==Ie)throw new Error(`Expected ${Ie}`);if(Bi(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ie} minimum_runtime_version must be 2`);return{schema:Ie,minimum_runtime_version:2,revision:Bi(e.revision,"Native v2 revision"),...as(e,xd)}}function pn(t){let e=Li(t,He);if(e.schema!==Te){if(e.schema===je||e.schema===Ie){let o=e.schema===je?fn(e):hn(e);throw new Rn(o.name,o.schema)}throw new pt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Bi(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new pt(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let r=Bi(e.revision,"Native revision"),n=as(e,Qy),a=sN(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Te,minimum_runtime_version:3,revision:r,verification_protocol:cN(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:is(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:is(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:is(e.partial_allowance,"Native partial_allowance","allowances")}}function _d(t){let e=Li(t,He);if(e.schema===je){let n=fn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Te}`}}if(e.schema===Ie){let n=hn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Te}`}}if(e.schema!==Te){let n=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new pt(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let i=Bi(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new pt(e.schema,i).message};let r=pn(e);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function Ze(t,e){Tn(e);let i=G.join(t.changesDir,e);if(!L(t.changesDir,i))throw new Error("Native change path escaped");return i}async function os(t,e){let i=ie(t,e),r=G.join(i,"schema-migration.json");await A(L(t.runtimeDir,r)?t.runtimeDir:t.nativeRoot,r);try{return await Cn.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var lN=256*1024;async function Td(t,e=G.dirname(t)){let i=G.relative(e,t).split(G.sep).join("/"),r=await pe({root:e,ref:i,maxBytes:lN}),n=(0,ns.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${n.errors[0].message}`);return n.toJS()}async function uN(t,e){let i=G.join(Ze(t,e),He);await A(t.nativeRoot,i);let r=_d(await Td(i,t.nativeRoot));if(r.state&&r.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await os(t,e)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(r.status==="current"&&r.state&&await fN(t,r.state),r)}async function dN(t,e){let i=G.join(Ze(t,e),He);await A(t.nativeRoot,i);let r=_d(await Td(i,t.nativeRoot));if(r.state&&r.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return r}async function fN(t,e){if(await hd(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function et(t,e){let i=await uN(t,e);if(i.status==="migration-required")throw new Rn(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new pt(i.schema,i.minimumRuntimeVersion);return await kd(t,e),i.state}async function hN(t){let e;try{let r=await Hi({root:t.nativeRoot,directory:t.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await r.verify(),e=r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}return e.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort()}async function Id(t){let e=[];for(let i of await hN(t)){let r=await dN(t,i);if(!r.state){if(await Ed(t,i))continue;e.push(i);continue}if(r.state.archived)continue;let n=await Mt(t,i);if(!(!n&&await Ed(t,i))){if(n?.schema==="comet.native.workspace.v3"){if((await xn({paths:t,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await Pn({paths:t,identity:n})).state==="drifted")continue;e.push(i)}}return e}function Sd(t,e){let i=G.resolve(t),r=G.resolve(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function Ed(t,e){for(let i of nn(t.projectRoot))if(!Sd(i,t.projectRoot))try{let r=await X(i);if(!r)continue;let n=await $t(i,r.native.artifact_root),a=G.join(n.changesDir,e),o=G.join(a,"comet-state.yaml");try{let l=await Cn.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let d=await Cn.readFile(G.join(dt(n,e),"state.json"),"utf8"),u=JSON.parse(d);if(u.schema==="comet.native.local-execution.v4"&&typeof u.workspace?.projectRoot=="string"&&Sd(u.workspace.projectRoot,i))return!0;continue}}catch(l){l.code}await Cn.access(G.join(a,He));let s=await Mt(n,e);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await xn({paths:n,identity:s})).state==="aligned")return!0;continue}if((await Pn({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}var RC=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as yN}from"node:fs";import Fi from"node:path";function In(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function jn(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function xe(t,e,i=!1){if(typeof t!="string"||!i&&t.length===0)throw new Error(`${e} must be ${i?"a string":"a non-empty string"}`);return t}function jd(t,e){return t===null?null:xe(t,e)}function On(t,e,i=0){if(!Number.isSafeInteger(t)||t<i)throw new Error(`${e} must be a safe integer greater than or equal to ${i}`);return t}function NN(t,e){if(t===null)return null;if(!Number.isSafeInteger(t))throw new Error(`${e} must be null or a safe integer`);return t}function bN(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function $n(t,e,i){if(typeof t!="string"||!e.includes(t))throw new Error(`${i} must be one of: ${e.join(", ")}`);return t}function ss(t,e){if(t===null)return null;let i=xe(t,e);if(Number.isNaN(Date.parse(i)))throw new Error(`${e} must be an ISO timestamp`);return i}function cs(t,e){let i=xe(t,e);if(!Fi.isAbsolute(i))throw new Error(`${e} must be absolute`);return Fi.resolve(i)}function kN(t,e){let i=`Native local checks[${e}]`,r=In(t,i);if(jn(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,d)=>xe(l,`${i}.argv[${d}]`,!0)),a=$n(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=ss(r.startedAt,`${i}.startedAt`),s=ss(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=On(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:xe(r.id,`${i}.id`),name:xe(r.name,`${i}.name`),operationId:xe(r.operationId,`${i}.operationId`),status:a,repeatable:bN(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:On(r.executionCount,`${i}.executionCount`),argv:n,cwd:cs(r.cwd,`${i}.cwd`),exitCode:NN(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:xe(r.log,`${i}.log`)}}function $d(t){let e="Native local execution state",i=In(t,e);if(jn(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),e),i.schema!==$i)throw new Error(`Native local execution schema must be ${$i}`);let r=In(i.workspace,"Native local workspace");jn(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=In(i.execution,"Native local execution");jn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=ss(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:xe(o.operationId,"Native local execution.operationId"),stage:$n(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:$n(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:jd(o.executionId,"Native local execution.executionId"),status:$n(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:On(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(kN);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:$i,change:xe(i.change,"Native local change"),basedOnStateVersion:On(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:cs(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:cs(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:jd(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function Od(t){return $d({schema:$i,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,workspace:{projectRoot:Fi.resolve(t.projectRoot),worktreeRoot:Fi.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null},execution:null,checks:[]})}async function Hd(t,e,i={}){let r=$d(e);await yN.mkdir(Fi.dirname(t),{recursive:!0}),await Se(t,r,i)}var Dd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,SN="comet-state.yaml",EN="state.json",PN=`# Outcome
|
|
176
|
+
|
|
177
|
+
# Scope
|
|
178
|
+
|
|
179
|
+
# Non-goals
|
|
180
|
+
|
|
181
|
+
# Acceptance examples
|
|
182
|
+
|
|
183
|
+
# Constraints and invariants
|
|
184
|
+
|
|
185
|
+
# Decisions
|
|
186
|
+
|
|
187
|
+
# Open questions
|
|
188
|
+
|
|
189
|
+
# Verification expectations
|
|
190
|
+
`;function Bd(t,e){if(!Dd.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=Vi.join(t.changesDir,e);if(!L(t.changesDir,i))throw new Error("Native change path escaped");return i}function ls(t,e){return Vi.join(Bd(t,e),SN)}function xN(t,e){return Vi.join(dt(t,e),EN)}async function Ld(t,e){try{let i=await tt.readFile(ls(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function CN(t){return{isolation:t?.isolation??"current",change_branch:t?.changeBranch??null,target_branch:t?.targetBranch??null,finish:null}}function RN(t){return re(t).currentBranch}function AN(t,e){if(!e)return;let i=re(t);if(e.changeBranch!==null&&(!i.isGitWorktree||i.currentBranch!==e.changeBranch))throw new Error(`Native workspace binding ${e.changeBranch??"(missing)"} does not match the current branch ${i.currentBranch??"(detached)"}`);if(e.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Md(t){return ye(t.paths,`create portable change ${t.name}`,async()=>{if(!Dd.test(t.name))throw new Error(`Invalid Native change name: ${t.name}`);t.initialProjectConfig&&await X(t.paths.projectRoot)===null&&await _i(t.paths.projectRoot,t.initialProjectConfig),AN(t.paths.projectRoot,t.workspaceBinding);let e=(await Id(t.paths)).filter(o=>o!==t.name);if(e.length>0)throw new Ft(t.workspaceBinding?.isolation??"current",e);let i=Bd(t.paths,t.name),r=dt(t.paths,t.name);await Promise.all([A(t.paths.nativeRoot,i),A(t.paths.runtimeDir,r)]);let n=!1,a=!1;try{await tt.mkdir(t.paths.changesDir,{recursive:!0}),await tt.mkdir(i,{recursive:!1}),n=!0,await tt.mkdir(t.paths.changesRuntimeDir,{recursive:!0}),await tt.mkdir(r,{recursive:!1}),a=!0,await tt.mkdir(Vi.join(i,"specs"),{recursive:!0}),await te(Vi.join(i,"brief.md"),PN);let o=Mu({name:t.name,language:t.language,workspace:CN(t.workspaceBinding),createdAt:t.now,nextAction:"confirm-shape"});return await Vu(ls(t.paths,t.name),o,{containedRoot:t.paths.nativeRoot}),await Hd(xN(t.paths,t.name),Od({portableState:o,projectRoot:t.paths.projectRoot,branch:RN(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),o}catch(o){throw a&&await tt.rm(r,{recursive:!0,force:!0}),n&&await tt.rm(i,{recursive:!0,force:!0}),o}})}async function Fd(t,e){return Fu(ls(t,e))}import{randomUUID as _N}from"crypto";import{promises as Hn}from"fs";import qd from"path";var us="comet.selection.v2",KR=16*1024;function Wd(t){return qd.join(t,".comet","current-change.json")}function TN(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Vd(t){return t===null||typeof t=="string"}function IN(t){let e;try{e=JSON.parse(t)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!TN(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!Vd(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:us,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==us)throw new Error(`current change selection schema must be ${us}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!Vd(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function zd(t,e){let i=IN(JSON.stringify(e));if(i.legacy)throw new Error("cannot write a legacy current change selection");let r=Wd(t),n=`${r}.${_N()}.tmp`;await Hn.mkdir(qd.dirname(r),{recursive:!0});try{await Hn.writeFile(n,`${JSON.stringify(i.selection,null,2)}
|
|
191
|
+
`,"utf8"),await Hn.rename(n,r)}catch(a){throw await Hn.rm(n,{force:!0}),a}}var aA=16*1024;async function Jd(t,e){return ye(t,`select change ${e}`,async()=>{Tn(e),await Ld(t,e)?await Fd(t,e):await et(t,e),await zd(t.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:e,branch:null})})}import{promises as Dn}from"node:fs";import V from"node:path";import{execFileSync as jN}from"node:child_process";var $N=3e4,ON=8*1024*1024,ds=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function HN(t,e){try{return jN("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:$N,maxBuffer:ON,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new ds(t,e,r)}}function mt(t,e){return HN(t,e).trim()}function Gd(t){return mt(t,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function fs(t,e){mt(t,["check-ref-format","--branch",e])}var vt=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};function Kd(t,e){let i=V.normalize(t),r=V.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Yd(t,e){let i=V.relative(t,e);return i===""||!V.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${V.sep}`)}function Ud(t){return JSON.stringify(t.native)}async function hs(t,e){let i=await X(t);if(i&&e){if(Ud(i)!==Ud(e))throw new Error(`Native worktree configuration differs from the source project: ${V.join(t,".comet","config.yaml")}`);return!1}return!i&&e?(await _i(t,e),!0):!1}async function DN(t,e){if(!Yd(t,e))return!1;let r=`/${V.relative(t,e).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=mt(t,["rev-parse","--git-common-dir"]),a=V.resolve(t,n),o=V.join(a,"info","exclude"),s="";try{s=await Dn.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(r))return!1;await Dn.mkdir(V.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
192
|
+
`)?"":`
|
|
193
|
+
`;return await Dn.appendFile(o,`${c}${r}
|
|
194
|
+
`,"utf8"),!0}function BN(t,e,i){let r=V.resolve(t,i??V.join(".worktrees",e)),n=V.resolve(t,mt(t,["rev-parse","--git-common-dir"]));if(Yd(n,r))throw new Error("Native worktree path cannot be inside the Git common directory");if(nn(t).some(a=>Kd(a,r)))throw new Error(`Native worktree path is already registered: ${r}`);return r}async function LN(t){try{throw await Dn.lstat(t),new Error(`Native worktree path already exists: ${t}`)}catch(e){if(e.code!=="ENOENT")throw e}}async function Xd(t){let e=V.resolve(t.projectRoot);if(t.isolation==="current"){if(t.changeBranch||t.targetBranch||t.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let l=re(e);if(l.isGitWorktree&&l.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:e,binding:{isolation:"current",changeBranch:l.currentBranch,targetBranch:l.currentBranch},preparation:{isolation:"current",projectRoot:e,changeBranch:l.currentBranch,targetBranch:l.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let i=re(e);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let r=t.changeBranch??`comet/${t.name}`;fs(e,r);let n=i.currentBranch===r,a=t.targetBranch??(n?void 0:i.currentBranch);if(!a)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(fs(e,a),!Ii(e,a))throw new Error(`Native target branch is not a verified local branch: ${a}`);if(t.isolation==="branch"){if(t.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let l=!1;if(!n){if(!Gd(e))throw new Error("Native branch isolation requires a clean current working directory");if(Ii(e,r))throw new Error(`Native change branch already exists: ${r}`);mt(e,["switch","-c",r,a]),l=!0}let d;try{d=await hs(e,t.sourceConfig)}catch(u){throw new vt(`Native branch preparation is incomplete: ${u.message}`,{isolation:"branch",projectRoot:e,changeBranch:r,targetBranch:a,worktreePath:null,createdBranch:l,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:u})}return{projectRoot:e,binding:{isolation:"branch",changeBranch:r,targetBranch:a},preparation:{isolation:"branch",projectRoot:e,changeBranch:r,targetBranch:a,worktreePath:null,createdBranch:l,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:d}}}if(n){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let l=t.worktreePath?V.resolve(i.primaryWorktreeRoot,t.worktreePath):void 0;if(l&&!Kd(l,i.currentWorktreeRoot))throw new Error(`Native worktree path ${l} does not match the current worktree ${i.currentWorktreeRoot}`);let d;try{d=await hs(e,t.sourceConfig)}catch(u){throw new vt(`Native worktree preparation is incomplete: ${u.message}`,{isolation:"worktree",projectRoot:e,changeBranch:r,targetBranch:a,worktreePath:e,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:u})}return{projectRoot:e,binding:{isolation:"worktree",changeBranch:r,targetBranch:a},preparation:{isolation:"worktree",projectRoot:e,changeBranch:r,targetBranch:a,worktreePath:e,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:d}}}if(Ii(e,r))throw new Error(`Native change branch already exists: ${r}`);let o=BN(i.primaryWorktreeRoot,t.name,t.worktreePath);await LN(o);let s=await DN(i.primaryWorktreeRoot,o),c={isolation:"worktree",projectRoot:o,changeBranch:r,targetBranch:a,worktreePath:o,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:s,configInitialized:!1};try{mt(i.primaryWorktreeRoot,["worktree","add","-b",r,o,a]),c.createdBranch=!0,c.createdWorktree=!0,c.configInitialized=await hs(o,t.sourceConfig)}catch(l){throw new vt(`Native worktree preparation is incomplete: ${l.message}`,c,{cause:l})}return{projectRoot:o,binding:{isolation:"worktree",changeBranch:r,targetBranch:a},preparation:c}}import vs from"path";var FN=["Outcome","Scope","Non-goals","Acceptance examples"],RA=[...FN,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var VN=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Qd=1024*1024;var ef="scoped-text-safety",qN=1,WN=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var zN="comet.native.checker-policy.v1";var qA=ve(zN,{policy:ef,version:qN,limits:WN,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var JN=["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"],WA=new Set(JN);var KN=Qd,s_=3*KN;var tf={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:[]},XN=Z("comet-native-runtime:v3:scope-reopen"),$_=[{skillVersion:"3",skillHash:Z("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Z("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Z("comet-native-runtime:v1")}];var nf=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],pT=new Set(nf),rb=new Set([...nf,"minimum_runtime_version","revision"]),mT=new Set([...rb,"operation"]),vT=512*1024,nb=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),gT=new Set([...nb,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var bT={maxAcceptanceCriteria:Bu.maxCriteria};var xT={maxSpecs:64,maxFileBytes:on,maxTotalBytes:4*1024*1024};import{execFile as hb}from"node:child_process";import{promisify as pb}from"node:util";var HT={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var rI=512*1024;var qi=class extends Error{recovery;constructor(e,i){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var xI=64*1024;var CI=3600*1e3;var RI=pb(hb);var Bn=class extends Error{details;constructor(e){let i=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=e}};var hj={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var Sj=16*1024*1024,Ej=256*1024,Pj=16*1024;var _j=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var N$=16*1024*1024,Ln=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Mn=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var sf=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],ms=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:sf,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries or inspect the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker]
|
|
195
|
+
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape, a completed skill-coordinated pass, or an explicitly degraded verifier-unavailable fallback before Archive.","--return-to-build Return Verify or Archive to Build after invalidation or user choice.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Implementation changed" --return-to-build','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
196
|
+
comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function ps(t,e){return`${t}:
|
|
197
|
+
${e.map(i=>` ${i}`).join(`
|
|
198
|
+
`)}`}function Nb(t){let e=t.filter(r=>r!=="--help");if(e.length===0)return"";let i=e.slice(0,2).join(" ");return ms[i]||e.length>1&&ms[e[0]]?.subcommands?i:e[0]}function bb(t=[]){let e=Nb(t),i=ms[e];if(!i)throw new Error(`Unknown Native help topic: ${e}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",ps("Commands",i.subcommands));let n=e===""?i.options:[...i.options??[],...sf];return n&&n.length>0&&r.push("",ps("Options",n)),r.push("",`Output:
|
|
199
|
+
${i.output}`),i.examples&&r.push("",ps("Examples",i.examples)),e===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:e,usage:`${r.join(`
|
|
200
|
+
`)}
|
|
201
|
+
`}}var kb=bb().usage;var $$=10*1024*1024,Ne=class extends Error{};function lf(t,e){let i=t.flatMap((r,n)=>r===e?[n]:[]);if(i.length>1)throw new Ne(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function it(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new Ne(`${e} may only be provided once`);if(i.length===0)return;let r=i[0],n=t[r+1];if(n===void 0||n.startsWith("--"))throw new Ne(`${e} requires a value`);return t.splice(r,2),n}function uf(t){if(t.length>0)throw new Ne(`Unexpected argument: ${t[0]}`)}function df(t,e){let i=t.shift();if(!i||i.startsWith("--"))throw new Ne(`${e} is required`);return i}function ff(t,e="en"){let i=it(t,"--language")??e;if(i!=="en"&&i!=="zh-CN")throw new Ne("--language must be en or zh-CN");return i}function cf(t,e){let i=vs.normalize(t),r=vs.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Sb(t){let e=vs.resolve(t),i=re(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return e;let r=re(e);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!cf(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||cf(i.currentWorktreeRoot,r.currentWorktreeRoot)?e:i.currentWorktreeRoot}async function hf(t){return t?Sb(t):$o(process.cwd())}function pf(t,e,i){return{command:t,exitCode:0,data:e,text:i??JSON.stringify(e,null,2)+`
|
|
202
|
+
`}}function mf(t,e){if(e instanceof Ne)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof Ln)return{command:t,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof Mn)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof An)return{command:t,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof Ft)return{command:t,exitCode:73,data:{requestedIsolation:e.requestedIsolation,activeChanges:e.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:e.message}};if(e instanceof vt)return{command:t,exitCode:73,data:{preparation:e.preparation},error:{code:"workspace-preparation-incomplete",message:e.message}};if(e instanceof _n)return{command:t,exitCode:65,data:{change:e.change,complete:!1,omittedCount:e.omittedCount,omittedByReason:e.omittedByReason,samplePaths:e.samplePaths,sampleTruncated:e.sampleTruncated,effectiveLimits:e.effectiveLimits,policyHash:e.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:e.message}};if(e instanceof Bn)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof qi)return{command:t,exitCode:65,data:e.recovery,error:{code:"implementation-scope-stale",message:e.message}};if(e instanceof Error){let i=e.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:t,exitCode:70,error:{code:"internal",message:e.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function vf(t,e){return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
|
|
203
|
+
`}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function gf(t,e){let i=df(t,"change name"),r=await X(e),n=ff(t,r?.native.language??"en"),a=it(t,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new Ne("--isolation must be current, branch, or worktree");let o=it(t,"--change-branch"),s=it(t,"--target-branch"),c=it(t,"--worktree-path");uf(t);let l=r;if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete`);let d=await Xd({projectRoot:e,name:i,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{},...c?{worktreePath:c}:{},sourceConfig:l});e=d.projectRoot,r=await X(e);let u=r===null?ku("docs",n):void 0;if(r||(r=u),r.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete`);let f=await $t(e,r.native.artifact_root);await Nu(f);let p=await Md({paths:f,name:i,language:n,workspaceBinding:d.binding,...u?{initialProjectConfig:u}:{}});return await Jd(f,p.name),pf("new",{...p,preparation:d.preparation,continuation:Su(p)},`Created Native change ${p.name}
|
|
204
|
+
`)}function Eb(t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
|
|
205
|
+
`}}async function wf(t,e,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s,c;try{lf(n,"--json"),s=it(n,"--project-root");let d=[...n,...a],u=await hf(s);c=await e(d,u)}catch(d){c=mf(t,d)}let l=o?Eb(c):vf(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
|
|
199
206
|
`)?"":`
|
|
200
|
-
`)),l.exitCode}process.exitCode=await
|
|
207
|
+
`)),l.exitCode}process.exitCode=await wf("new",gf);
|